diff --git a/.editorconfig b/.editorconfig index 361b867b1..73050d175 100644 --- a/.editorconfig +++ b/.editorconfig @@ -23,3 +23,69 @@ tab_width = 4 [*.{xml,csproj}] indent_style = space indent_size = 2 + +# From https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference +# and https://github.com/dotnet/roslyn/blob/master/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs +[*.cs] +dotnet_style_qualification_for_field = true:warning +dotnet_style_qualification_for_property = true:warning +dotnet_style_qualification_for_method = true:warning +dotnet_style_qualification_for_event = true:warning +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = false:warning +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_coalesce_expression = true:warning +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion +dotnet_sort_system_directives_first = true +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = true +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = true +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_parentheses = expressions,type_casts,control_flow_statements +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_cast = false +csharp_space_around_declaration_statements = true +csharp_space_before_open_square_brackets = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_square_brackets = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_semicolon_in_for_statement = true +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_around_binary_operators = true +csharp_indent_braces = false +csharp_indent_block_contents = true +csharp_indent_switch_labels = true +csharp_indent_case_contents = true +# See https://github.com/dotnet/roslyn/blob/d4dab355b96955aca5b4b0ebf6282575fad78ba8/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs +csharp_indent_case_contents_when_block = false +csharp_indent_labels = false +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Disabled for Unity compatibility until 2017.1 RTM +[*.cs] +dotnet_style_null_propagation = false:warning +csharp_style_expression_bodied_methods = false:warning +csharp_style_expression_bodied_constructors = false:warning +csharp_style_expression_bodied_operators = false:warning +csharp_style_expression_bodied_properties = false:warning +csharp_style_expression_bodied_indexers = false:warning +csharp_style_expression_bodied_accessors = false:warning +csharp_style_pattern_matching_over_is_with_cast_check = false:warning +csharp_style_pattern_matching_over_as_with_null_check = false:warning +csharp_style_inlined_variable_declaration = false:warning +csharp_style_throw_expression = false:warning +csharp_style_conditional_delegate_call = false:warning diff --git a/.nuget/NuGet.exe b/.nuget/NuGet.exe index 31fc9885e..83ead7a4d 100644 Binary files a/.nuget/NuGet.exe and b/.nuget/NuGet.exe differ diff --git a/CHANGES.txt b/CHANGES.txt index 2cba1f26f..9dffa6710 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -438,11 +438,15 @@ Release 0.7.0-alpha3 2016/05/22 IMPROVEMENTS * Improve .NET Core support with work around for corefx GetInterfaceMap() limitation. .NET Core build requires RC2 or above. * Improve Unity support. Unity DLLs now support IL2CPP with various AOT issue workarounds. Unity build requires 5.3.5f1 or above. + * DateMemberAttribute matching is now name based instead of type based. NEW FEATURES * SerializerGenerator.GenerateSerializerCodeAssembly now supports custom namespace. Issue #138. + * Add IgnoreDataMemberAttribute to ignoring member indicators. Issue #146. BUG FIXES + * Fix explicit IPackable/IUnpackable interface implementation causes serializer generator error. Issue #150. + * Fix non-public collection typed members with attributes causes serialization generation error. Issue #152. * Fix generated serializer codes are not available in WinRT/UWP because of reflection API incompatibility when the type has non-public and explicitly marked fields/properties. * Fix collection only implements IEnumerable may cause NotSupportedException. * Fix hidden by signature members ("new" in C#) causes invalid serializer code generation. Issue/PR #147, #161, #162. @@ -479,12 +483,33 @@ Release 0.7-beta2 - 2016/06/26 BUG FIXES * Fix type initializer causes InvalidOperatiionException of serializer generation on WinRT projects. #170. - * Fix package dependency issue prevents *-aot runtime cannot install MsgPack.Cli packages (effects 0.7.0-beta1 only). - * Fix Xamarin iOS AOT releated bugs (effects 0.7.0-beta1 only). + * Fix package dependency issue prevents *-aot runtime cannot install MsgPack.Cli packages (affects 0.7.0-beta1 only). + * Fix Xamarin iOS AOT releated bugs (affects 0.7.0-beta1 only). -Release 0.7 (planned) + BREAKING CHANGES + * netstandard1.1 and 1.3 now do NOT support code generation (Reflection.Emit) based serializer (affects 0.7.0-alpha/beta only). + +Release 0.7-RC1 2016/06/29 + + This release supports .NET Core 1.0 final. + + BREAKING CHANGES + * netstandard 1.1 now do NOT support System.DBNull because System.Data.Common final package supports only >=1.2 (affects 0.7.0-alpha/beta only). + * mpu.exe now works on .NET 4.6.1. + + IMPROVEMENTS + * The type which implement IEnumerable but does not implement Add now supported. Issue #169. + This behavior can be disabled with setting SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes to false. + * mpu.exe and SerializerGenerator now supports compatibility switches. + + BUG FIX + * Fix batch serializer code generation may report invalid error message due to context reset leaking. + * Fix reflection based serializer possibly throws NotSupportedException instead of SerializationException. + +Release 0.7 2016/07/03 This release includes 0.6.8 fixes. Here are cumulative changelogs from 0.6.8. + (There are no changes from 0.7.0-rc1) MAJOR BREAKING CHANGES * PackerCompatibilityOptions.None is now default. This means that msgpack bin or str8 formats are used by default. @@ -495,6 +520,7 @@ Release 0.7 (planned) * Unity without IL2CPP (a.k.a. AOT) is no longer supported. * IPackable/IUnpackable is respected for collections now. Issue #153. This behavior can be disabled by setting SerializationCompatibilityOptions.IgnorePackabilityForCollection to true. + * mpu.exe now works on .NET 4.6.1. TRIVIAL BREAKING CHANGES * Generated serializers code has different structure, it might break your custom toolset which depends generated code structure. @@ -507,8 +533,8 @@ Release 0.7 (planned) * Add buffering option for Packer/Unpacker which can be enabled by PackerUnpackerStreamOptions.WithBuffering = true. It should improve performance for non-buffered stream like NetworkStream. * Async support. Issue #49. Note that it is highly recommended to use buffering feature of Packer or Unpacker factory methods to avoid too chutty asynchronous I/O call. In addition, async API may avoid unnecessary blocking but it is not so efficienty in most cases. * SerializerGenerator.GenerateSerializerCodeAssembly now supports custom namespace. Issue #138. - * Add .NET Core support. .NET Core build requires RC2 or above. - * Unity I+2CPP support. Unity DLLs now support IL2CPP with various AOT issue workarounds. Unity build requires 5.3.5f1 or above. + * Add IgnoreDataMemberAttribute to ignoring member indicators. Issue #146. + * Unity IL2CPP support. Unity DLLs now support IL2CPP with various AOT issue workarounds. Unity build requires 5.3.5f1 or above. * Xamarin iOS linker support. IMPROVEMENTS @@ -517,16 +543,227 @@ Release 0.7 (planned) * Move throw statements from hot-path to improve performance a bit. * Generated serializer now always check SerializationContext.SerializationMethod when they serialize objects. No longer need to re-generate serializer codes/assemblies to switch serialization method between array and map. * Generated code now more structured which improves debuggability, it also remove some redundant expressions. + * DateMemberAttribute matching is now name based instead of type based. + * The type which implement IEnumerable but does not implement Add now supported. Issue #169. + This behavior can be disabled with setting SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes to false. + * mpu.exe and SerializerGenerator now supports compatibility switches. BUG FIXES * Fix Unpacker.Skip failes when the stream is fragmented such as raw NetworkStream. * Fix generated serializer codes are not available in WinRT/UWP because of reflection API incompatibility when the type has non-public and explicitly marked fields/properties. + * Fix explicit IPackable/IUnpackable interface implementation causes serializer generator error. Issue #150. + * Fix non-public collection typed members with attributes causes serialization generation error. Issue #152. * Fix collection only implements IEnumerable may cause NotSupportedException. * Fix hidden by signature members ("new" in C#) causes invalid serializer code generation. Issue/PR #147, #161, #162. * IPackable/IUnpackable is respected for collections now. Issue #153. * Fix the Unpacker always returns 0 when the underlying stream has double typed value. * Fix MessagePackObject.PackToMessage does not look PackerCompatibilityOptions. Issue #168. * Fix type initializer causes InvalidOperatiionException of serializer generation on WinRT projects. #170. + * Fix batch serializer code generation may report invalid error message due to context reset leaking. + * Fix reflection based serializer possibly throws NotSupportedException instead of SerializationException. KNOWN ISSUES * Reflection based serializers in Unity build is not stable even if you specify [Preserve] and/or link.xml. + +Release 0.7.1 2016/7/10 + + BUG FIXES + * Relaxes .NET Framework version. .NET 4.5.0, 4.5.1, 4.6.0 are resupported. Issue #176. + * Reduce memory allocation. Issue #179. + +Release 0.8.0 beta 2016/07/24 + + BREAKING CHANGES + * `MessagePackDeserializationConstructorAttribute` now always used when the type has default constructor. + The previous behavior was bug as XML documentatino said. + + NEW FEATURES + * Null member skipping in map based serialization. + This behabvior must be enabled via `SerializationContext.DictionarySerializationOptions.OmitNullEntry`. + Issue #136. + * Dictionary key transformation via `SerializationContext.DictionarySerializationOptions.KeyTransformer`. + Built in transformer is placed in `DictionaryKeyTransoformers`. + Issue #175. + * Add F# collections support. Related to issue #178. + + BUG FIXES + * Fix `MessagePackDeserializationConstructorAttribute` is ignored when the type has default constructor. + * Make Xamarin.iOS unified API compliant. Issue #181. + * Fix `mpu.exe -l`. + + IMPROVEMENTS + * Relax constructor based deserialization condition. It will be used even if there are any settable members(including private property setters). Part of issue #178 and fixes issue #135. + * PackHelpers and UnpackHelpers APIs are now backward compatible. + +Release 0.8.0 + + Nothing from 0.8.0 beta. + +Release 0.8.1 2017/02/02 + + BUG FIXES + * Fix null items of complex type in List or Dictionary will not be deserialized as null. Issue #211. + +Release 0.9.0 beta1 2016/09/24 + + NEW FEATURES + * Enum name transformation via `SerializationContext.EnumSerializationOptions.NameTransformer`. + Built in transformer is placed in `EnumTransoformers`. + Issue #184. + * Polymorphic attributes now supports type qualification. Issue #171. + * Runtime type polymorphism now supports name based type verification. This feature allows to prevent loading malicious or unknown types ibefore assembly loading. + * Asymmetric serializers. You can generate "pack only" serializer when you set SerializationContext.CompabilityOptions.AllowAsymmetricSerializer to true. #68. + * Built in serializer for System.Text.StringBuilder now supports UnpackTo. + * Add serialization to/from MessagePackObject as extension methods of MessagePackSerializer and MessagePackSerializer. Issue #90 + + BUG FIXES + * Fix nuspec to prevent old NuGet clients which do not support .NET Standard TFMs. Issue #177. + +Release 0.9.0 beta2 2017/2/12 + + NEW FEATURES + * Users of serializer code generator API can specify TextWriter to output. This may improve tooling chain. + * Users of serializer code generator API can suppress [DebuggerNonUserCode] attribute to enable debugger step in. + * SerializerRepository API now expose ContainsFor and GetRegisteredSerializers methods to investigate registered serializers. + * SerializationContext.DisablePrivilegedAccess for restricted environment like Silverlight to select between granting permission or relinquish non-public access. + * UWP build is now included. + + BUG FIXES + * The generated code for the type which has Tuple typed member uses old PackHelper API. + * Fix struct deserialization. Issue #189. Thank you @samcragg! + * Fix asynchronous packing is not be emitted correctly. Issue #201 + * Fix SerializerCodeGenerator does not handle collections correctly for IsRecursive = true. Issue #203 + * Fix extra field causes IndexOutOfBoundException when reflection based serializers are used. Issue #199 + * Fix some built-in serializers throws InvalidOperationException instead of SerializationException for type errors. Issue #204 + * Fix a combination of readonly members and collection members incorrect code generation when the type also have deserialization constructor. Issue #207. + * Fix built-in collection serializers such as List serializer causes SecurityException when the program run in restricted environment like Silverlight. Issue #205. + * Fix null items of complex type in List or Dictionary will not be deserialized as null. Issue #211. (from 0.8.1) + * Fix types which implement IPackable and IUnpackable but do not have any members cannot be serialized. Issue #202 + * Fix Windows Native build error. Issue #206. + +Release 0.9.0 RC1 2017-08-13 + + NEW FEATURES + * ByteArrayPacker/ByteArrayUnpacker. They are suitable for fixed pattern serialization/deserialization. + * Fast mode of unpacker which omits nested collection management. This option can be disabled with setting UnpackerOptions.ValidationLevel to ValidationLevel.Collection. + + IMPROVEMENTS + * Byte array based serialization API now uses ByteArrayPacker/ByteArrayUnpacker, improves about 40% faster than Stream based. + * Deserialization now uses ValidationLevel.None, improves about 30% faster than validating one. + * Packer/Unpacker performance improvements about 10-20%. As a result, new byte array "fast" unpacker is about 3x faster than previous unpacker. + + BUG FIXES + * Fix constructor deserialization fails if the constructor parameters order is not lexical. Issue #233 + * Fix asynchronous multi dimensional array deserialization corruption. + * Fix enum serialization throws NullReferenceException in Unity. Issue #215. + * Fix MessagePackSerializer.Capability does not work correctly in Unity. + * Fix polymorphic serializer error in Unity. + +Release 0.9.0 2017-8-26 + + NEW FEATURES + * Enum name transformation via `SerializationContext.EnumSerializationOptions.NameTransformer`. + Built in transformer is placed in `EnumTransoformers`. + Issue #184. + * Polymorphic attributes now supports type qualification. Issue #171. + * Runtime type polymorphism now supports name based type verification. This feature allows to prevent loading malicious or unknown types ibefore assembly loading. + * Asymmetric serializers. You can generate "pack only" serializer when you set SerializationContext.CompabilityOptions.AllowAsymmetricSerializer to true. #68. + * Built in serializer for System.Text.StringBuilder now supports UnpackTo. + * Add serialization to/from MessagePackObject as extension methods of MessagePackSerializer and MessagePackSerializer. Issue #90 + * Users of serializer code generator API can specify TextWriter to output. This may improve tooling chain. + * Users of serializer code generator API can suppress [DebuggerNonUserCode] attribute to enable debugger step in. + * SerializerRepository API now expose ContainsFor and GetRegisteredSerializers methods to investigate registered serializers. + * SerializationContext.DisablePrivilegedAccess for restricted environment like Silverlight to select between granting permission or relinquish non-public access. + * UWP build is now included. + * ByteArrayPacker/ByteArrayUnpacker. They are suitable for fixed pattern serialization/deserialization. + * Fast mode of unpacker which omits nested collection management. This option can be disabled with setting UnpackerOptions.ValidationLevel to ValidationLevel.Collection. + + IMPROVEMENTS + * Byte array based serialization API now uses ByteArrayPacker/ByteArrayUnpacker, improves about 40% faster than Stream based. + * Deserialization now uses ValidationLevel.None, improves about 30% faster than validating one. + * Packer/Unpacker performance improvements about 10-20%. As a result, new byte array "fast" unpacker is about 3x faster than previous unpacker. + + BUG FIXES + * Fix nuspec to prevent old NuGet clients which do not support .NET Standard TFMs. Issue #177. + * The generated code for the type which has Tuple typed member uses old PackHelper API. + * Fix struct deserialization. Issue #189. Thank you @samcragg! + * Fix asynchronous packing is not be emitted correctly. Issue #201 + * Fix SerializerCodeGenerator does not handle collections correctly for IsRecursive = true. Issue #203 + * Fix extra field causes IndexOutOfBoundException when reflection based serializers are used. Issue #199 + * Fix some built-in serializers throws InvalidOperationException instead of SerializationException for type errors. Issue #204 + * Fix a combination of readonly members and collection members incorrect code generation when the type also have deserialization constructor. Issue #207. + * Fix built-in collection serializers such as List serializer causes SecurityException when the program run in restricted environment like Silverlight. Issue #205. + * Fix null items of complex type in List or Dictionary will not be deserialized as null. Issue #211. (from 0.8.1) + * Fix types which implement IPackable and IUnpackable but do not have any members cannot be serialized. Issue #202 + * Fix Windows Native build error. Issue #206. + * Fix constructor deserialization fails if the constructor parameters order is not lexical. Issue #233 + * Fix asynchronous multi dimensional array deserialization corruption. + * Fix enum serialization throws NullReferenceException in Unity. Issue #215. + * Fix MessagePackSerializer.Capability does not work correctly in Unity. + * Fix polymorphic serializer error in Unity. + +Release 0.9.1 2017-8-30 + + BUG FIXES + * Fix ByteArrayPacker throws IndexOutOfBoundException when the buffer remaining bytes is equal to packed scalar size. #252 + +Release 0.9.2 2017-09-26 + + BUG FIXES + * Fix UAP build drop does not exists in nupkg. #186 + +Release 1.0.0-beta1 2017-10-01 + + NEW FEATURES + * .NET Standard 2.0 which supports serializer source code generation on .NET Core. Note that serializer assembly generation is not supported. + * MessagePackSerializer.UnpackMessagePackObject(byte[]) utility method. + * MessagePack timestamp type support. This includes interoperability with DateTime/DateTimeOffset as well as MsgPack.Timespan type with basic arithmatics, properties, and conversions. + + BUG FIXES + * Fix ByteArrayPacker throws IndexOutOfBoundException when the buffer remaining bytes is equal to packed scalar size. #252 + * Fix UAP build drop does not exists in nupkg. #186 + * Fix new unpacker cannot unpack reserved ext types. + +Relase 1.0.0-beta2 2017-10-29 + + CHANGES + * Xamarin builds are now integrated to .NET Standard 2.0. + + NEW FEATURES + * ValueTuple support. #277 + + IMPROVEMENTS + * System.Tuple detection now ignores their declaring assemblies. + * Improve exception message in AOT error of Unity. + * .NET Standard 1.1/1.3 projects now do not depend on System.Linq.Expressions package. + +Release 1.0.0-rc1 2017-12-17 + + BUG FIXES + * Fix NRE in .NET Standard 1.1/1.3 build (this issue got mixed in beta2). + * Fix built-in Guid/BigInteger always output raw type even if PackerCompatibilityOptions.PackBinaryAsRaw is not specified. #270 + * Fix MessagePackObject.UnderlyingType reports wrong type for ext types. Part of #269. + This bug also caused misleading error message for incompatible type conversion. + * Fix exceptions thrown by MessagePackObject.AsBinary()/AsString() reports internal type name. Part of #269. + +Release 1.0.0 2018-6-14 + + BUG FIXES + * [NonSerialized] attribute does not effect in Mono based platform including Unity. + * Fix map keys order emitted by asymmetric (serialization only) serializer are inconsistent across platform. + * Fix Unity build does not honor serialization related attributes correctly. + * Fix internal inconsitency between serialization related attributes detection and their parameter retrieval. + +Release 1.0.1 2018-09-09 + + BUG FIXES + * Fix conversion from DateTime[Offset] to Timestamp failure for before Unix epoc. #296 + +Release 1.1 + + BUG FIXES + * Fix conversion from DateTime[Offset] to Timestamp failure for before Unix epoc. #296 (port from 1.0.x branch) + + NEW FEATURE + * Allow programatically ignoring arbitary members via BindingOptions. Thank you @ShrenikOne #282 + * To prevent accidental Timestamp serialization in existing code, SerializationContext.ConfigureClassic(SerializationCompatibilityLevel) and SerializationContext.CreateClassicContext(SerializationCompatibilityLevel) are added. #296 diff --git a/CONTRIBUTIONS.md b/CONTRIBUTIONS.md index 33384bf5e..2f4de626c 100644 --- a/CONTRIBUTIONS.md +++ b/CONTRIBUTIONS.md @@ -1,41 +1,58 @@ -# Contributions +Contributions Guidelines +==== -## You can contribute... +Executive Summary +---- -* Submit issues in github. But please ensure that your question is already described in wiki() or samples() +* Let's contribute. +* Make red-green test for code. + +You can contribute... +---- + +* Submit issues in github. But please ensure that your question has not beeny described in wiki or samples. * Pull-request. Note that your request might be rejected if it break existing test or it become applicable because of other fix(es). -* Write wiki (documentation request in github issues is OK, but please note that telling why/what documentation needed is harder than code, so it is happy if you write the purpose and example for the request). +* Write wiki. +* Create samples. +* Request documentation / samples. +* Report articles you found or written. * Improve unit tests more efficiently. -* Patches for English are welcome :) +* Patches for English text. +* New platform support including Xamarin Mac, Compact Framework, Micro Framework, etc. +* Improve tools. * etc. -## Branching +Branching +---- MessagePack for CLIs branches are: -* Version branch for every *.n release. Active branch is the latest minor version having release tags. -** If the latest version branch does not have any tags, so it is developing branch. -* Mater branch is synchronized with active branch when the new release is done. -** You should submit pull-request for active branch. It will be merged newest develop branch and master branch in the future. +* Version branch for every major/minor release for bug fixes. Active branch is the latest minor version. +* Master branch which contains next major/minor release. +* Some ephemeral WIP branches. Do not send PR for WIP branch. -## Guidelines +Guidelines +---- ### General Style * Keep backward compatibility for published API. * Write Unit test for APIs, and optinally stable/complex internal module. -* Think interoperability. If you want full-feature serializer only working on .NET, use `BinaryFormatter`. Interoperability for many languages is advantage of MessagePack. +* Think interoperability. If you want full-feature serializer only working on .NET, use `BinaryFormatter`. Interoperability for many languages is advantage of MessagePack. ### Coding Style -Follow existing styles, period. Please keep existing style because changing style is not so valuable, and out times should be spent to improve software itself unless the coding style causes observable and measurable impact. +Follow existing styles, period. Please keep existing style because changing style is not so valuable, and out times should be spent to improve software itself unless the coding style causes observable and measurable impact. +If you modify existing source, watch above/bellow lines and use their styles. +If you put new source, you should follow bellow guidelines, but I don't think fixing your new file is more valuable than your life as long as it has reasonable readability. So, keep consistant in your new source file. #### Commonly Used Styles + These rules are commonly acceptted rules I think, so I omit their rationale. -* Published APIs follows Framework Design Guidelines. See, T.B.D. This rule can be checked by FxCop (CodeAnasys feature in VS). +* Published APIs follows Framework Design Guidelines. The digest is [here](https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/framework-design-guidelines-digest.md). This rule can be checked by FxCop (CodeAnasys feature in VS). * Allman style. * Locals uses camelCasing, fields uses camelCasing precding underscore like '_foo'. -** Note that 's_', 'm_', 't_' prefixes are not used. + * Note that 's_', 'm_', 't_' prefixes are currently not used. * All methods are PascalCasing even if they are private. camelCasingName(...) expression should be delegate invocation except P/Invoke. #### Specific Styles @@ -43,25 +60,59 @@ These rules are commonly acceptted rules I think, so I omit their rationale. These rules are not so common (at least, they are differ from .NET Core/Mono style), so I should describe their reason: * Specify 'this' keyword to distinguish instance fields and static fields. I think [TheradStatic] and ThreadLocal is rare than mutable statics, so these should be distinguished by field name like `xxxPerThread`. -* Use PascalCasing for private constants. In reality, I do not have policy for this, just following R# default. +* Use PascalCasing for private constants. * Put braces even if the statement is single line. It is multi-layer guard for a little but destroying bug. * Use tab for indentation. Most tools supports tabs, developer can be configure spacing for a tab usually, code formatting tools act better for tab. * Verbose spacing. It is a kind of multi-layer guard. -OK, use formatting files below: -* Visual Studio - ### Unit Testing -* Please write unit testing to verify your reported issue is reproduced and solved. +* Please write unit tests to verify your reported issue is reproduced and solved. * If you add new feature, write unit testing with testing methodology like border value analysis. -## Trouble Shooting +How To +---- + +### Add New File for Various Projects + +#### Add the File for All Project with the Tool + +MessagePack for CLI has various projects to support multiple platforms, so there is a tool to synchronize project assets -- `SyncProjects`. +This tool is located in `tools/SyncProjects`, simple XLinq based tool. +If you add new file to the project, run `SyncProjects` as following: + +* If the file should be work in all platforms, just run `SyncProjects.bat`. + * If you work on *nix shell, use `view` and `source` to run the exe. +* If the file should not be work in some platforms, edit `Sync.xml` and/or `Sync.Test.xml`. + * This file defines that given project should be copied from another project. + * This file also defines exclusion and preservation. + By default, the tool synchronize all source inclusion from base project. + If the preservation is specified, the file will be preserved on synchronized project. + +If you think this is messy, let's post pull request anyway. +It will be postponed one or some weeks, but it will be merged if the fix is valid and contains red-green testing. + +#### Add Test Cases for Serializer Generation + +**TODO:** + +Solution Organizations +---- + +* **MsgPack.sln** contains CLR 4 based projects. This is primary platform. +* **MsgPack.compat.sln** contains CLR 2 based projects, specifically .NET 3.5 and Unity, and the `mpu` tool. + These projects are separated because Visual Studio cannot load multiple CLRs for unit testing at a time. +* **MsgPack.Windows.sln** contains Windows specific projects, namely Silverlight5, UWP, Windows Phone. + This solution also contains test projects for .NET Core build because most stable .NET Standard implementations are WinRT/UWP. + These projects are separated because non-Windows users cannot open them. +* **MsgPack.Xamarin.sln** contains Xamarin Android and Xamarin iOS projects. + These projects are separated because of license requirements. +* **MsgPack.Xamarin.sln** contains Xamarin Android and Xamarin iOS projects. + These projects are separated because of license requirements. +* There are no solutions for .NET Core/.NET Standard Libraries. There is a `project.json` under `src/netstandard` directory. + +FAQ +---- * Q: I cannot build MsgPack.compat.sln on Mono w/ xbuild error. ** A: Currently, this issue is not trucked, so use msbuild.exe to build unity lib and/or .NET 3.5 port. - -* Q: I cannot run Windows Phone unit tests. -** A: The tool looks like not so stable, but you ensure that: -*** Recent Visual Studio Update is applied -*** And recent Windows Phone Tools are applied http://www.microsoft.com/en-us/download/details.aspx?id=43719 \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..06e5a5521 Binary files /dev/null and b/Directory.Build.props differ diff --git a/MsgPack.Common.props b/MsgPack.Common.props new file mode 100644 index 000000000..9a83c5d65 --- /dev/null +++ b/MsgPack.Common.props @@ -0,0 +1,108 @@ + + + + Properties + MsgPack + TRACE + prompt + 4 + AnyCPU + false + $(SolutionDir)\src\MsgPack.snk + true + false + true + portable + + + true + false + bin\Debug\ + $(DefineConstants);DEBUG;SKIP_LARGE_TEST + + + true + bin\Release\ + + + bin\Instrument\ + true + true + true + + + bin\CodeAnalysis\ + true + false + false + + + + + $(DefineConstants);__MOBILE__;AOT;XAMARIN + $(VsInstallRoot)\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\ + true + true + true + + + true + + + $(DefineConstants);__ANDROID__ + MonoAndroid + v1.0 + + + $(DefineConstants);__IOS__ + Xamarin.iOS + v1.0 + + + $(DefineConstants);NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;AOT + + + + + $(AssemblyName).XML + + + $(OutputPath)\$(TargetFramework)\$(AssemblyName).XML + + + + + pdbonly + + + + + $(DefineConstants);FEATURE_TAP + true + + + $(DefineConstants);FEATURE_CONCURRENT + + + $(DefineConstants);FEATURE_POINTER_CONVERSION + + + $(DefineConstants);FEATURE_EMIT + true + + + $(DefineConstants);FEATURE_CODEGEN + true + + + $(DefineConstants);FEATURE_ASMGEN + true + + + $(DefineConstants);FEATURE_MEMCOPY + + + + full + + diff --git a/MsgPack.Windows.sln b/MsgPack.Windows.sln index 69cd979e9..0474bd60e 100644 --- a/MsgPack.Windows.sln +++ b/MsgPack.Windows.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 +VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "common", "common", "{60EC42E9-D79B-4ADF-8F80-4DCD580061FD}" ProjectSection(SolutionItems) = preProject @@ -50,12 +50,20 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".NET Standard", ".NET Stand EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Uwp", "src\MsgPack.Uwp\MsgPack.Uwp.csproj", "{9D65A105-FB03-40DB-9185-8C695B8EE8D6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetStandardProjectBuilder", "src\netstandard\build\NetStandardProjectBuilder.csproj", "{A1B322FC-AA39-4894-AFA8-AB427A3FBA09}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Uwp", "test\MsgPack.UnitTest.Uwp\MsgPack.UnitTest.Uwp.csproj", "{0F930636-458B-401F-9EAF-F4F05E93BCC9}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Uwp.Aot", "test\MsgPack.UnitTest.Uwp.Aot\MsgPack.UnitTest.Uwp.Aot.csproj", "{E4CA9866-6234-49D4-8CDF-1F3A21EFD138}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Silverlight.5", "test\MsgPack.UnitTest.Silverlight.5\MsgPack.UnitTest.Silverlight.5.csproj", "{17D0F223-E156-42CF-ACA8-815733FE094F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunit.framework-sl-5.0", "test\NUnitLite\NUnitFramework\framework\nunit.framework-sl-5.0.csproj", "{3DEB15F9-E7DA-403F-B6D3-A8499310397F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-sl-5.0", "test\NUnitLite\NUnitFramework\nunitlite\nunitlite-sl-5.0.csproj", "{0A5F920A-1BF5-4DAC-B799-0C618B203797}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Silverlight.5.FullTrust", "test\MsgPack.UnitTest.Silverlight.5.FullTrust\MsgPack.UnitTest.Silverlight.5.FullTrust.csproj", "{26A3F930-FDAF-4886-9111-D326A6F68E82}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetStandardProjectBuilder", "src\netstandard\build\NetStandardProjectBuilder.csproj", "{A1B322FC-AA39-4894-AFA8-AB427A3FBA09}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution CodeAnalysis|Any CPU = CodeAnalysis|Any CPU @@ -377,49 +385,12 @@ Global {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|Any CPU.Build.0 = Release|Any CPU {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|ARM.ActiveCfg = Release|ARM {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|ARM.Build.0 = Release|ARM - {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|x64.ActiveCfg = Release|x64 {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|x64.Build.0 = Release|x64 {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|x86.ActiveCfg = Release|x86 {9D65A105-FB03-40DB-9185-8C695B8EE8D6}.Release|x86.Build.0 = Release|x86 - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|ARM.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x64.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x86.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|ARM.ActiveCfg = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|ARM.Build.0 = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x64.ActiveCfg = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x64.Build.0 = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x86.ActiveCfg = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x86.Build.0 = Debug|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|ARM.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x64.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x86.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Any CPU.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|ARM.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|ARM.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x64.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x64.Build.0 = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x86.ActiveCfg = Release|Any CPU - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x86.Build.0 = Release|Any CPU {0F930636-458B-401F-9EAF-F4F05E93BCC9}.CodeAnalysis|Any CPU.ActiveCfg = Release|x64 {0F930636-458B-401F-9EAF-F4F05E93BCC9}.CodeAnalysis|Any CPU.Build.0 = Release|x64 {0F930636-458B-401F-9EAF-F4F05E93BCC9}.CodeAnalysis|Any CPU.Deploy.0 = Release|x64 @@ -524,6 +495,202 @@ Global {E4CA9866-6234-49D4-8CDF-1F3A21EFD138}.Release|x86.ActiveCfg = Release|x86 {E4CA9866-6234-49D4-8CDF-1F3A21EFD138}.Release|x86.Build.0 = Release|x86 {E4CA9866-6234-49D4-8CDF-1F3A21EFD138}.Release|x86.Deploy.0 = Release|x86 + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|ARM.ActiveCfg = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|ARM.Build.0 = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|x64.ActiveCfg = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|x64.Build.0 = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|x86.ActiveCfg = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Debug|x86.Build.0 = Debug|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|x64.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.PerformanceTest|x86.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|Any CPU.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|ARM.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|ARM.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|x64.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|x64.Build.0 = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|x86.ActiveCfg = Release|Any CPU + {17D0F223-E156-42CF-ACA8-815733FE094F}.Release|x86.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|ARM.ActiveCfg = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|ARM.Build.0 = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|x64.ActiveCfg = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|x64.Build.0 = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|x86.ActiveCfg = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Debug|x86.Build.0 = Debug|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|x64.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.PerformanceTest|x86.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|Any CPU.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|ARM.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|ARM.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|x64.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|x64.Build.0 = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|x86.ActiveCfg = Release|Any CPU + {3DEB15F9-E7DA-403F-B6D3-A8499310397F}.Release|x86.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|ARM.ActiveCfg = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|ARM.Build.0 = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|x64.ActiveCfg = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|x64.Build.0 = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|x86.ActiveCfg = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Debug|x86.Build.0 = Debug|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|x64.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.PerformanceTest|x86.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|Any CPU.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|ARM.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|ARM.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|x64.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|x64.Build.0 = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|x86.ActiveCfg = Release|Any CPU + {0A5F920A-1BF5-4DAC-B799-0C618B203797}.Release|x86.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|Any CPU.Build.0 = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|ARM.ActiveCfg = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|ARM.Build.0 = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|x64.ActiveCfg = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|x64.Build.0 = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|x86.ActiveCfg = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Debug|x86.Build.0 = Debug|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|x64.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.PerformanceTest|x86.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|Any CPU.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|Any CPU.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|ARM.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|ARM.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|x64.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|x64.Build.0 = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|x86.ActiveCfg = Release|Any CPU + {26A3F930-FDAF-4886-9111-D326A6F68E82}.Release|x86.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|ARM.ActiveCfg = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|ARM.Build.0 = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x64.Build.0 = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Debug|x86.Build.0 = Debug|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x64.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.PerformanceTest|x86.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Any CPU.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|ARM.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|ARM.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x64.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x64.Build.0 = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x86.ActiveCfg = Release|Any CPU + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -545,8 +712,12 @@ Global {09C98E72-44F7-4469-B82A-DFA3053652E6} = {87A17015-9338-431E-B338-57BDA03984C1} {BFCE0B36-F21B-4EB1-919E-C486E70C8BEA} = {1BD5D488-707E-4030-8AE8-80D93D04963F} {9D65A105-FB03-40DB-9185-8C695B8EE8D6} = {086116A9-EC42-45C1-B359-7AFB9A488556} - {A1B322FC-AA39-4894-AFA8-AB427A3FBA09} = {BFCE0B36-F21B-4EB1-919E-C486E70C8BEA} {0F930636-458B-401F-9EAF-F4F05E93BCC9} = {7D06945C-638C-4973-B0B6-D0D667FA318F} {E4CA9866-6234-49D4-8CDF-1F3A21EFD138} = {09C98E72-44F7-4469-B82A-DFA3053652E6} + {17D0F223-E156-42CF-ACA8-815733FE094F} = {9600C37E-439F-43D7-9D12-3AB0BEF7D906} + {3DEB15F9-E7DA-403F-B6D3-A8499310397F} = {9600C37E-439F-43D7-9D12-3AB0BEF7D906} + {0A5F920A-1BF5-4DAC-B799-0C618B203797} = {9600C37E-439F-43D7-9D12-3AB0BEF7D906} + {26A3F930-FDAF-4886-9111-D326A6F68E82} = {9600C37E-439F-43D7-9D12-3AB0BEF7D906} + {A1B322FC-AA39-4894-AFA8-AB427A3FBA09} = {BFCE0B36-F21B-4EB1-919E-C486E70C8BEA} EndGlobalSection EndGlobal diff --git a/MsgPack.Xamarin.sln b/MsgPack.Xamarin.sln index 1c92c0ecc..7cc0ad8cf 100644 --- a/MsgPack.Xamarin.sln +++ b/MsgPack.Xamarin.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.27130.2027 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "common", "common", "{60EC42E9-D79B-4ADF-8F80-4DCD580061FD}" ProjectSection(SolutionItems) = preProject @@ -10,10 +10,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "common", "common", "{60EC42 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1BD5D488-707E-4030-8AE8-80D93D04963F}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Mono", "Mono", "{BA5E7D16-23AB-44B5-BAF5-6E9C9F51E67A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Xamarin.Android", "src\MsgPack.Xamarin.Android\MsgPack.Xamarin.Android.csproj", "{A6210C9C-1614-46C5-97B2-6A37032AF143}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{87A17015-9338-431E-B338-57BDA03984C1}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Xamarin.Android", "test\MsgPack.UnitTest.Xamarin.Android\MsgPack.UnitTest.Xamarin.Android.csproj", "{5EDECDB4-5179-4441-974F-EC26B4F54528}" @@ -24,10 +20,38 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{DB9CF5 .nuget\NuGet.targets = .nuget\NuGet.targets EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Xamarin.iOS", "src\MsgPack.Xamarin.iOS\MsgPack.Xamarin.iOS.csproj", "{346B55F0-94FA-4B90-9C11-06031043B685}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Xamarin.iOS", "test\MsgPack.UnitTest.Xamarin.iOS\MsgPack.UnitTest.Xamarin.iOS.csproj", "{2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack", "src\MsgPack\MsgPack.csproj", "{5BCEC32E-990E-4DE5-945F-BD27326A7418}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.ArraySerialization.Xamarin.iOS", "test\MsgPack.UnitTest.ArraySerialization.Xamarin.iOS\MsgPack.UnitTest.ArraySerialization.Xamarin.iOS.csproj", "{0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.MapSerialization.Xamarin.iOS", "test\MsgPack.UnitTest.MapSerialization.Xamarin.iOS\MsgPack.UnitTest.MapSerialization.Xamarin.iOS.csproj", "{4270609F-A834-484E-B882-0725BC187CBA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Packer.Xamarin.iOS", "test\MsgPack.UnitTest.Packer.Xamarin.iOS\MsgPack.UnitTest.Packer.Xamarin.iOS.csproj", "{8608E697-4636-4CF1-AAEF-66370021DB7F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unpacker.Xamarin.iOS", "test\MsgPack.UnitTest.Unpacker.Xamarin.iOS\MsgPack.UnitTest.Unpacker.Xamarin.iOS.csproj", "{7F63D9CD-28E2-4E24-BFAA-71DE14078023}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unpacking.Xamarin.iOS", "test\MsgPack.UnitTest.Unpacking.Xamarin.iOS\MsgPack.UnitTest.Unpacking.Xamarin.iOS.csproj", "{01607987-6F33-4990-8E1A-EAB89ED5C968}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Timestamp.Xamarin.iOS", "test\MsgPack.UnitTest.Timestamp.Xamarin.iOS\MsgPack.UnitTest.Timestamp.Xamarin.iOS.csproj", "{AFD483BA-392D-437B-8D0C-D053BD15E2EA}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Android", "Android", "{4F31AC41-89F9-42D1-AAB4-BACD7637F7A0}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "iOS", "iOS", "{3FF6E499-E496-413E-9EDD-632076565FEB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.ArraySerialization.Xamarin.Android", "test\MsgPack.UnitTest.ArraySerialization.Xamarin.Android\MsgPack.UnitTest.ArraySerialization.Xamarin.Android.csproj", "{AE931C31-C472-4F0C-B988-6EDCA66E0C2E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.MapSerialization.Xamarin.Android", "test\MsgPack.UnitTest.MapSerialization.Xamarin.Android\MsgPack.UnitTest.MapSerialization.Xamarin.Android.csproj", "{A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Packer.Xamarin.Android", "test\MsgPack.UnitTest.Packer.Xamarin.Android\MsgPack.UnitTest.Packer.Xamarin.Android.csproj", "{87803450-73E2-4EC3-9A11-B4A399C6FD47}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Timestamp.Xamarin.Android", "test\MsgPack.UnitTest.Timestamp.Xamarin.Android\MsgPack.UnitTest.Timestamp.Xamarin.Android.csproj", "{64868F91-8537-4CC7-9900-A29D5E51FB52}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unpacker.Xamarin.Android", "test\MsgPack.UnitTest.Unpacker.Xamarin.Android\MsgPack.UnitTest.Unpacker.Xamarin.Android.csproj", "{F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unpacking.Xamarin.Android", "test\MsgPack.UnitTest.Unpacking.Xamarin.Android\MsgPack.UnitTest.Unpacking.Xamarin.Android.csproj", "{436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Ad-Hoc|Any CPU = Ad-Hoc|Any CPU @@ -38,42 +62,29 @@ Global AppStore|iPhone = AppStore|iPhone AppStore|iPhoneSimulator = AppStore|iPhoneSimulator AppStore|Mixed Platforms = AppStore|Mixed Platforms + CodeAnalysis|Any CPU = CodeAnalysis|Any CPU + CodeAnalysis|iPhone = CodeAnalysis|iPhone + CodeAnalysis|iPhoneSimulator = CodeAnalysis|iPhoneSimulator + CodeAnalysis|Mixed Platforms = CodeAnalysis|Mixed Platforms Debug|Any CPU = Debug|Any CPU Debug|iPhone = Debug|iPhone Debug|iPhoneSimulator = Debug|iPhoneSimulator Debug|Mixed Platforms = Debug|Mixed Platforms + Instrument|Any CPU = Instrument|Any CPU + Instrument|iPhone = Instrument|iPhone + Instrument|iPhoneSimulator = Instrument|iPhoneSimulator + Instrument|Mixed Platforms = Instrument|Mixed Platforms + PerformanceTest|Any CPU = PerformanceTest|Any CPU + PerformanceTest|iPhone = PerformanceTest|iPhone + PerformanceTest|iPhoneSimulator = PerformanceTest|iPhoneSimulator + PerformanceTest|Mixed Platforms = PerformanceTest|Mixed Platforms Release|Any CPU = Release|Any CPU Release|iPhone = Release|iPhone Release|iPhoneSimulator = Release|iPhoneSimulator Release|Mixed Platforms = Release|Mixed Platforms EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Ad-Hoc|Any CPU.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Ad-Hoc|Any CPU.Build.0 = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Ad-Hoc|iPhone.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Ad-Hoc|Mixed Platforms.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Ad-Hoc|Mixed Platforms.Build.0 = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.AppStore|Any CPU.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.AppStore|Any CPU.Build.0 = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.AppStore|iPhone.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.AppStore|iPhoneSimulator.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.AppStore|Mixed Platforms.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.AppStore|Mixed Platforms.Build.0 = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Debug|iPhone.ActiveCfg = Debug|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Release|Any CPU.Build.0 = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Release|iPhone.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A6210C9C-1614-46C5-97B2-6A37032AF143}.Release|Mixed Platforms.Build.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|Any CPU.ActiveCfg = Release|Any CPU - {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|Any CPU.Build.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|Any CPU.Deploy.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|iPhone.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Release|Any CPU @@ -81,13 +92,24 @@ Global {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|Mixed Platforms.Build.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Ad-Hoc|Mixed Platforms.Deploy.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|Any CPU.ActiveCfg = Release|Any CPU - {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|Any CPU.Build.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|Any CPU.Deploy.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|iPhone.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|iPhoneSimulator.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|Mixed Platforms.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|Mixed Platforms.Build.0 = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.AppStore|Mixed Platforms.Deploy.0 = Release|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|Any CPU.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|Any CPU.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|Any CPU.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|iPhone.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|iPhone.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|iPhone.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|iPhoneSimulator.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|iPhoneSimulator.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|Mixed Platforms.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.CodeAnalysis|Mixed Platforms.Deploy.0 = Debug|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Debug|Any CPU.Build.0 = Debug|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Debug|Any CPU.Deploy.0 = Debug|Any CPU @@ -96,37 +118,37 @@ Global {5EDECDB4-5179-4441-974F-EC26B4F54528}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Debug|Mixed Platforms.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|Any CPU.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|Any CPU.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|Any CPU.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|iPhone.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|iPhone.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|iPhone.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|iPhoneSimulator.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|iPhoneSimulator.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|Mixed Platforms.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.Instrument|Mixed Platforms.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|Any CPU.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|Any CPU.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|Any CPU.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|iPhone.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|iPhone.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|iPhone.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|iPhoneSimulator.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|iPhoneSimulator.Deploy.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|Mixed Platforms.Build.0 = Debug|Any CPU + {5EDECDB4-5179-4441-974F-EC26B4F54528}.PerformanceTest|Mixed Platforms.Deploy.0 = Debug|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Release|Any CPU.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Release|iPhone.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {5EDECDB4-5179-4441-974F-EC26B4F54528}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Ad-Hoc|Any CPU.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Ad-Hoc|Any CPU.Build.0 = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Ad-Hoc|iPhone.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Ad-Hoc|Mixed Platforms.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Ad-Hoc|Mixed Platforms.Build.0 = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.AppStore|Any CPU.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.AppStore|Any CPU.Build.0 = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.AppStore|iPhone.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.AppStore|iPhoneSimulator.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.AppStore|Mixed Platforms.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.AppStore|Mixed Platforms.Build.0 = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|Any CPU.Build.0 = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|iPhone.ActiveCfg = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|iPhone.Build.0 = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Release|Any CPU.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Release|Any CPU.Build.0 = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Release|iPhone.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {346B55F0-94FA-4B90-9C11-06031043B685}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator @@ -140,6 +162,14 @@ Global {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.AppStore|Mixed Platforms.ActiveCfg = AppStore|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.AppStore|Mixed Platforms.Build.0 = AppStore|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|Any CPU.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|Any CPU.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|iPhone.ActiveCfg = Release|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|iPhone.Build.0 = Release|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.CodeAnalysis|Mixed Platforms.Build.0 = Release|iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Debug|Any CPU.ActiveCfg = Debug|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Debug|iPhone.ActiveCfg = Debug|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Debug|iPhone.Build.0 = Debug|iPhone @@ -147,22 +177,739 @@ Global {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|Any CPU.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|Any CPU.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|iPhone.ActiveCfg = Release|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|iPhone.Build.0 = Release|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|Mixed Platforms.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Instrument|Mixed Platforms.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|Any CPU.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|Any CPU.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|iPhone.ActiveCfg = Release|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|iPhone.Build.0 = Release|iPhone + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|iPhoneSimulator + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.PerformanceTest|Mixed Platforms.Build.0 = Release|iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Release|Any CPU.ActiveCfg = Release|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Release|iPhone.ActiveCfg = Release|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Release|iPhone.Build.0 = Release|iPhone {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C}.Release|Mixed Platforms.ActiveCfg = Release|iPhone + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|iPhone.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|iPhone.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|iPhoneSimulator.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Ad-Hoc|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|iPhone.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|iPhone.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|iPhoneSimulator.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.AppStore|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|iPhone.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|iPhone.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|iPhoneSimulator.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|iPhone.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|iPhone.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|iPhone.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|iPhoneSimulator.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|iPhone.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|iPhone.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|iPhoneSimulator.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|iPhone.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|iPhone.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|iPhoneSimulator.Build.0 = Ad-Hoc|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|Mixed Platforms.ActiveCfg = Ad-Hoc|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Ad-Hoc|Mixed Platforms.Build.0 = Ad-Hoc|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|Any CPU.ActiveCfg = AppStore|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|iPhone.ActiveCfg = AppStore|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|iPhone.Build.0 = AppStore|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.AppStore|Mixed Platforms.Build.0 = AppStore|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|iPhone.ActiveCfg = Debug|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|iPhone.Build.0 = Debug|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|iPhone.ActiveCfg = Instrument|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|iPhone.Build.0 = Instrument|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|iPhoneSimulator.Build.0 = Instrument|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|Any CPU.ActiveCfg = AppStore|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|Any CPU.Build.0 = AppStore|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|iPhone.ActiveCfg = AppStore|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|iPhone.Build.0 = AppStore|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.PerformanceTest|Mixed Platforms.Build.0 = AppStore|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|iPhone.ActiveCfg = Release|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|iPhone.Build.0 = Release|iPhone + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|iPhoneSimulator.Build.0 = Ad-Hoc|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|Mixed Platforms.ActiveCfg = Ad-Hoc|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Ad-Hoc|Mixed Platforms.Build.0 = Ad-Hoc|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|Any CPU.ActiveCfg = AppStore|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|iPhone.ActiveCfg = AppStore|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|iPhone.Build.0 = AppStore|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.AppStore|Mixed Platforms.Build.0 = AppStore|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|iPhone.ActiveCfg = Debug|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|iPhone.Build.0 = Debug|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|iPhone.ActiveCfg = Instrument|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|iPhone.Build.0 = Instrument|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|iPhoneSimulator.Build.0 = Instrument|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|Any CPU.ActiveCfg = AppStore|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|Any CPU.Build.0 = AppStore|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|iPhone.ActiveCfg = AppStore|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|iPhone.Build.0 = AppStore|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.PerformanceTest|Mixed Platforms.Build.0 = AppStore|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Release|iPhone.ActiveCfg = Release|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Release|iPhone.Build.0 = Release|iPhone + {4270609F-A834-484E-B882-0725BC187CBA}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {4270609F-A834-484E-B882-0725BC187CBA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {4270609F-A834-484E-B882-0725BC187CBA}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|iPhoneSimulator.Build.0 = Ad-Hoc|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|Mixed Platforms.ActiveCfg = Ad-Hoc|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Ad-Hoc|Mixed Platforms.Build.0 = Ad-Hoc|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|Any CPU.ActiveCfg = AppStore|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|iPhone.ActiveCfg = AppStore|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|iPhone.Build.0 = AppStore|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.AppStore|Mixed Platforms.Build.0 = AppStore|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|iPhone.ActiveCfg = Debug|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|iPhone.Build.0 = Debug|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|iPhone.ActiveCfg = Instrument|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|iPhone.Build.0 = Instrument|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|iPhoneSimulator.Build.0 = Instrument|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|Any CPU.ActiveCfg = AppStore|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|Any CPU.Build.0 = AppStore|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|iPhone.ActiveCfg = AppStore|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|iPhone.Build.0 = AppStore|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.PerformanceTest|Mixed Platforms.Build.0 = AppStore|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|iPhone.ActiveCfg = Release|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|iPhone.Build.0 = Release|iPhone + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {8608E697-4636-4CF1-AAEF-66370021DB7F}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|iPhoneSimulator.Build.0 = Ad-Hoc|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|Mixed Platforms.ActiveCfg = Ad-Hoc|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Ad-Hoc|Mixed Platforms.Build.0 = Ad-Hoc|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|Any CPU.ActiveCfg = AppStore|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|iPhone.ActiveCfg = AppStore|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|iPhone.Build.0 = AppStore|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.AppStore|Mixed Platforms.Build.0 = AppStore|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|iPhone.ActiveCfg = Debug|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|iPhone.Build.0 = Debug|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|iPhone.ActiveCfg = Instrument|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|iPhone.Build.0 = Instrument|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|iPhoneSimulator.Build.0 = Instrument|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|Any CPU.ActiveCfg = AppStore|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|Any CPU.Build.0 = AppStore|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|iPhone.ActiveCfg = AppStore|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|iPhone.Build.0 = AppStore|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.PerformanceTest|Mixed Platforms.Build.0 = AppStore|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|iPhone.ActiveCfg = Release|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|iPhone.Build.0 = Release|iPhone + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {7F63D9CD-28E2-4E24-BFAA-71DE14078023}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|iPhoneSimulator.Build.0 = Ad-Hoc|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|Mixed Platforms.ActiveCfg = Ad-Hoc|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Ad-Hoc|Mixed Platforms.Build.0 = Ad-Hoc|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|Any CPU.ActiveCfg = AppStore|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|iPhone.ActiveCfg = AppStore|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|iPhone.Build.0 = AppStore|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.AppStore|Mixed Platforms.Build.0 = AppStore|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|iPhone.ActiveCfg = Debug|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|iPhone.Build.0 = Debug|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|iPhone.ActiveCfg = Instrument|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|iPhone.Build.0 = Instrument|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|iPhoneSimulator.Build.0 = Instrument|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|Any CPU.ActiveCfg = AppStore|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|Any CPU.Build.0 = AppStore|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|iPhone.ActiveCfg = AppStore|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|iPhone.Build.0 = AppStore|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.PerformanceTest|Mixed Platforms.Build.0 = AppStore|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|Any CPU.ActiveCfg = Release|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|iPhone.ActiveCfg = Release|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|iPhone.Build.0 = Release|iPhone + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {01607987-6F33-4990-8E1A-EAB89ED5C968}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|Any CPU.ActiveCfg = Ad-Hoc|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|Any CPU.Build.0 = Ad-Hoc|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Ad-Hoc|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|iPhoneSimulator.Build.0 = Ad-Hoc|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|Mixed Platforms.ActiveCfg = Ad-Hoc|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Ad-Hoc|Mixed Platforms.Build.0 = Ad-Hoc|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|Any CPU.ActiveCfg = AppStore|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|iPhone.ActiveCfg = AppStore|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|iPhone.Build.0 = AppStore|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.AppStore|Mixed Platforms.Build.0 = AppStore|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|iPhone.ActiveCfg = Debug|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|iPhone.Build.0 = Debug|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|Mixed Platforms.ActiveCfg = Debug|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Debug|Mixed Platforms.Build.0 = Debug|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|iPhone.ActiveCfg = Instrument|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|iPhone.Build.0 = Instrument|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|iPhoneSimulator.Build.0 = Instrument|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|Any CPU.ActiveCfg = AppStore|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|Any CPU.Build.0 = AppStore|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|iPhone.ActiveCfg = AppStore|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|iPhone.Build.0 = AppStore|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|iPhoneSimulator.ActiveCfg = AppStore|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|iPhoneSimulator.Build.0 = AppStore|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|Mixed Platforms.ActiveCfg = AppStore|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.PerformanceTest|Mixed Platforms.Build.0 = AppStore|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|iPhone.ActiveCfg = Release|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|iPhone.Build.0 = Release|iPhone + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {AFD483BA-392D-437B-8D0C-D053BD15E2EA}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|iPhone.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Ad-Hoc|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|iPhone.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.AppStore|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|iPhone.ActiveCfg = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|iPhone.Build.0 = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|iPhoneSimulator.Build.0 = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|Any CPU.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|iPhone.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.PerformanceTest|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|iPhone.ActiveCfg = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|iPhone.Build.0 = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|iPhone.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Ad-Hoc|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|iPhone.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.AppStore|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|iPhone.ActiveCfg = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|iPhone.Build.0 = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|iPhoneSimulator.Build.0 = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|Any CPU.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|iPhone.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.PerformanceTest|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|iPhone.ActiveCfg = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|iPhone.Build.0 = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|iPhone.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Ad-Hoc|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|iPhone.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.AppStore|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|Any CPU.Build.0 = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|iPhone.ActiveCfg = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|iPhone.Build.0 = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|iPhoneSimulator.Build.0 = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|Any CPU.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|iPhone.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.PerformanceTest|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|Any CPU.ActiveCfg = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|iPhone.ActiveCfg = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|iPhone.Build.0 = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {87803450-73E2-4EC3-9A11-B4A399C6FD47}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|iPhone.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Ad-Hoc|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|iPhone.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.AppStore|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|iPhone.ActiveCfg = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|iPhone.Build.0 = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|iPhoneSimulator.Build.0 = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|Any CPU.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|iPhone.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.PerformanceTest|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|iPhone.ActiveCfg = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|iPhone.Build.0 = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {64868F91-8537-4CC7-9900-A29D5E51FB52}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|iPhone.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Ad-Hoc|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|iPhone.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.AppStore|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|iPhone.ActiveCfg = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|iPhone.Build.0 = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|iPhoneSimulator.Build.0 = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|Any CPU.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|iPhone.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.PerformanceTest|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|iPhone.ActiveCfg = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|iPhone.Build.0 = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|iPhone.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Ad-Hoc|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|iPhone.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.AppStore|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|iPhone.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|Any CPU.ActiveCfg = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|Any CPU.Build.0 = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|iPhone.ActiveCfg = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|iPhone.Build.0 = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|iPhoneSimulator.ActiveCfg = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|iPhoneSimulator.Build.0 = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|Mixed Platforms.ActiveCfg = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Instrument|Mixed Platforms.Build.0 = Instrument|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|Any CPU.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|iPhone.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|iPhone.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|iPhoneSimulator.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|iPhoneSimulator.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.PerformanceTest|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|iPhone.ActiveCfg = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|iPhone.Build.0 = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA}.Release|Mixed Platforms.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {BA5E7D16-23AB-44B5-BAF5-6E9C9F51E67A} = {1BD5D488-707E-4030-8AE8-80D93D04963F} - {A6210C9C-1614-46C5-97B2-6A37032AF143} = {BA5E7D16-23AB-44B5-BAF5-6E9C9F51E67A} - {5EDECDB4-5179-4441-974F-EC26B4F54528} = {87A17015-9338-431E-B338-57BDA03984C1} - {346B55F0-94FA-4B90-9C11-06031043B685} = {BA5E7D16-23AB-44B5-BAF5-6E9C9F51E67A} - {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C} = {87A17015-9338-431E-B338-57BDA03984C1} + {5EDECDB4-5179-4441-974F-EC26B4F54528} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {5BCEC32E-990E-4DE5-945F-BD27326A7418} = {1BD5D488-707E-4030-8AE8-80D93D04963F} + {0D0D2516-D9C9-4B29-A87B-FD2F99121BCC} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {4270609F-A834-484E-B882-0725BC187CBA} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {8608E697-4636-4CF1-AAEF-66370021DB7F} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {7F63D9CD-28E2-4E24-BFAA-71DE14078023} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {01607987-6F33-4990-8E1A-EAB89ED5C968} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {AFD483BA-392D-437B-8D0C-D053BD15E2EA} = {3FF6E499-E496-413E-9EDD-632076565FEB} + {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} = {87A17015-9338-431E-B338-57BDA03984C1} + {3FF6E499-E496-413E-9EDD-632076565FEB} = {87A17015-9338-431E-B338-57BDA03984C1} + {AE931C31-C472-4F0C-B988-6EDCA66E0C2E} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + {A10B7CCB-3CD2-48E2-8715-F8186BCAE4E8} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + {87803450-73E2-4EC3-9A11-B4A399C6FD47} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + {64868F91-8537-4CC7-9900-A29D5E51FB52} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + {F08FFEDD-1158-40D8-ACC2-02DD6A5C84A8} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + {436EDA6D-0FF9-40E9-BB74-08D0DCDF94AA} = {4F31AC41-89F9-42D1-AAB4-BACD7637F7A0} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D6D6995F-870D-4920-9CA2-42FE54F45E5E} EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = src\MsgPack.Xamarin.Android\MsgPack.Xamarin.Android.csproj diff --git a/MsgPack.compats.sln b/MsgPack.compats.sln index 91e053320..73b77ed8b 100644 --- a/MsgPack.compats.sln +++ b/MsgPack.compats.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.26228.9 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "common", "common", "{60EC42E9-D79B-4ADF-8F80-4DCD580061FD}" ProjectSection(SolutionItems) = preProject @@ -18,30 +18,22 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{DB9CF5 .nuget\NuGet.targets = .nuget\NuGet.targets EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".NET35", ".NET35", "{B7BF9C9A-7349-499F-BD44-553190C0CFDC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Net35", "src\MsgPack.Net35\MsgPack.Net35.csproj", "{C5490CDC-3B79-42DC-ACFB-75A62E55862C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Net35", "test\MsgPack.UnitTest.Net35\MsgPack.UnitTest.Net35.csproj", "{B8BDEBCD-343C-42A9-8C17-C1318B42F011}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.CodeDom.Net35", "test\MsgPack.UnitTest.CodeDom.Net35\MsgPack.UnitTest.CodeDom.Net35.csproj", "{2A8463C8-8E4B-44F6-AA58-D1232DF88438}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Unity", "Unity", "{936467D2-1DD3-4243-BBB4-FCCB2CA1E3AC}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mpu", "src\mpu\mpu.csproj", "{CB7C32CD-A8D8-44A4-A595-DF4303566C81}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NUnitLite", "NUnitLite", "{767C2A1C-53F8-4048-BE02-CB4393B1CEB6}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NUnitLiteRunner", "test\NUnitLiteRunner\NUnitLiteRunner.csproj", "{12047296-B817-4C1A-B01B-5E619F72E407}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-3.5", "test\NUnitLite\src\framework\nunitlite-3.5.csproj", "{43B24DC5-16D6-45EF-93F1-B021B785A892}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop", "test\MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop\MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj", "{46C5B3D9-45E8-46B6-89F7-837D52C6187A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Unity.Full", "src\MsgPack.Unity.Full\MsgPack.Unity.Full.csproj", "{30581B4A-BCA5-4446-B5E7-4F890A3E9514}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Unity", "src\MsgPack.Unity\MsgPack.Unity.csproj", "{04774100-60EE-4FD5-ACED-593394DFF7B7}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-3.5", "test\NUnitLite\NUnitFramework\nunitlite\nunitlite-3.5.csproj", "{82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunit.framework-3.5", "test\NUnitLite\NUnitFramework\framework\nunit.framework-3.5.csproj", "{7FA125B4-E377-4D4C-AECB-17B934E3A4B3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution CodeAnalysis|Any CPU = CodeAnalysis|Any CPU @@ -70,119 +62,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CoreProfile|Any CPU.Build.0 = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CoreProfile|ARM.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CoreProfile|x64.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.CoreProfile|x86.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Debug|ARM.ActiveCfg = Debug|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Debug|x64.ActiveCfg = Debug|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Debug|x86.ActiveCfg = Debug|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Instrument|Any CPU.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Instrument|Any CPU.Build.0 = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Instrument|ARM.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Instrument|x64.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Instrument|x86.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Release|Any CPU.Build.0 = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Release|ARM.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Release|x64.ActiveCfg = Release|Any CPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C}.Release|x86.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CoreProfile|ARM.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CoreProfile|x64.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.CoreProfile|x86.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Debug|ARM.ActiveCfg = Debug|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Debug|x64.ActiveCfg = Debug|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Debug|x86.ActiveCfg = Debug|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Instrument|Any CPU.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Instrument|ARM.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Instrument|x64.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Instrument|x86.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Release|ARM.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Release|x64.ActiveCfg = Release|Any CPU - {B8BDEBCD-343C-42A9-8C17-C1318B42F011}.Release|x86.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CoreProfile|Any CPU.Build.0 = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CoreProfile|ARM.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CoreProfile|x64.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.CoreProfile|x86.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Debug|ARM.ActiveCfg = Debug|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Debug|x64.ActiveCfg = Debug|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Debug|x86.ActiveCfg = Debug|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Instrument|Any CPU.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Instrument|Any CPU.Build.0 = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Instrument|ARM.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Instrument|x64.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Instrument|x86.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Release|ARM.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Release|x64.ActiveCfg = Release|Any CPU - {2A8463C8-8E4B-44F6-AA58-D1232DF88438}.Release|x86.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CoreProfile|Any CPU.Build.0 = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CoreProfile|ARM.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CoreProfile|x64.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CoreProfile|x86.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|ARM.ActiveCfg = Debug|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|x64.ActiveCfg = Debug|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|x86.ActiveCfg = Debug|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|Any CPU.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|Any CPU.Build.0 = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|ARM.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|x64.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|x86.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|Any CPU.Build.0 = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|ARM.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|x64.ActiveCfg = Release|Any CPU - {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|x86.ActiveCfg = Release|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU @@ -211,34 +90,6 @@ Global {12047296-B817-4C1A-B01B-5E619F72E407}.Release|ARM.ActiveCfg = Release|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.Release|x64.ActiveCfg = Release|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.Release|x86.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CoreProfile|Any CPU.Build.0 = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CoreProfile|ARM.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CoreProfile|x64.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.CoreProfile|x86.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Any CPU.Build.0 = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|ARM.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|x64.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|x86.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Instrument|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Instrument|Any CPU.Build.0 = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Instrument|ARM.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Instrument|x64.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Instrument|x86.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|ARM.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|x64.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|x86.ActiveCfg = Release|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU @@ -327,22 +178,112 @@ Global {04774100-60EE-4FD5-ACED-593394DFF7B7}.Release|ARM.ActiveCfg = Release|Any CPU {04774100-60EE-4FD5-ACED-593394DFF7B7}.Release|x64.ActiveCfg = Release|Any CPU {04774100-60EE-4FD5-ACED-593394DFF7B7}.Release|x86.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|Any CPU.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|ARM.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|ARM.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|x64.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|x64.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|x86.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.CoreProfile|x86.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|ARM.ActiveCfg = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|ARM.Build.0 = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|x64.ActiveCfg = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|x64.Build.0 = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|x86.ActiveCfg = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|x86.Build.0 = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|Any CPU.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|ARM.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|ARM.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|x64.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|x64.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|x86.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Instrument|x86.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|x64.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.PerformanceTest|x86.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|ARM.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|ARM.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|x64.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|x64.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|x86.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|x86.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|Any CPU.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|Any CPU.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|ARM.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|ARM.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|x64.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|x64.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|x86.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.CoreProfile|x86.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|ARM.ActiveCfg = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|ARM.Build.0 = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|x64.ActiveCfg = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|x64.Build.0 = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|x86.ActiveCfg = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|x86.Build.0 = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|Any CPU.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|ARM.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|ARM.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|x64.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|x64.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|x86.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Instrument|x86.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|x64.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.PerformanceTest|x86.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|ARM.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|ARM.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|x64.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|x64.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|x86.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {B7BF9C9A-7349-499F-BD44-553190C0CFDC} = {1BD5D488-707E-4030-8AE8-80D93D04963F} - {C5490CDC-3B79-42DC-ACFB-75A62E55862C} = {B7BF9C9A-7349-499F-BD44-553190C0CFDC} - {B8BDEBCD-343C-42A9-8C17-C1318B42F011} = {87A17015-9338-431E-B338-57BDA03984C1} - {2A8463C8-8E4B-44F6-AA58-D1232DF88438} = {87A17015-9338-431E-B338-57BDA03984C1} {936467D2-1DD3-4243-BBB4-FCCB2CA1E3AC} = {1BD5D488-707E-4030-8AE8-80D93D04963F} - {CB7C32CD-A8D8-44A4-A595-DF4303566C81} = {936467D2-1DD3-4243-BBB4-FCCB2CA1E3AC} {767C2A1C-53F8-4048-BE02-CB4393B1CEB6} = {87A17015-9338-431E-B338-57BDA03984C1} {12047296-B817-4C1A-B01B-5E619F72E407} = {767C2A1C-53F8-4048-BE02-CB4393B1CEB6} - {43B24DC5-16D6-45EF-93F1-B021B785A892} = {767C2A1C-53F8-4048-BE02-CB4393B1CEB6} {46C5B3D9-45E8-46B6-89F7-837D52C6187A} = {87A17015-9338-431E-B338-57BDA03984C1} {30581B4A-BCA5-4446-B5E7-4F890A3E9514} = {936467D2-1DD3-4243-BBB4-FCCB2CA1E3AC} {04774100-60EE-4FD5-ACED-593394DFF7B7} = {936467D2-1DD3-4243-BBB4-FCCB2CA1E3AC} + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A} = {767C2A1C-53F8-4048-BE02-CB4393B1CEB6} + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3} = {767C2A1C-53F8-4048-BE02-CB4393B1CEB6} EndGlobalSection EndGlobal diff --git a/MsgPack.nuspec b/MsgPack.nuspec index 29c381d2c..1030c7002 100644 --- a/MsgPack.nuspec +++ b/MsgPack.nuspec @@ -1,6 +1,6 @@  - + MsgPack.Cli MessagePack for CLI 0.0.0-development @@ -11,82 +11,88 @@ http://cli.msgpack.org/images/msgpack.ico false MessagePack is fast, compact, and interoperable binary serialization format. -This package provides MessagePack serialization/deserialization APIs. This pacakge also supports Mono, Xamarin, .NET Core and Unity. - +This package provides MessagePack serialization/deserialization APIs. This package also supports Mono, Xamarin, .NET Core and Unity. + This release includes .NET Core and Unity IL2CPP support, Xamarin iOS linker support, asynchronous serialization support, and various improvements and bug fixes reported in github issues. Copyright 2010-2016 FUJIWARA, Yusuke, all rights reserved. MsgPack MessagePack Serialization Formatter Serializer - - + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/MsgPack.sln b/MsgPack.sln index 2f81409d1..a606c43e6 100644 --- a/MsgPack.sln +++ b/MsgPack.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.3 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "common", "common", "{60EC42E9-D79B-4ADF-8F80-4DCD580061FD}" ProjectSection(SolutionItems) = preProject @@ -12,35 +12,41 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1BD5D488-707 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{87A17015-9338-431E-B338-57BDA03984C1}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".NET46", ".NET46", "{DDA4827C-7960-4CA6-AE41-8C1544DCFBE9}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{DB9CF5EC-73DA-4AEB-BC6B-AF4260009E8B}" ProjectSection(SolutionItems) = preProject .nuget\NuGet.exe = .nuget\NuGet.exe .nuget\NuGet.targets = .nuget\NuGet.targets EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack", "src\MsgPack\MsgPack.csproj", "{5BCEC32E-990E-4DE5-945F-BD27326A7418}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest", "test\MsgPack.UnitTest\MsgPack.UnitTest.csproj", "{3889C9BE-0473-4B41-80E8-C4C923E837E7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack.UnitTest", "test\MsgPack.UnitTest\MsgPack.UnitTest.csproj", "{3889C9BE-0473-4B41-80E8-C4C923E837E7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.NUnitPortable", "test\MsgPack.NUnitPortable\MsgPack.NUnitPortable.csproj", "{FC521316-EBCD-4EF1-8235-C976B2A31EB0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.CodeDom", "test\MsgPack.UnitTest.CodeDom\MsgPack.UnitTest.CodeDom.csproj", "{23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack.UnitTest.CodeDom", "test\MsgPack.UnitTest.CodeDom\MsgPack.UnitTest.CodeDom.csproj", "{23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.BclExtensions", "test\MsgPack.UnitTest.BclExtensions\MsgPack.UnitTest.BclExtensions.csproj", "{DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack.UnitTest.BclExtensions", "test\MsgPack.UnitTest.BclExtensions\MsgPack.UnitTest.BclExtensions.csproj", "{DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{7D2D3DAB-6EB6-463D-B186-E875DA48DF9F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples", "samples\Samples\Samples.csproj", "{7F8D9786-383D-4441-8A3A-5E305E26B965}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CLR", "CLR", "{AF25D7E8-2F55-4431-BCE1-7C3E3C0E74E1}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MultiPlatform", "MultiPlatform", "{AF25D7E8-2F55-4431-BCE1-7C3E3C0E74E1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_common", "_common", "{EACF1BF1-CB21-4D62-942C-3488F60B8D70}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".NET45", ".NET45", "{3E9C7751-EE97-4820-BFEF-BA5F532A45C9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack", "src\MsgPack\MsgPack.csproj", "{5BCEC32E-990E-4DE5-945F-BD27326A7418}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MultiPlatform", "MultiPlatform", "{7D8FA6E5-A27C-4672-90ED-06033F030A66}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{2F623C70-7B64-490E-8605-D75D444CF065}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "mpu", "src\mpu\mpu.csproj", "{CB7C32CD-A8D8-44A4-A595-DF4303566C81}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Net45", "src\MsgPack.Net45\MsgPack.Net45.csproj", "{9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Net35", "Net35", "{F041F2B6-6692-4035-96A3-BB36742F5CCC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack.UnitTest.CodeDom.Net35", "test\MsgPack.UnitTest.CodeDom.Net35\MsgPack.UnitTest.CodeDom.Net35.csproj", "{34FC29EA-8722-49CD-8D2A-CE170797F605}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack.UnitTest.Net35", "test\MsgPack.UnitTest.Net35\MsgPack.UnitTest.Net35.csproj", "{ED57FCBD-9917-4822-B969-EB5D98D7207B}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -54,6 +60,11 @@ Global Debug|Mixed Platforms = Debug|Mixed Platforms Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 + Instrument|Any CPU = Instrument|Any CPU + Instrument|ARM = Instrument|ARM + Instrument|Mixed Platforms = Instrument|Mixed Platforms + Instrument|x64 = Instrument|x64 + Instrument|x86 = Instrument|x86 PerformanceTest|Any CPU = PerformanceTest|Any CPU PerformanceTest|ARM = PerformanceTest|ARM PerformanceTest|Mixed Platforms = PerformanceTest|Mixed Platforms @@ -66,39 +77,16 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|ARM.ActiveCfg = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|x64.ActiveCfg = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|x86.ActiveCfg = CodeAnalysis|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|ARM.ActiveCfg = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|x64.ActiveCfg = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|x86.ActiveCfg = Debug|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Any CPU.ActiveCfg = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Any CPU.Build.0 = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|ARM.ActiveCfg = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Mixed Platforms.ActiveCfg = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Mixed Platforms.Build.0 = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|x64.ActiveCfg = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|x86.ActiveCfg = PerformanceTest|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Any CPU.Build.0 = Release|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|ARM.ActiveCfg = Release|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|x64.ActiveCfg = Release|Any CPU - {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|x86.ActiveCfg = Release|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|ARM.ActiveCfg = CodeAnalysis|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|x64.ActiveCfg = CodeAnalysis|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|x86.ActiveCfg = CodeAnalysis|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.CodeAnalysis|x86.Build.0 = Release|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -106,13 +94,26 @@ Global {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Debug|x64.ActiveCfg = Debug|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Debug|x86.ActiveCfg = Debug|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Any CPU.ActiveCfg = PerformanceTest|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Any CPU.Build.0 = PerformanceTest|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|ARM.ActiveCfg = PerformanceTest|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Mixed Platforms.ActiveCfg = PerformanceTest|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Mixed Platforms.Build.0 = PerformanceTest|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|x64.ActiveCfg = PerformanceTest|Any CPU - {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|x86.ActiveCfg = PerformanceTest|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|Any CPU.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|ARM.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|ARM.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|Mixed Platforms.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|Mixed Platforms.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|x64.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|x64.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|x86.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Instrument|x86.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|x64.Build.0 = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {3889C9BE-0473-4B41-80E8-C4C923E837E7}.PerformanceTest|x86.Build.0 = Release|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Release|ARM.ActiveCfg = Release|Any CPU {3889C9BE-0473-4B41-80E8-C4C923E837E7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU @@ -130,6 +131,16 @@ Global {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Debug|x64.ActiveCfg = Debug|Any CPU {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Debug|x86.ActiveCfg = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|Any CPU.ActiveCfg = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|Any CPU.Build.0 = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|ARM.ActiveCfg = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|ARM.Build.0 = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|Mixed Platforms.ActiveCfg = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|Mixed Platforms.Build.0 = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|x64.ActiveCfg = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|x64.Build.0 = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|x86.ActiveCfg = Debug|Any CPU + {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.Instrument|x86.Build.0 = Debug|Any CPU {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU {FC521316-EBCD-4EF1-8235-C976B2A31EB0}.PerformanceTest|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -152,6 +163,16 @@ Global {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Debug|x64.ActiveCfg = Debug|Any CPU {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Debug|x86.ActiveCfg = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|Any CPU.ActiveCfg = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|Any CPU.Build.0 = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|ARM.ActiveCfg = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|ARM.Build.0 = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|Mixed Platforms.ActiveCfg = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|Mixed Platforms.Build.0 = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|x64.ActiveCfg = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|x64.Build.0 = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|x86.ActiveCfg = Debug|Any CPU + {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.Instrument|x86.Build.0 = Debug|Any CPU {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2}.PerformanceTest|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -174,6 +195,16 @@ Global {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Debug|x64.ActiveCfg = Debug|Any CPU {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Debug|x86.ActiveCfg = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|Any CPU.ActiveCfg = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|Any CPU.Build.0 = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|ARM.ActiveCfg = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|ARM.Build.0 = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|Mixed Platforms.ActiveCfg = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|Mixed Platforms.Build.0 = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|x64.ActiveCfg = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|x64.Build.0 = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|x86.ActiveCfg = Debug|Any CPU + {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.Instrument|x86.Build.0 = Debug|Any CPU {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU {DB3ED6D2-D27F-4E8F-AFE2-5503113216AC}.PerformanceTest|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -196,6 +227,16 @@ Global {7F8D9786-383D-4441-8A3A-5E305E26B965}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.Debug|x64.ActiveCfg = Debug|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.Debug|x86.ActiveCfg = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|Any CPU.ActiveCfg = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|Any CPU.Build.0 = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|ARM.ActiveCfg = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|ARM.Build.0 = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|Mixed Platforms.ActiveCfg = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|Mixed Platforms.Build.0 = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|x64.ActiveCfg = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|x64.Build.0 = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|x86.ActiveCfg = Debug|Any CPU + {7F8D9786-383D-4441-8A3A-5E305E26B965}.Instrument|x86.Build.0 = Debug|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.PerformanceTest|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -206,41 +247,209 @@ Global {7F8D9786-383D-4441-8A3A-5E305E26B965}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.Release|x64.ActiveCfg = Release|Any CPU {7F8D9786-383D-4441-8A3A-5E305E26B965}.Release|x86.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|Mixed Platforms.ActiveCfg = CodeAnalysis|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|Mixed Platforms.Build.0 = CodeAnalysis|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|ARM.ActiveCfg = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|x64.ActiveCfg = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Debug|x86.ActiveCfg = Debug|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|x64.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.PerformanceTest|x86.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|Any CPU.Build.0 = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|ARM.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|x64.ActiveCfg = Release|Any CPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D}.Release|x86.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|ARM.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|ARM.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|x64.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|x64.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|x86.ActiveCfg = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Debug|x86.Build.0 = Debug|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|ARM.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|ARM.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|x64.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|x64.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|x86.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Instrument|x86.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|x64.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.PerformanceTest|x86.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Any CPU.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|ARM.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|ARM.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|x64.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|x64.Build.0 = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|x86.ActiveCfg = Release|Any CPU + {5BCEC32E-990E-4DE5-945F-BD27326A7418}.Release|x86.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|ARM.ActiveCfg = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|ARM.Build.0 = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|x64.ActiveCfg = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|x64.Build.0 = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|x86.ActiveCfg = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Debug|x86.Build.0 = Debug|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|Any CPU.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|ARM.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|ARM.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|Mixed Platforms.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|Mixed Platforms.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|x64.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|x64.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|x86.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Instrument|x86.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|x64.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.PerformanceTest|x86.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|Any CPU.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|ARM.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|ARM.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|x64.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|x64.Build.0 = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|x86.ActiveCfg = Release|Any CPU + {CB7C32CD-A8D8-44A4-A595-DF4303566C81}.Release|x86.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|Any CPU.Build.0 = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|ARM.ActiveCfg = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|ARM.Build.0 = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|x64.ActiveCfg = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|x64.Build.0 = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|x86.ActiveCfg = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Debug|x86.Build.0 = Debug|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|Any CPU.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|ARM.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|ARM.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|Mixed Platforms.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|Mixed Platforms.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|x64.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|x64.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|x86.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Instrument|x86.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|x64.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.PerformanceTest|x86.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|Any CPU.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|Any CPU.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|ARM.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|ARM.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|x64.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|x64.Build.0 = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|x86.ActiveCfg = Release|Any CPU + {34FC29EA-8722-49CD-8D2A-CE170797F605}.Release|x86.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|ARM.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|ARM.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|Mixed Platforms.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|Mixed Platforms.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|x64.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|x64.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|x86.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.CodeAnalysis|x86.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|ARM.ActiveCfg = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|ARM.Build.0 = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|x64.ActiveCfg = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|x64.Build.0 = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|x86.ActiveCfg = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Debug|x86.Build.0 = Debug|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|Any CPU.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|Any CPU.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|ARM.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|ARM.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|Mixed Platforms.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|Mixed Platforms.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|x64.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|x64.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|x86.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Instrument|x86.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|Any CPU.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|Any CPU.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|ARM.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|ARM.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|Mixed Platforms.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|x64.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|x64.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|x86.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.PerformanceTest|x86.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|Any CPU.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|ARM.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|ARM.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|x64.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|x64.Build.0 = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|x86.ActiveCfg = Release|Any CPU + {ED57FCBD-9917-4822-B969-EB5D98D7207B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {DDA4827C-7960-4CA6-AE41-8C1544DCFBE9} = {1BD5D488-707E-4030-8AE8-80D93D04963F} - {5BCEC32E-990E-4DE5-945F-BD27326A7418} = {DDA4827C-7960-4CA6-AE41-8C1544DCFBE9} {3889C9BE-0473-4B41-80E8-C4C923E837E7} = {AF25D7E8-2F55-4431-BCE1-7C3E3C0E74E1} {FC521316-EBCD-4EF1-8235-C976B2A31EB0} = {EACF1BF1-CB21-4D62-942C-3488F60B8D70} {23F8ABB1-F41A-4150-B5D5-9A7AA60E05D2} = {AF25D7E8-2F55-4431-BCE1-7C3E3C0E74E1} @@ -248,7 +457,15 @@ Global {7F8D9786-383D-4441-8A3A-5E305E26B965} = {7D2D3DAB-6EB6-463D-B186-E875DA48DF9F} {AF25D7E8-2F55-4431-BCE1-7C3E3C0E74E1} = {87A17015-9338-431E-B338-57BDA03984C1} {EACF1BF1-CB21-4D62-942C-3488F60B8D70} = {87A17015-9338-431E-B338-57BDA03984C1} - {3E9C7751-EE97-4820-BFEF-BA5F532A45C9} = {1BD5D488-707E-4030-8AE8-80D93D04963F} - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D} = {3E9C7751-EE97-4820-BFEF-BA5F532A45C9} + {5BCEC32E-990E-4DE5-945F-BD27326A7418} = {7D8FA6E5-A27C-4672-90ED-06033F030A66} + {7D8FA6E5-A27C-4672-90ED-06033F030A66} = {1BD5D488-707E-4030-8AE8-80D93D04963F} + {2F623C70-7B64-490E-8605-D75D444CF065} = {1BD5D488-707E-4030-8AE8-80D93D04963F} + {CB7C32CD-A8D8-44A4-A595-DF4303566C81} = {2F623C70-7B64-490E-8605-D75D444CF065} + {F041F2B6-6692-4035-96A3-BB36742F5CCC} = {87A17015-9338-431E-B338-57BDA03984C1} + {34FC29EA-8722-49CD-8D2A-CE170797F605} = {F041F2B6-6692-4035-96A3-BB36742F5CCC} + {ED57FCBD-9917-4822-B969-EB5D98D7207B} = {F041F2B6-6692-4035-96A3-BB36742F5CCC} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {614ADBB5-010D-4B4B-8ED9-B2C1BD1F76CA} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index f5838bb55..d6253d7ee 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,18 @@ # MessagePack for CLI +## CI Status + +|**Configuration**|**Status**| +|:--|:--| +|Release |[![Build status release](https://ci.appveyor.com/api/projects/status/5ln7u7efwjepj6o8?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-x2p85)| +|Debug (.NET Core 2.0) |[![Build status debug (.NET Core 2.0)](https://ci.appveyor.com/api/projects/status/dlc0v4rrolwj0t2t?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli)| +|Debug (.NET Core 2.0) |[![Build status debug (.NET Core 1.0)](https://ci.appveyor.com/api/projects/status/avurf519all92v5u?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-g3guk)| +|Debug (.NET Framework 4.x) |[![Build status debug (.NET Framework 4.x)](https://ci.appveyor.com/api/projects/status/np6723q2uiqofr1a?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-nuf62)| +|Debug (Code DOM)] |[![Build status debug (Code DOM)](https://ci.appveyor.com/api/projects/status/1mw78wkxx50jvab1?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-rhnh0)| +|Debug (miscs)] |[![Build status debug (miscs)](https://ci.appveyor.com/api/projects/status/avufc51yu2cm6idw?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-bo856)| +|Debug (.NET Framework 3.5) |[![Build status debug (.NET Framework 3.5)](https://ci.appveyor.com/api/projects/status/cjp8phlnbwj7gkj9?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-3jme9)| +|Debug (.NET Framework 3.5 Code DOM) |[![Build status debug (.NET Framework 3.5 Code DOM)](https://ci.appveyor.com/api/projects/status/1mw78wkxx50jvab1?svg=true)](https://ci.appveyor.com/project/yfakariya/msgpack-cli-rhnh0)| + ## What is it? This is MessagePack serialization/deserialization for CLI (Common Language Infrastructure) implementations such as .NET Framework, Silverlight, Mono (including Moonlight.) @@ -8,14 +21,15 @@ This library can be used from ALL CLS compliant languages such as C#, F#, Visual ## Usage You can serialize/deserialize objects as following: -1. Create serializer via `MessagePackSerializer.Create` generic method. This method creates dependent types serializers as well. -1. Invoke serializer as following: -** `Pack` method with destination `Stream` and target object for serialization. -** `Unpack` method with source `Stream`. + +1. Create serializer via `MessagePackSerializer.Get` generic method. This method creates dependent types serializers as well. +2. Invoke serializer as following: + * `Pack` method with destination `Stream` and target object for serialization. + * `Unpack` method with source `Stream`. ```c# // Creates serializer. -var serializer = SerializationContext.Default.GetSerializer(); +var serializer = MessagePackSerializer.Get(); // Pack obj to stream. serializer.Pack(stream, obj); // Unpack from stream. @@ -24,19 +38,24 @@ var unpackedObject = serializer.Unpack(stream); ```vb ' Creates serializer. -Dim serializer = SerializationContext.Default.GetSerializer(Of T)() +Dim serializer = MessagePackSerializer.Get(Of T)() ' Pack obj to stream. serializer.Pack(stream, obj) ' Unpack from stream. Dim unpackedObject = serializer.Unpack(stream) ``` +**For production environment, you should instantiate own `SerializationContext` and manage its lifetime. It is good idea to treat it as singleton because `SerializationContext` is thread-safe.** + ## Features * Fast and interoperable binary format serialization with simple API. * Generating pre-compiled assembly for rapid start up. * Flexible MessagePackObject which represents MessagePack type system naturally. +**Note: AOT support is limited yet. Use [serializer pre-generation](https://github.com/msgpack/msgpack-cli/wiki/Xamarin-and-Unity) with `mpu -s` utility or API.** +If you do not pre-generated serializers, MsgPack for CLI uses reflection in AOT environments, it is slower and it sometimes causes AOT related error (`ExecutionEngineException` for runtime JIT compilation). **You also have to call `MessagePackSerializer.PrepareType` and companions in advance to avoid AOT related error.** See [wiki](https://github.com/msgpack/msgpack-cli/wiki/Xamarin-and-Unity) for details. + ## Documentation See [wiki](https://github.com/msgpack/msgpack-cli/wiki) @@ -55,44 +74,104 @@ See [wiki](https://github.com/msgpack/msgpack-cli/wiki) ### For .NET Framework -1. Install recent Windows SDK (at least, .NET Framework 4 Client Profile and MSBuild is needed.)
- Or install Visual Studio or Visual Studio Express. - 1. If you want to build unit test assemblies, install NuGet and then restore NUnit packages. -2. Run: +1. Install Visual Studio 2017 (Community edition is OK) and 2015 (for MsgPack.Windows.sln). + * You must install .NET Framework 3.5, 4.x, .NET Core, and Xamarin dev tools to build all builds successfully. + If you do not want to install options, edit `` element in `*.csproj` files to exclude platforms you want to exclude. +2. Install latest .NET Core SDK. +3. Run with Visual Studio Developer Command Prompt: + msbuild MsgPack.sln /t:Restore msbuild MsgPack.sln - Or (for .NET 3.5 drops and Unity 3D drops): + Or (for Unity 3D drops): + msbuild MsgPack.compats.sln /t:Restore msbuild MsgPack.compats.sln Or (for Windows Runtime/Phone drops and Silverlight 5 drops): + msbuild MsgPack.Windows.sln /t:Restore msbuild MsgPack.Windows.sln - Or (for Xamarin drops, you must have Xamarin Business or upper license and Mac machine on the LAN to build on Windows): + Or (for Xamarin unit testing, you must have Xamarin Business or upper license and Mac machine on the LAN to build on Windows): + msbuild MsgPack.Xamarin.sln /t:Restore msbuild MsgPack.Xamarin.sln Or open one of above solution files in your IDE and run build command in it. ### For Mono -Open MsgPack.mono.sln with MonoDevelop and then click **Build** menu item. -(Of cource, you can build via xbuild.) +1. Install latest Mono and .NET Core SDK. +2. Now, you can build MsgPack.sln and MsgPack.Xamarin.sln with above instructions and `msbuild` in latest Mono. Note that `xbuild` does not work because it does not support latest csproj format. ### Own Unity 3D Build -First of all, there are binary drops on github release page, you should use it to save your time. -Because we will not guarantee source code organization compatibilities, we might add/remove non-public types or members, which should break source code build. -If you want to import sources, you must include just only described on MsgPack.Unity3D.csproj. +First of all, there are binary drops on github release page, you should use it to save your time. +Because we will not guarantee source code organization compatibilities, we might add/remove non-public types or members, which should break source code build. +If you want to import sources, you must include just only described on MsgPack.Unity3D.csproj. If you want to use ".NET 2.0 Subset" settings, you must use just only described on MsgPack.Unity3D.CorLibOnly.csproj file, and define `CORLIB_ONLY` compiler constants. +### Xamarin Android testing + +If you run on Windows, it is recommended to use HXM instead of Hyper-V based emulator. +You can disable Hyper-V from priviledged (administrator) powershell as follows: + +```powershell +Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Hypervisor +``` + +If you want to use Hyper-V again (such as for Docker for Windows etc.), you can do it by following in priviledged (administrator) powershell: + +```powershell +Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Hypervisor +``` + +#### Xamarin Android Trouble shooting tips + +* **Q:** Javac shows compilation error. + * **A:** Rebuild the test project and try it run again. + +### Xamarin iOS testing + +You must create provisoning profiles in your MacOS devices. +See [Xamarin documents about provisining](https://developer.xamarin.com/guides/ios/getting_started/installation/device_provisioning/free-provisioning/) for details. + +There are bundle IDs of current iOS tests: + +* `org.msgpack.msgpack-cli-xamarin-ios-test` +* `org.msgpack.msgpack-cli-xamarin-ios-test-packer` +* `org.msgpack.msgpack-cli-xamarin-ios-test-unpacker` +* `org.msgpack.msgpack-cli-xamarin-ios-test-unpacking` +* `org.msgpack.msgpack-cli-xamarin-ios-test-timestamp` +* `org.msgpack.msgpack-cli-xamarin-ios-test-arrayserialization` +* `org.msgpack.msgpack-cli-xamarin-ios-test-mapserialization` + +*Note that some reflection based serializer tests failed with AOT related limitation.* + +#### Xamarin iOS Trouble shooting tips + +See [Xamarin's official trouble shooting docs first.](https://developer.xamarin.com/guides/ios/getting_started/installation/windows/connecting-to-mac/troubleshooting/) + +* **Q:** An error occurred while running unit test project. + * **A:** Rebuild the project and rerun it. Or, login your Mac again, ant retry it. +* **Q:** It is hard to read English. + * **A:** You can read localized Xamarin docs with putting `{region}-{lang}` as the first component of URL path such as `https://developer.xamarin.com/ja-jp/guides/...`. + +## Maintenance + +### MsgPack.Windows.sln + +This solution contains Silverlight5 and (old) UWP project for backward compability. They are required Visual Studio 2015 to build and test. +You can download Visual Studio 2015 community edition from [here](https://visualstudio.microsoft.com/vs/older-downloads/). + +**You do not have to install Visual Studio 2015 as long as you don't edit/test/build Silverlight and/or old UWP project.** + ## See also -* GitHub Page : http://cli.msgpack.org/ -* Wiki (documentation) : https://github.com/msgpack/msgpack-cli/wiki -* API Reference : http://cli.msgpack.org/doc/top.html -* Issue tracker : https://github.com/msgpack/msgpack-cli/issues -* MSBuild reference : http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx -* Mono xbuild reference : http://www.mono-project.com/Microsoft.Build +* GitHub Page : http://cli.msgpack.org/ +* Wiki (documentation) : https://github.com/msgpack/msgpack-cli/wiki +* API Reference : http://cli.msgpack.org/doc/top.html +* Issue tracker : https://github.com/msgpack/msgpack-cli/issues +* MSBuild reference : http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx +* Mono xbuild reference : http://www.mono-project.com/Microsoft.Build diff --git a/Sync.Test.json b/Sync.Test.json new file mode 100644 index 000000000..2677a2afa --- /dev/null +++ b/Sync.Test.json @@ -0,0 +1,420 @@ +[ + { + "name": "MsgPack.UnitTest.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "Serialization/AotTest.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen35/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Dummies/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Mono/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/_SetUpFixture.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CodeDomCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CompositeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/FromExpressionTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAndDataMemberMixedTarget.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAttributeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/SerializerGeneratorTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/PreGeneratedSerializerGenerator.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/RoslynCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/TempFileDependentAssemblyManager.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*FieldBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/_SetUpFixture.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Augments.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/TestSuite.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/Array*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/Map*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/PreGenerated*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/*Packer*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/*Unpacker*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Unpacking*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/TimeStamp*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/TimeStamp*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/ArraySegmentEqualityComparer`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/PreGeneratedSerializerActivator*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/gen/MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/gen/MsgPack_Serialization_InnerSerializer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/gen/MsgPack_Serialization_OuterSerializer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/gen/MsgPack_Serialization_TestValueTypeSerializer.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Packer.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/*Packer*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/*Unpacker*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/CollectionAssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/SplittingStream.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/StreamExtensions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestRandom.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Unpacker.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/*Unpacker*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/CollectionAssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/SplittingStream.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/StreamExtensions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestRandom.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Unpacking.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/Unpacking*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/CollectionAssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/SplittingStream.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/StreamExtensions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestRandom.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Timestamp.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/TimeStamp*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/TimeStamp*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/LegacyJapaneseCultureInfo.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/CollectionAssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/SplittingStream.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/StreamExtensions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestRandom.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.ArraySerialization.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/gen/**/*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/Array*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/Complex*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*Field*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/CollectionAssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Image.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/AddOnlyCollection`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/ArraySegmentEqualityComparer`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/AutoMessagePackSerializerTest.Types.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/BaseCollections.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/ComplexType*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/Data*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/EchoKeyedCollection_2MessagePackSerializer`2.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/EnumSerializationTest.EnumDefinitions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/IVerifiable.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/IVerifiable`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/MillisecondsDateTimeComparer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/MillisecondsDateTimeOffsetComparer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/NilImplicationTestTarget.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/PreGeneratedSerializerActivator*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/SerializationTargets.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/SimpleCollection`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/StringKeyedCollection.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/TestValueType.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/TypeWith*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/SplittingStream.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/StreamExtensions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestRandom.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.MapSerialization.Xamarin.iOS", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/gen/**/*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/Complex*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/Map*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*Field*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/CollectionAssertEx.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Image.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/AddOnlyCollection`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/ArraySegmentEqualityComparer`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/AutoMessagePackSerializerTest.Types.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/BaseCollections.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/ComplexType*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/Data*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/EchoKeyedCollection_2MessagePackSerializer`2.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/EnumSerializationTest.EnumDefinitions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/IVerifiable.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/IVerifiable`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/MillisecondsDateTimeComparer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/MillisecondsDateTimeOffsetComparer.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/NilImplicationTestTarget.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/PreGeneratedSerializerActivator*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/SerializationTargets.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/SimpleCollection`1.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/StringKeyedCollection.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/TestValueType.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/TypeWith*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/SplittingStream.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/StreamExtensions.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestRandom.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Xamarin.Android", + "base": "MsgPack.UnitTest.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Xamarin.iOS/Main.cs"}, + {"type": "remove", "path": "Resources/Resource.Designer.cs"}, + {"type": "remove", "path": "Serialization/AotTest.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Packer.Xamarin.Android", + "base": "MsgPack.UnitTest.Packer.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.Packer.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Packer.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Packer.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Packer.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Packer.Xamarin.iOS/Main.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Unpacker.Xamarin.Android", + "base": "MsgPack.UnitTest.Unpacker.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.Unpacker.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacker.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacker.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacker.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacker.Xamarin.iOS/Main.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Unpacking.Xamarin.Android", + "base": "MsgPack.UnitTest.Unpacking.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.Unpacking.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacking.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacking.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacking.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Unpacking.Xamarin.iOS/Main.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Timestamp.Xamarin.Android", + "base": "MsgPack.UnitTest.Timestamp.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.Timestamp.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Timestamp.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Timestamp.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Timestamp.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Timestamp.Xamarin.iOS/Main.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.ArraySerialization.Xamarin.Android", + "base": "MsgPack.UnitTest.ArraySerialization.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.ArraySerialization.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.ArraySerialization.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.ArraySerialization.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.ArraySerialization.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.ArraySerialization.Xamarin.iOS/Main.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.MapSerialization.Xamarin.Android", + "base": "MsgPack.UnitTest.MapSerialization.Xamarin.iOS", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.MapSerialization.Xamarin.iOS/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.MapSerialization.Xamarin.iOS/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.MapSerialization.Xamarin.iOS/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.MapSerialization.Xamarin.iOS/AppDelegate.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.MapSerialization.Xamarin.iOS/Main.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Uwp", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen35/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Dummies/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Mono/**/*.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/_SetUpFixture.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CodeDomCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CompositeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/FromExpressionTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAndDataMemberMixedTarget.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAttributeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/SerializerGeneratorTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/PreGeneratedSerializerGenerator.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/RoslynCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/TempFileDependentAssemblyManager.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*FieldBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/_SetUpFixture.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Augments.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/TestSuite.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs"}, + {"type": "include", "path": "../MsgPack.NUnitPortable/TimeoutAttribute.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Uwp.Aot", + "base": "MsgPack.UnitTest.Uwp", + "globs": [ + ] + }, + { + "name": "MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop", + "base": "MsgPack.UnitTest.Uwp", + "globs": [ + {"type": "include", "path": "../../src/MsgPack/Tuple`n.cs"}, + {"type": "remove", "path": "./Assets/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen/**/*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/gen35/**/*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Dummies/**/*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Mono/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen35/MsgPack_Serialization_PolymorphicMemberTypeKnownType*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen35/MsgPack_Serialization_PolymorphicMemberTypeRuntimeType*.cs"}, + {"type": "remove", "path": "../MsgPack.NUnitPortable/TimeoutAttribute.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CodeDomCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CompositeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/FromExpressionTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAndDataMemberMixedTarget.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAttributeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/RoslynCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/SerializerGeneratorTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/TempFileDependentAssemblyManager.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*FieldBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/_SetUpFixture.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Augments.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/ExceptionTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/MessagePackObjectTest.RuntimeSerialization.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/TestSuite.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/UnpackingTest.Combinations*.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.WinRT", + "base": "MsgPack.UnitTest.Uwp", + "globs": [ + {"type": "remove", "path": "../MsgPack.NUnitPortable/TimeoutAttribute.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CodeDomCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/FromExpressionTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/PreGenerated*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/RoslynCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/SerializerGeneratorTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/TempFileDependentAssemblyManager.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*FieldBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*GenerationBased*.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/_SetUpFixture.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAndDataMemberMixedTarget.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/Serialization/MessagePackMemberAttributeTest.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/_SetUpFixture.cs"}, + {"type": "include", "path": "../MsgPack.UnitTest/TestSuite.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.BclExtensions.WinRT", + "base": "MsgPack.UnitTest.BclExtensions", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.BclExtensions/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.BclExtensions/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.BclExtensions/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/obj/**/*.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.BclExtensions/Serialization/*CodeDomBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.BclExtensions/Serialization/*FieldBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.BclExtensions/Serialization/RoslynCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.BclExtensions/Serialization/TempFileDependentAssemblyManager.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Silverlight.WindowsPhone", + "base": "MsgPack.UnitTest.WinRT", + "globs": [ + ] + }, + { + "name": "MsgPack.UnitTest.WinRT.WindowsPhone", + "base": "MsgPack.UnitTest.WinRT", + "globs": [ + ] + }, + { + "name": "MsgPack.UnitTest.Silverlight.5", + "base": "MsgPack.UnitTest", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/obj/**/*.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen35/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Dummies/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Mono/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/gen/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/PreGenerated*"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/_SetUpFixture.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/AppendableReadOnlyCollections.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/ArrayGenerationBasedAutoMessagePackSerializerTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/ArrayGenerationBasedEnumSerializationTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CodeDomCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/CompositeTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/FromExpressionTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/GenerationBasedNilImplicationTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MapGenerationBasedAutoMessagePackSerializerTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/MapGenerationBasedEnumSerializationTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/SerializerGeneratorTest.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/RoslynCodeGeneration.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/TempFileDependentAssemblyManager.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/Serialization/*FieldBased*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/_SetUpFixture.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/AssertEx.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest/TestSuite.cs"} + ] + }, + { + "name": "MsgPack.UnitTest.Silverlight.5.FullTrust", + "base": "MsgPack.UnitTest.Silverlight.5", + "globs": [ + {"type": "include", "path": "../MsgPack.UnitTest.Silverlight.5/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Silverlight.5/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Silverlight.5/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.UnitTest.Silverlight.5/App.xaml.cs"} + ] + } +] \ No newline at end of file diff --git a/Sync.Test.xml b/Sync.Test.xml deleted file mode 100644 index a8a130227..000000000 --- a/Sync.Test.xml +++ /dev/null @@ -1,239 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Sync.json b/Sync.json new file mode 100644 index 000000000..3ad947057 --- /dev/null +++ b/Sync.json @@ -0,0 +1,144 @@ +[ + { + "name": "MsgPack.Uwp", + "globs": [ + {"type": "include", "path": "../CommonAssemblyInfo.cs"}, + {"type": "include", "path": "../MsgPack/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/obj/**/*.cs"}, + {"type": "include", "path": "**/*.cs"}, + {"type": "remove", "path": "obj/**/*.cs"}, + + {"type": "remove", "path": "../MsgPack/Serialization/AbstractSerializers/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CodeDomSerializers/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/EmittingSerializers/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/ExpressionSerializers/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/Metadata/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/Reflection/TracingILGenerator.*"}, + {"type": "remove", "path": "../MsgPack/Serialization/CallbackEnumMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CallbackMessagePackSerializer`1.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CodeGenerationSink.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DependentAssemblyManager.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializerNameResolver.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/FromExpression.*"}, + {"type": "remove", "path": "../MsgPack/Serialization/IndividualFileCodeGenerationSink.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/ISerializerGeneratorConfiguration.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/ReflectionExtensions.ConstructorDelegate.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SerializerAssemblyGenerationConfiguration.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SerializerCodeInformation.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SerializerCodeGenerationConfiguration.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SerializerCodeGenerationContext.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SerializerCodeGenerationResult.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SerializerGenerator.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/TeeTextWriter.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/SingleTextWriterCodeGenerationSink.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/Tracer.cs"}, + {"type": "remove", "path": "../MsgPack/Contract.cs"}, + {"type": "remove", "path": "../MsgPack/Delegates.cs"}, + {"type": "remove", "path": "../MsgPack/MPContract.cs"}, + {"type": "remove", "path": "../MsgPack/NetFxCompatibilities.cs"}, + {"type": "remove", "path": "../MsgPack/Tuple`n.cs"}, + {"type": "remove", "path": "../MsgPack/UnsafeNativeMethods.cs"}, + {"type": "remove", "path": "../MsgPack/Volatile.cs"}, + {"type": "remove", "path": "../MsgPack/Validation.cs"} + ] + }, + { + "name": "MsgPack.Unity.Full", + "base": "MsgPack.Uwp", + "globs": [ + {"type": "include", "path": "../MsgPack/Serialization/Tracer.cs"}, + {"type": "include", "path": "../MsgPack/MPContract.cs"}, + {"type": "include", "path": "../MsgPack/Volatile.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CollectionSerializers/CollectionSerializerBase`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CollectionSerializers/DictionarySerializerBase`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CollectionSerializers/ReadOnlyCollectionMessagePackSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CollectionSerializers/ReadOnlyDictionaryMessagePackSerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyCollectionMessagePackSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyDictionaryMessagePackSerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/FileTimeMessagePackSerializerProvider.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/FSharpCollectionSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/FSharpMapSerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/ImmutableCollectionSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/ImmutableDictionarySerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/ImmutableStackSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/NativeFileTimeMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Numerics_ComplexMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/TimestampFileTimeMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/UnixEpocFileTimeMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/ReflectionSerializers/ReflectionTupleMessagePackSerializer`1.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/ReflectionExtensions.ConstructorDelegate.cs"}, + {"type": "remove", "path": "../MsgPack/BufferedStream.cs"}, + {"type": "remove", "path": "../MsgPack/NetStandardCompatibility.cs"}, + {"type": "remove", "path": "../MsgPack/TaskAugument.cs"}, + {"type": "remove", "path": "../MsgPack/UnsafeNativeMethods.cs"}, + {"type": "remove", "path": "../MsgPack/Validation.cs"} + ] + }, + { + "name": "MsgPack.Unity", + "base": "MsgPack.Unity.Full", + "globs": [ + {"type": "include", "path": "../MsgPack.Unity.Full/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.Unity.Full/Properties/**/*.cs"}, + {"type": "remove", "path": "../MsgPack.Unity.Full/obj/**/*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Queue_1MessagePackSerializer`1.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Stack_1MessagePackSerializer`1.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_UriMessagePackSerializer.cs"} + ] + }, + { + "name": "MsgPack.Silverlight.5", + "base": "MsgPack.Uwp", + "globs": [ + {"type": "include", "path": "../MsgPack/UnsafeNativeMethods.cs"}, + {"type": "include", "path": "../MsgPack/Volatile.cs"}, + {"type": "include", "path": "../MsgPack/Serialization/Metadata/_MessagePackSerializer.cs"}, + {"type": "include", "path": "../MsgPack/Serialization/Metadata/_SerializationContext.cs"}, + {"type": "include", "path": "../MsgPack/Serialization/Reflection/TracingILGenerator*.cs"}, + {"type": "include", "path": "../MsgPack/Serialization/ReflectionExtensions.ConstructorDelegate.cs"}, + {"type": "include", "path": "../MsgPack/Serialization/FromExpression*.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CollectionSerializers/ReadOnlyCollectionMessagePackSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/CollectionSerializers/ReadOnlyDictionaryMessagePackSerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyCollectionMessagePackSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyDictionaryMessagePackSerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/FileTimeMessagePackSerializerProvider.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/FSharpCollectionSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/FSharpMapSerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/ImmutableCollectionSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/ImmutableDictionarySerializer`3.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/ImmutableStackSerializer`2.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/NativeFileTimeMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_QueueMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_StackMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/TimestampFileTimeMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/UnixEpocFileTimeMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/BufferedStream.cs"}, + {"type": "remove", "path": "../MsgPack/NetStandardCompatibility.cs"}, + {"type": "remove", "path": "../MsgPack/TaskAugument.cs"} + ] + }, + { + "name": "MsgPack.Silverlight.WindowsPhone", + "base": "MsgPack.Uwp", + "globs": [ + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_QueueMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_StackMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Numerics_ComplexMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs"}, + {"type": "remove", "path": "../MsgPack/Serialization/Reflection/ReflectionHelpers.cs"}, + {"type": "remove", "path": "../MsgPack/BufferedStream.cs"}, + {"type": "remove", "path": "../MsgPack/NetStandardCompatibility.cs"}, + {"type": "remove", "path": "../MsgPack/TaskAugument.cs"} + ] + } +] \ No newline at end of file diff --git a/Sync.xml b/Sync.xml deleted file mode 100644 index 253f3fadd..000000000 --- a/Sync.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SyncProjects.bat b/SyncProjects.bat index e93264fad..d75777c19 100644 --- a/SyncProjects.bat +++ b/SyncProjects.bat @@ -1,4 +1,8 @@ -:: src -@.\tools\SyncProjects\bin\SyncProjects.exe -:: test -@.\tools\SyncProjects\bin\SyncProjects.exe -d Sync.Test.xml -s test \ No newline at end of file +@setlocal +@rem src +@dotnet run -p .\tools\SyncProjects2\SyncProjects2\SyncProjects2.csproj +@if not ERRORLEVEL 0 exit /b %ERRORLEVEL% + +@rem test +@dotnet run -p .\tools\SyncProjects2\SyncProjects2\SyncProjects2.csproj -d Sync.Test.json -s test +@exit /b %ERRORLEVEL% diff --git a/appveyor-debug-codedom.yml b/appveyor-debug-codedom.yml new file mode 100644 index 000000000..d4aebb8cc --- /dev/null +++ b/appveyor-debug-codedom.yml @@ -0,0 +1,39 @@ +version: '{branch}-{build}' +image: Visual Studio 2017 +skip_tags: true +configuration: Debug +assembly_info: + patch: true + file: '**\*AssemblyInfo.cs' + assembly_version: $(AssemblyBaseVersion).0 + assembly_file_version: $(AssemblyBaseVersion).{build} + assembly_informational_version: $(PackageVersion) +environment: + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild +install: +- cmd: >- + cd .\build +- ps: >- + ./SetBuildEnv.ps1 + + cd .. +build_script: +- ps: >- + Write-Host "Configuration=${env:CONFIGURATION}" + + cd ./build + + ./Build.ps1 + + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + + cd .. +test_script: +- cmd: >- + cd ./build + + ./RunUnitTests-CodeDOM.cmd diff --git a/appveyor-debug-netcore10.yml b/appveyor-debug-netcore10.yml new file mode 100644 index 000000000..5389a70c0 --- /dev/null +++ b/appveyor-debug-netcore10.yml @@ -0,0 +1,39 @@ +version: '{branch}-{build}' +image: Visual Studio 2017 +skip_tags: true +configuration: Debug +assembly_info: + patch: true + file: '**\*AssemblyInfo.cs' + assembly_version: $(AssemblyBaseVersion).0 + assembly_file_version: $(AssemblyBaseVersion).{build} + assembly_informational_version: $(PackageVersion) +environment: + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild +install: +- cmd: >- + cd .\build +- ps: >- + ./SetBuildEnv.ps1 + + cd .. +build_script: +- ps: >- + Write-Host "Configuration=${env:CONFIGURATION}" + + cd ./build + + ./Build.ps1 + + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + + cd .. +test_script: +- cmd: >- + cd ./build + + ./RunUnitTests-NetCore10.cmd diff --git a/appveyor-debug.yml b/appveyor-debug.yml index 64e8f612e..8164e2b83 100644 --- a/appveyor-debug.yml +++ b/appveyor-debug.yml @@ -1,15 +1,7 @@ version: '{branch}-{build}' +image: Visual Studio 2017 skip_tags: true configuration: Debug -init: -- cmd: >- - cd \ - - appveyor DownloadFile http://dl.google.com/android/android-sdk_r24.3.4-windows.zip - - 7z x android-sdk_r24.3.4-windows.zip > nul - - cd %APPVEYOR_BUILD_FOLDER% assembly_info: patch: true file: '**\*AssemblyInfo.cs' @@ -17,15 +9,13 @@ assembly_info: assembly_file_version: $(AssemblyBaseVersion).{build} assembly_informational_version: $(PackageVersion) environment: - ANDROID_HOME: C:\android-sdk-windows + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild install: +- cmd: >- + cd .\build - ps: >- - cd ./build - ./SetBuildEnv.ps1 - ./UpdateAndroidSdk.cmd - cd .. build_script: - ps: >- @@ -35,11 +25,15 @@ build_script: ./Build.ps1 + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + cd .. test_script: - cmd: >- cd ./build ./RunUnitTests.cmd - - cd .. diff --git a/appveyor-debug35-codedom.yml b/appveyor-debug35-codedom.yml new file mode 100644 index 000000000..0cc031f37 --- /dev/null +++ b/appveyor-debug35-codedom.yml @@ -0,0 +1,39 @@ +version: '{branch}-{build}' +image: Visual Studio 2017 +skip_tags: true +configuration: Debug +assembly_info: + patch: true + file: '**\*AssemblyInfo.cs' + assembly_version: $(AssemblyBaseVersion).0 + assembly_file_version: $(AssemblyBaseVersion).{build} + assembly_informational_version: $(PackageVersion) +environment: + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild +install: +- cmd: >- + cd .\build +- ps: >- + ./SetBuildEnv.ps1 + + cd .. +build_script: +- ps: >- + Write-Host "Configuration=${env:CONFIGURATION}" + + cd ./build + + ./Build.ps1 + + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + + cd .. +test_script: +- cmd: >- + cd ./build + + ./RunUnitTests35-codedom.cmd diff --git a/appveyor-debug35.yml b/appveyor-debug35.yml new file mode 100644 index 000000000..817f5ce52 --- /dev/null +++ b/appveyor-debug35.yml @@ -0,0 +1,39 @@ +version: '{branch}-{build}' +image: Visual Studio 2017 +skip_tags: true +configuration: Debug +assembly_info: + patch: true + file: '**\*AssemblyInfo.cs' + assembly_version: $(AssemblyBaseVersion).0 + assembly_file_version: $(AssemblyBaseVersion).{build} + assembly_informational_version: $(PackageVersion) +environment: + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild +install: +- cmd: >- + cd .\build +- ps: >- + ./SetBuildEnv.ps1 + + cd .. +build_script: +- ps: >- + Write-Host "Configuration=${env:CONFIGURATION}" + + cd ./build + + ./Build.ps1 + + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + + cd .. +test_script: +- cmd: >- + cd ./build + + ./RunUnitTests35.cmd diff --git a/appveyor-debug4x.yml b/appveyor-debug4x.yml new file mode 100644 index 000000000..66fff7217 --- /dev/null +++ b/appveyor-debug4x.yml @@ -0,0 +1,39 @@ +version: '{branch}-{build}' +image: Visual Studio 2017 +skip_tags: true +configuration: Debug +assembly_info: + patch: true + file: '**\*AssemblyInfo.cs' + assembly_version: $(AssemblyBaseVersion).0 + assembly_file_version: $(AssemblyBaseVersion).{build} + assembly_informational_version: $(PackageVersion) +environment: + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild +install: +- cmd: >- + cd .\build +- ps: >- + ./SetBuildEnv.ps1 + + cd .. +build_script: +- ps: >- + Write-Host "Configuration=${env:CONFIGURATION}" + + cd ./build + + ./Build.ps1 + + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + + cd .. +test_script: +- cmd: >- + cd ./build + + ./RunUnitTests4x.cmd diff --git a/appveyor-release.yml b/appveyor-release.yml index 18a75a3ba..49dca6f53 100644 --- a/appveyor-release.yml +++ b/appveyor-release.yml @@ -1,17 +1,10 @@ version: '{branch}-{build}' +image: Visual Studio 2017 branches: only: - master + - /[0-9]+\.[0-9]+(\.[xX])?/ configuration: Release -init: -- cmd: >- - cd \ - - appveyor DownloadFile http://dl.google.com/android/android-sdk_r24.3.4-windows.zip - - 7z x android-sdk_r24.3.4-windows.zip > nul - - cd %APPVEYOR_BUILD_FOLDER% assembly_info: patch: true file: '**\*AssemblyInfo.cs' @@ -19,15 +12,13 @@ assembly_info: assembly_file_version: $(AssemblyBaseVersion).{build} assembly_informational_version: $(PackageVersion) environment: - ANDROID_HOME: C:\android-sdk-windows + XamarinMSBuildExtensionsPath: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild install: +- cmd: >- + cd .\build - ps: >- - cd ./build - ./SetBuildEnv.ps1 - ./UpdateAndroidSdk.cmd - cd .. build_script: - ps: >- @@ -37,21 +28,43 @@ build_script: ./Build.ps1 + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to build." + exit 1 + } + appveyor PushArtifact "../dist/MsgPack.Cli.${env:PackageVersion}.nupkg" + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to publish nupkg." + exit 1 + } + appveyor PushArtifact "../dist/MsgPack.Cli.${env:PackageVersion}.symbols.nupkg" + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to publish symbol nupkg." + exit 1 + } + appveyor PushArtifact "../dist/MsgPack.Cli.${env:PackageVersion}.zip" + if ( $LastExitCode -ne 0 ) + { + Write-Error "Failed to publish zip." + exit 1 + } + cd .. deploy: - provider: Environment name: msgpack-cli-nuget on: - branch: master APPVEYOR_REPO_TAG: true - provider: Environment name: msgpack-cli-github on: - branch: master APPVEYOR_REPO_TAG: true diff --git a/assets/Big.png b/asset/Big.png similarity index 100% rename from assets/Big.png rename to asset/Big.png diff --git a/assets/Small.png b/asset/Small.png similarity index 100% rename from assets/Small.png rename to asset/Small.png diff --git a/assets/icon.png b/asset/icon.png similarity index 100% rename from assets/icon.png rename to asset/icon.png diff --git a/assets/msgpack.ico b/asset/msgpack.ico similarity index 100% rename from assets/msgpack.ico rename to asset/msgpack.ico diff --git a/build/Build.ps1 b/build/Build.ps1 index 1f2f0fbcc..c397399b9 100644 --- a/build/Build.ps1 +++ b/build/Build.ps1 @@ -1,55 +1,41 @@ param([Switch]$Rebuild) +[string]$msbuild = "msbuild" + if ( $env:APPVEYOR -eq "True" ) { - [string]$builder = "MSBuild.exe" - [string]$winBuilder = "MSBuild.exe" - [string]$nuget = "nuget" - [string]$nugetVerbosity = "quiet" - [string]$dotnetVerbosity = "Warning" # AppVeyor should have right MSBuild and dotnet-cli... # Android SDK should be installed in init and ANDROID_HOME should be initialized before this script. } else { - # Ensure Android SDK for API level 10 is installed. - # Thanks to https://github.com/googlesamples/android-ndk/pull/80 - - [string]$env:ANDROID_HOME = "$env:localappdata/Android/android-sdk/" - - if ( !( Test-Path "$env:ANDROID_HOME/tools/android.bat" ) ) - { - Write-Error "Android SDK is required." - exit 1 - } - - ./SetBuildEnv.ps1 - if ( $env:SKIP_ANDROID_SDK_UPDATE -ne "True" ) - { - ./UpdateAndroidSdk.cmd - } - [string]$builder = "${env:ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe" - [string]$winBuilder = "${env:ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe" - [string]$nuget = "../.nuget/nuget.exe" - [string]$nugetVerbosity = "normal" - [string]$dotnetVerbosity = "Information" - - if ( !( Test-Path( "$winBuilder" ) ) ) + [string]$VSMSBuildExtensionsPath = $null + + $msbuildCandidates = @( + "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Community\MSBuild\15.0\bin\MSBuild.exe", + "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin\MSBuild.exe", + "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\bin\MSBuild.exe", + "${env:ProgramFiles}\Microsoft Visual Studio\2017\Community\MSBuild\15.0\bin\MSBuild.exe", + "${env:ProgramFiles}\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin\MSBuild.exe", + "${env:ProgramFiles}\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\bin\MSBuild.exe" + ) + foreach ( $msbuildCandidate in $msbuildCandidates ) { - $winBuilder = "${env:ProgramFiles}\MSBuild\14.0\Bin\MSBuild.exe" + if ( ( Test-Path $msbuildCandidate ) ) + { + $VSMSBuildExtensionsPath = [IO.Path]::GetFullPath( [IO.Path]::GetDirectoryName( $msbuildCandidate ) + "\..\..\" ) + break; + } } - if ( !( Test-Path( "$winBuilder" ) ) ) + + if ( $VSMSBuildExtensionsPath -eq $null ) { - Write-Error "MSBuild v14 is required." + Write-Error "Failed to locate MSBuild.exe which can build .NET Core and .NET 3.5. VS2017 is required." exit 1 } - if ( !( Test-Path( "${env:ProgramFiles}\dotnet\dotnet.exe" ) ) ) - { - Write-Error "DotNet CLI is required." - exit 1 - } + ./SetBuildEnv.ps1 } [string]$buildConfig = 'Release' @@ -62,7 +48,6 @@ if ( ![String]::IsNullOrWhitespace( $env:CONFIGURATION ) ) [string]$slnCompat = '../MsgPack.compats.sln' [string]$slnWindows = '../MsgPack.Windows.sln' [string]$slnXamarin = '../MsgPack.Xamarin.sln' -[string]$projCoreClr = "../src/Msgpack.CoreClr" $buildOptions = @( '/v:minimal' ) if( $Rebuild ) @@ -71,6 +56,9 @@ if( $Rebuild ) } $buildOptions += "/p:Configuration=${buildConfig}" +$restoreOptions = "/v:minimal" + +Write-Host "Clean up directories..." # Unity if ( !( Test-Path "./MsgPack-CLI" ) ) @@ -102,103 +90,79 @@ if ( !( Test-Path "./MsgPack-CLI/mpu" ) ) } # build -& $nuget restore $sln -Verbosity $nugetVerbosity + +Write-Host "Restore $sln packages..." + +& $msbuild /t:restore $sln $restoreOptions if ( $LastExitCode -ne 0 ) { Write-Error "Failed to restore $sln" exit $LastExitCode } -& $builder $sln $buildOptions +Write-Host "Build $sln..." + +& $msbuild $sln $buildOptions if ( $LastExitCode -ne 0 ) { Write-Error "Failed to build $sln" exit $LastExitCode } -& $nuget restore $slnCompat -Verbosity $nugetVerbosity +Write-Host "Restore $slnCompat packages..." + +& $msbuild /t:restore $slnCompat $restoreOptions if ( $LastExitCode -ne 0 ) { Write-Error "Failed to restore $slnCompat" exit $LastExitCode } -& $builder $slnCompat $buildOptions +Write-Host "Build $slnCompat..." + +& $msbuild $slnCompat $buildOptions if ( $LastExitCode -ne 0 ) { Write-Error "Failed to build $slnCompat" exit $LastExitCode } -& $nuget restore $slnWindows -Verbosity $nugetVerbosity -if ( $LastExitCode -ne 0 ) -{ - Write-Error "Failed to restore $slnWindows" - exit $LastExitCode -} +Write-Host "Restore $slnWindows packages..." -& $winBuilder $slnWindows $buildOptions -if ( $LastExitCode -ne 0 ) +if ( $env:APPVEYOR -eq "True" ) { - Write-Error "Failed to build $slnWindows" - exit $LastExitCode + # Use nuget for legacy environments. + nuget restore $slnWindows -Verbosity quiet } - -& $nuget restore $slnXamarin -Verbosity $nugetVerbosity -if ( $LastExitCode -ne 0 ) +else { - Write-Error "Failed to restore $slnXamarin" - exit $LastExitCode + & $msbuild /t:restore $slnWindows $restoreOptions } -& $builder $slnXamarin $buildOptions if ( $LastExitCode -ne 0 ) { - Write-Error "Failed to build $slnXamarin" + Write-Error "Failed to restore $slnWindows" exit $LastExitCode } -if ( $buildConfig -eq 'Release' ) -{ - Copy-Item ../bin/MonoTouch10 ../bin/Xamarin.iOS10 -Recurse -} +Write-Host "Build $slnWindows..." -dotnet restore $projCoreClr +& $msbuild $slnWindows $buildOptions if ( $LastExitCode -ne 0 ) { - Write-Error "Failed to restore $projNetStandard11" + Write-Error "Failed to build $slnWindows" exit $LastExitCode } -$netstandardBaseCommandLine = @("build", "$projCoreClr", "-c", "$buildConfig") -$netstandard1_1CommandLine = $netstandardBaseCommandLine + @("-f", "netstandard1.1") -$netstandard1_3CommandLine = $netstandardBaseCommandLine + @("-f", "netstandard1.3") if ( $buildConfig -eq 'Release' ) { - $netstandard1_1CommandLine += @("-o", "../bin/netstandard1.1") - $netstandard1_3CommandLine += @("-o", "../bin/netstandard1.3") -} + Write-Host "Build NuGet packages..." -& "dotnet" $netstandard1_1CommandLine -if ( $LastExitCode -ne 0 ) -{ - Write-Error "Failed to build netstd1.1. $netstandard1_1CommandLine" - exit $LastExitCode -} - -& "dotnet" $netstandard1_3CommandLine -if ( $LastExitCode -ne 0 ) -{ - Write-Error "Failed to build netstd1.3. $netstandard1_3CommandLine" - exit $LastExitCode -} - -if ( $buildConfig -eq 'Release' ) -{ - & $nuget pack ../MsgPack.nuspec -Symbols -Version $env:PackageVersion -OutputDirectory ../dist + & $msbuild ../src/MsgPack/MsgPack.csproj /t:pack /v:minimal /p:Configuration=$buildConfig /p:IncludeSource=true /p:IncludeSymbols=true /p:NuspecProperties=version=$env:PackageVersion - Copy-Item ../bin/ ./MsgPack-CLI/ -Recurse -Exclude @("*.vshost.*") - Copy-Item ../tools/mpu/bin/ ./MsgPack-CLI/mpu/ -Recurse -Exclude @("*.vshost.*") + Move-Item ../bin/*.nupkg ../dist/ + Copy-Item ../bin/* ./MsgPack-CLI/ -Recurse -Exclude @("*.vshost.*") + Copy-Item ../tools/mpu/bin/* ./MsgPack-CLI/mpu/ -Recurse -Exclude @("*.vshost.*") [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null # 'latest' should be rewritten with semver manually. if ( ( Test-Path "../dist/MsgPack.Cli.${env:PackageVersion}.zip" ) ) diff --git a/build/RunUnitTests-CodeDOM.cmd b/build/RunUnitTests-CodeDOM.cmd new file mode 100644 index 000000000..4274d15f5 --- /dev/null +++ b/build/RunUnitTests-CodeDOM.cmd @@ -0,0 +1,8 @@ +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.CodeDom/MsgPack.UnitTest.CodeDom.csproj +if not %errorlevel% == 0 exit /b 1 +@rem WinRT related tests require developer license... +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT/AppPackages/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug.appx +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions.WinRT/AppPackages/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug.appx +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT.WindowsPhone/AppPackages/MsgPack.UnitTest.WinRT.WindowsPhone_1.0.0.0_x86_Debug_Test/MsgPack.UnitTest.WinRT.WindowsPhone_1.0.0.0_x86_Debug.appx +@rem UWP test with NUnit3 is not available in cli +@rem Xamarin tests are not available in cli \ No newline at end of file diff --git a/build/RunUnitTests-NetCore10.cmd b/build/RunUnitTests-NetCore10.cmd new file mode 100644 index 000000000..b1ec28612 --- /dev/null +++ b/build/RunUnitTests-NetCore10.cmd @@ -0,0 +1,10 @@ +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj --framework netcoreapp1.0 +if not %errorlevel% == 0 exit /b 1 +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions/MsgPack.UnitTest.BclExtensions.csproj --framework netcoreapp1.0 +if not %errorlevel% == 0 exit /b 1 +@rem WinRT related tests require developer license... +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT/AppPackages/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug.appx +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions.WinRT/AppPackages/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug.appx +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT.WindowsPhone/AppPackages/MsgPack.UnitTest.WinRT.WindowsPhone_1.0.0.0_x86_Debug_Test/MsgPack.UnitTest.WinRT.WindowsPhone_1.0.0.0_x86_Debug.appx +@rem UWP test with NUnit3 is not available in cli +@rem Xamarin tests are not available in cli \ No newline at end of file diff --git a/build/RunUnitTests.cmd b/build/RunUnitTests.cmd index f02d7d50b..ed3e8884c 100644 --- a/build/RunUnitTests.cmd +++ b/build/RunUnitTests.cmd @@ -1,8 +1,7 @@ -nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest/bin/Debug/MsgPack.UnitTest.dll --framework:net-4.5 --result=test-result-net45.xml;format=AppVeyor -nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions/bin/Debug/MsgPack.UnitTest.BclExtensions.dll --framework:net-4.5 --result=test-result-net45-bclext.xml;format=AppVeyor -nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.CodeDom/bin/Debug/MsgPack.UnitTest.CodeDom.dll --framework:net-4.5 --result=test-result-net45-codedom.xml;format=AppVeyor -nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.Net35/bin/Debug/MsgPack.UnitTest.Net35.dll --framework:net-3.5 --result=test-result-net35.xml;format=AppVeyor -nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.CodeDom.Net35/bin/Debug/MsgPack.UnitTest.CodeDom.Net35.dll --framework:net-3.5 --result=test-result-net35-codedom.xml;format=AppVeyor +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj --framework netcoreapp2.0 +if not %errorlevel% == 0 exit /b 1 +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions/MsgPack.UnitTest.BclExtensions.csproj --framework netcoreapp2.0 +if not %errorlevel% == 0 exit /b 1 @rem WinRT related tests require developer license... @rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT/AppPackages/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug.appx @rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions.WinRT/AppPackages/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug.appx diff --git a/build/RunUnitTests35-CodeDOM.cmd b/build/RunUnitTests35-CodeDOM.cmd new file mode 100644 index 000000000..01f40ce6c --- /dev/null +++ b/build/RunUnitTests35-CodeDOM.cmd @@ -0,0 +1,2 @@ +nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.CodeDom.Net35/bin/Debug/net35/MsgPack.UnitTest.CodeDom.Net35.dll --framework:net-3.5 --result=test-result-net35-codedom.xml;format=AppVeyor +if not %errorlevel% == 0 exit /b 1 diff --git a/build/RunUnitTests35.cmd b/build/RunUnitTests35.cmd new file mode 100644 index 000000000..efb3b96e4 --- /dev/null +++ b/build/RunUnitTests35.cmd @@ -0,0 +1,2 @@ +nunit3-console %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.Net35/bin/Debug/net35/MsgPack.UnitTest.Net35.dll --framework:net-3.5 --result=test-result-net35.xml;format=AppVeyor +if not %errorlevel% == 0 exit /b 1 diff --git a/build/RunUnitTests4x.cmd b/build/RunUnitTests4x.cmd new file mode 100644 index 000000000..4b1b79408 --- /dev/null +++ b/build/RunUnitTests4x.cmd @@ -0,0 +1,10 @@ +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj --framework net47 +if not %errorlevel% == 0 exit /b 1 +dotnet test %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions/MsgPack.UnitTest.BclExtensions.csproj --framework net47 +if not %errorlevel% == 0 exit /b 1 +@rem WinRT related tests require developer license... +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT/AppPackages/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.WinRT_1.1.0.0_AnyCPU_Debug.appx +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.BclExtensions.WinRT/AppPackages/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug_Test/MsgPack.UnitTest.BclExtensions.WinRT_1.1.0.0_AnyCPU_Debug.appx +@rem vstest.console /logger:Appveyor /InIsolation %APPVEYOR_BUILD_FOLDER%/test/MsgPack.UnitTest.WinRT.WindowsPhone/AppPackages/MsgPack.UnitTest.WinRT.WindowsPhone_1.0.0.0_x86_Debug_Test/MsgPack.UnitTest.WinRT.WindowsPhone_1.0.0.0_x86_Debug.appx +@rem UWP test with NUnit3 is not available in cli +@rem Xamarin tests are not available in cli \ No newline at end of file diff --git a/build/SetBuildEnv.ps1 b/build/SetBuildEnv.ps1 index 028e080c2..3e955cf1f 100644 --- a/build/SetBuildEnv.ps1 +++ b/build/SetBuildEnv.ps1 @@ -1,13 +1,17 @@ # Set versions for AssemblyInfo.cs $version = ( Get-Content .\Version.txt ); -$env:AssemblyBaseVersion = $version | foreach{ if( $_ -match "^\d+\.\d+" ){ $matches[0] } } +$env:AssemblyBaseVersion = $version | foreach{ if( $_ -match "^\d+\.\d+" ){ $matches[0] } } if ( $env:APPVEYOR_REPO_TAG -ne "True" ) { if ( ${env:APPVEYOR_BUILD_NUMBER} -eq $null ) { $now = [DateTime]::UtcNow $daysSpan = $now - ( New-Object DateTime( $now.Year, 1, 1 ) ) - $env:PackageVersion = "${version}-{0:yy}{1:000}" -f @( $now, $daysSpan.Days ) + $env:PackageVersion = "${version}-{0:yy}{1:000}-{2:000}" -f @( $now, $daysSpan.Days, ( $now.TimeOfDay.TotalMinutes / 2 ) ) + } + elseif ( ${version} -match "^[\d.]+$" ) + { + $env:PackageVersion = "${version}-${env:APPVEYOR_BUILD_NUMBER}" } else { @@ -18,3 +22,5 @@ else { $env:PackageVersion = $version } + +Write-Host "version:'${version}', AssemblyBaseVersion:'${env:AssemblyBaseVersion}', PackageVersion:'${env:PackageVersion}'" diff --git a/build/UpdateAndroidSdk.cmd b/build/UpdateAndroidSdk.cmd index 25f2504a3..0e0d27807 100644 --- a/build/UpdateAndroidSdk.cmd +++ b/build/UpdateAndroidSdk.cmd @@ -1 +1 @@ -echo y | "%ANDROID_HOME%/tools/android.bat" --silent update sdk --no-ui --all --filter android-10,android-23,platform-tools,tools,build-tools-23.0.3 +echo y | "%ProgramFiles(x86)%\Android\android-sdk\tools\android.bat" --silent update sdk --no-ui --all --filter android-10,platform-tools,tools,build-tools-23.0.3 diff --git a/build/Version.txt b/build/Version.txt index bde5e82e7..afaf360d3 100644 --- a/build/Version.txt +++ b/build/Version.txt @@ -1 +1 @@ -0.7.0-beta2 \ No newline at end of file +1.0.0 \ No newline at end of file diff --git a/samples/Samples/Sample01_BasicUsage.cs b/samples/Samples/Sample01_BasicUsage.cs index 9223bc7b5..37c660a08 100644 --- a/samples/Samples/Sample01_BasicUsage.cs +++ b/samples/Samples/Sample01_BasicUsage.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -30,7 +30,7 @@ namespace Samples { /// - /// A simple sample code for basic serialization/deserialization. + /// A simple sample code for basic serialization/deserialization. /// [TestFixture] public class BasicUsageSample @@ -44,7 +44,7 @@ public void SerializeThenDeserialize() { Id = 123, Title = "My photo", - Date = DateTime.Now, + Date = DateTime.UtcNow, Image = new byte[] { 1, 2, 3, 4 }, Comment = "This is test object to be serialize/deserialize using MsgPack." }; @@ -69,14 +69,19 @@ public void SerializeThenDeserialize() Debug.WriteLine( "Same Id? {0}", targetObject.Id == deserializedObject.Id ); Debug.WriteLine( "Same Title? {0}", targetObject.Title == deserializedObject.Title ); // Note that MsgPack defacto-standard is Unix epoc in milliseconds precision, so micro- and nano- seconds will be lost. See sample 04 for workaround. - Debug.WriteLine( "Same Date? {0}", targetObject.Date.ToString( "YYYY-MM-DD HH:mm:ss.fff" ) == deserializedObject.Date.ToString( "YYYY-MM-DD HH:mm:ss.fff" ) ); + Debug.WriteLine( "Same Date? {0}", targetObject.Date.ToString( "yyyy-MM-dd HH:mm:ss.fff" ) == deserializedObject.Date.ToString( "yyyy-MM-dd HH:mm:ss.fff" ) ); // Image and Comment tests are ommitted here. // Collection elements are deserialzed. Debug.WriteLine( "Items count: {0}", deserializedObject.Tags.Count ); } } - // Note: If you want to interop with other platform using SerializationMethod.Array (default), you should use [MessagePackMember]. See Sample06 for details. + /// + /// Simple class that will be used for serialization/deserialization. + /// + /// + /// If you want to interop with other platform using SerializationMethod.Array (default), you should use [MessagePackMember]. See Sample06 for details. + /// public class PhotoEntry { public long Id { get; set; } diff --git a/samples/Samples/Sample02_HandlingDynamicObject.cs b/samples/Samples/Sample02_HandlingDynamicObject.cs index 59548daf6..7dc29c3d8 100644 --- a/samples/Samples/Sample02_HandlingDynamicObject.cs +++ b/samples/Samples/Sample02_HandlingDynamicObject.cs @@ -29,7 +29,7 @@ namespace Samples { /// - /// A sample code for explore MessagePackObject. + /// A sample code for explore MessagePackObject. /// [TestFixture] public class HandlingDynamicObjectSample @@ -68,9 +68,12 @@ public void SerializeThenDeserialize() // 3. Unpack MessagePackObject to get raw representation. var rawObject = Unpacking.UnpackObject( stream ); - // You can read MPO tree via Unpacker + // 3-b. You can read MPO tree via Unpacker // var unpacker = Unpacker.Create( stream ); + // 3-c. Or, you can get it from serializer directly. + // var rawObject = MessagePackSerializer.UnpackMessagePackObject( stream ); + // Check its type Debug.WriteLine( "Is array? {0}", rawObject.IsArray ); // IsList is alias Debug.WriteLine( "Is map? {0}", rawObject.IsMap ); // IsDictionary is alias @@ -87,6 +90,23 @@ public void SerializeThenDeserialize() Debug.WriteLine( "Date : {0}({1})", asDictionary[ "Date" ], asDictionary[ "Date" ].UnderlyingType ); // byte[] is byte[], as you know. Debug.WriteLine( "Image : {0}({1})", asDictionary[ "Image" ], asDictionary[ "Image" ].UnderlyingType ); + + // 4. Now MessagePackSerializer handles MessagePackObject directly. + var mpo = serializer.ToMessagePackObject( targetObject ); + var asDictionary2 = mpo.AsDictionary(); + Debug.WriteLine( "---- ToMessagePackObject ----" ); + Debug.WriteLine( "Id : {0}({1})", asDictionary2[ "Id" ], asDictionary2[ "Id" ].UnderlyingType ); + Debug.WriteLine( "Title : {0}({1})", asDictionary2[ "Title" ], asDictionary2[ "Title" ].UnderlyingType ); + Debug.WriteLine( "Date : {0}({1})", asDictionary2[ "Date" ], asDictionary2[ "Date" ].UnderlyingType ); + Debug.WriteLine( "Image : {0}({1})", asDictionary2[ "Image" ], asDictionary2[ "Image" ].UnderlyingType ); + + // 5. Use MessagePackSerializer to deserialize target object from MessagePackObject + var targetObject2 = serializer.FromMessagePackObject( mpo ); + Debug.WriteLine( "---- FromMessagePackObject ----" ); + Debug.WriteLine( "Id : {0}", targetObject2.Id ); + Debug.WriteLine( "Title : {0}", targetObject2.Title ); + Debug.WriteLine( "Date : {0}", targetObject2.Date ); + Debug.WriteLine( "Image : {0}", Convert.ToBase64String( targetObject2.Image ) ); } } } diff --git a/samples/Samples/Sample03_SerializationContextAndOptions.cs b/samples/Samples/Sample03_SerializationContextAndOptions.cs index 6e374fbc5..863b054c4 100644 --- a/samples/Samples/Sample03_SerializationContextAndOptions.cs +++ b/samples/Samples/Sample03_SerializationContextAndOptions.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -29,7 +29,7 @@ namespace Samples { /// - /// A sample code to describe SerializationContext usage. + /// A sample code to describe SerializationContext usage. /// [TestFixture] public class SerializationContextAndOptionsSample @@ -44,29 +44,78 @@ public void CustomizeSerializeBehavior() // 2. Set options. - // 2-1. SerializationMethod: it changes comple type serialization method as array or map. - // Array(default): Space and time efficient, but depends on member declaration order so less version torrelant. - // Map : Less effitient, but more version torrelant (and easy to traverse as MesasgePackObject). + // 2-1. If you prefer classic (before 0.6) behavor, use utility method as following + // var context = SerializationContext.CreateClassicContext(); + + // Or, you can configure Default context classic as following + // SerializationContext.ConfigureClassic(); + + // 2-2. SerializationMethod: it changes comple type serialization method as array or map. + // Array(default): Space and time efficient, but depends on member declaration order so less version torrelant. + // Map : Less effitient, but more version torrelant (and easy to traverse as MesasgePackObject). context.SerializationMethod = SerializationMethod.Map; - // 2-2. EnumSerializationMethod: it changes enum serialization as their name or underlying value. - // ByName(default): More version torrelant and interoperable, and backward compatible prior to 0.5 of MsgPack for CLI. - // ByUnderlyingValue: More efficient, but you should manage their underlying value and specify precise data contract between counterpart systems. - context.EnumSerializationMethod = EnumSerializationMethod.ByUnderlyingValue; + // 2-2-1. You can customize map key handling when you use SerializationMethod.Map to improve interoperability. + // You can use preconfigured transformation in DictionaryKeyTransformers class. + context.DictionarySerializationOptions.KeyTransformer = DictionaryKeyTransformers.LowerCamel; + // 2-2-2. You can omit entry when map value is null. + context.DictionarySerializationOptions.OmitNullEntry = true; + + // 2-3. EnumSerializationMethod: it changes enum serialization as their name or underlying value. + // ByName(default): More version torrelant and interoperable, and backward compatible prior to 0.5 of MsgPack for CLI. + // ByUnderlyingValue: More efficient, but you should manage their underlying value and specify precise data contract between counterpart systems. + context.EnumSerializationOptions.SerializationMethod = EnumSerializationMethod.ByName; + + // 2-3-1. You can customize enum naming casing for EnumSerializationMethod.ByName. + // You can use preconfigured transformation in EnumNameTransformers class. + context.EnumSerializationOptions.NameTransformer = EnumNameTransformers.UpperSnake; - // 2-3. If CompatibilityOptions.OneBoundDataMemberOrder is set, the origin DataMemberAttribute.Order becomes 1. - // It is compatibility options 1 base library like Proto-buf.NET. + // 2-4. There are many compatibility switches: + + // 2-4-1. If CompatibilityOptions.OneBoundDataMemberOrder is set, the origin DataMemberAttribute.Order becomes 1. + // It is compatibility options 1 base library like Proto-buf.NET. context.CompatibilityOptions.OneBoundDataMemberOrder = true; - // 2-4. The CompatibilityOptions.PackerCompatibilityOptions control packer compatibility level. - // If you want to communicate with the library which only supports legacy message pack format spec, use PackerCompatibilityOptions.Classic flag set (default). - // If you want to utilize full feature including tiny string type, binary type, extended type, specify PackerCompatibilityOptions.None explicitly. + // 2-4-2. The CompatibilityOptions.PackerCompatibilityOptions control packer compatibility level. + // If you want to communicate with the library which only supports legacy message pack format spec, use PackerCompatibilityOptions.Classic flag set (default). + // If you want to utilize full feature including tiny string type, binary type, extended type, specify PackerCompatibilityOptions.None explicitly. context.CompatibilityOptions.PackerCompatibilityOptions = PackerCompatibilityOptions.None; + // 2-4-3. As of 0.7, MsgPack for CLI accepts IEnumerable type which does not have Add method as non-collection object. + // You can disable this new behavior with setting AllowNonCollectionEnumerableTypes to false. + context.CompatibilityOptions.AllowNonCollectionEnumerableTypes = false; + + // 2-4-4. As of 0.7, MsgPack for CLI respects IPackable/IUnpackable for collection types. + // You can disable this new behavior with setting IgnorePackabilityForCollection to true. + context.CompatibilityOptions.IgnorePackabilityForCollection = true; + + // 2-4-5. As of 0.9, MsgPack for CLI allows types which cannot be deserialized. + // It generates asymmetric serializer which can only serialize object. + // You can disable this new behavior with setting AllowAsymmetricSerializer to false. + context.CompatibilityOptions.AllowAsymmetricSerializer = false; + // Note: You can check capability of the generated serializer with MessagePackSerializer.Capabilities property. + // 2-5. You can tweak default concrete collection types for collection interfaces including IEnumerable, IList, etc. context.DefaultCollectionTypes.Unregister( typeof( IList<> ) ); context.DefaultCollectionTypes.Register( typeof( IList<> ), typeof( Collection<> ) ); + // 2-6. You can change default DateTime serialization method. + // Native: Use DateTime.ToBinary() based, it is precise but not interoperable + // UnixEpoc: Use milliseconds Unix epoc from 1970-01-01 for interoperability. + context.DefaultDateTimeConversionMethod = DateTimeConversionMethod.Native; + + // 2-7. You can tweak behaviors in code generation for serializer. These are advanced option. + + // 2-7-1. You can suppress asynchronous method generation. This is useful to generate serializer code for .NET 3.5/Unity. + context.SerializerOptions.WithAsync = false; + + // 2-7-2. You can tweak runtime serializer code(IL) generation behavior. This is very advanced feature. + context.SerializerOptions.GeneratorOption = SerializationMethodGeneratorOption.CanCollect; + + // 2-8. You can use SerializationContext as repository of msgpack ext type mappings. + // You must implement custom serializer to handle ext types correctly. See sample 04 to implement custom serializers. + context.ExtTypeCodeMapping.Add( "EventTime", 1 ); + // 3. Get a serializer instance with customized settings. var serializer = MessagePackSerializer.Get( context ); diff --git a/samples/Samples/Sample04_CustomSerializer.cs b/samples/Samples/Sample04_CustomSerializer.cs index c23e29a68..f7d9d4649 100644 --- a/samples/Samples/Sample04_CustomSerializer.cs +++ b/samples/Samples/Sample04_CustomSerializer.cs @@ -29,7 +29,7 @@ namespace Samples { /// - /// A sample code to describe SerializationContext usage. + /// A sample code to describe SerializationContext usage. /// [TestFixture] public class CustomSerializerSample @@ -50,7 +50,7 @@ public void RegisterAndUseCustomSerializer() // 3. Get a serializer instance with customized settings. var serializer = MessagePackSerializer.Get( context ); - // Test it. + // 4. Test Serialization and Deserialization. var dateTime = DateTime.Now; serializer.Pack( stream, dateTime ); stream.Position = 0; @@ -61,7 +61,7 @@ public void RegisterAndUseCustomSerializer() } /// - /// A custom serializer sample: Serialize as UTC. + /// A custom serializer sample: Serialize as UTC. /// public class NetUtcDateTimeSerializer : MessagePackSerializer { diff --git a/samples/Samples/Sample05_PackableAndUnpackable.cs b/samples/Samples/Sample05_PackableAndUnpackable.cs index 991c95d99..ec927d949 100644 --- a/samples/Samples/Sample05_PackableAndUnpackable.cs +++ b/samples/Samples/Sample05_PackableAndUnpackable.cs @@ -20,6 +20,7 @@ using System; using System.IO; +using System.Runtime.Serialization; using MsgPack; using MsgPack.Serialization; @@ -28,7 +29,7 @@ namespace Samples { /// - /// A sample code to describe SerializationContext usage. + /// A sample code to describe SerializationContext usage. /// [TestFixture] public class PackageAndUnpackableSample @@ -50,11 +51,11 @@ public void RegisterAndUseCustomSerializer() } /// - /// A custom serializer sample: Serialize as UTC. + /// A custom serializer sample: Serialize as UTC. /// public class PackableUnpackableObject : IPackable, IUnpackable { - // Imagine whien you cannot use auto-generated serializer so you have to implement custom serializer for own type easily. + // Imagine when you cannot use auto-generated serializer so you have to implement custom serializer for own type easily. public long Id { get; set; } public string Name { get; set; } @@ -85,26 +86,26 @@ public void UnpackFromMessage( Unpacker unpacker ) // It should be packed as array because we use hand-made packing implementation above. if ( !unpacker.IsArrayHeader ) { - throw SerializationExceptions.NewIsNotArrayHeader(); + throw new SerializationException( "Is not in array header." ); } // Check items count. if ( UnpackHelpers.GetItemsCount( unpacker ) != 2 ) { - throw SerializationExceptions.NewUnexpectedArrayLength( 2, UnpackHelpers.GetItemsCount( unpacker ) ); + throw new SerializationException( $"Array length should be 2, but {UnpackHelpers.GetItemsCount( unpacker )}" ); } // Unpack fields here: if ( !unpacker.ReadInt64( out id ) ) { - throw SerializationExceptions.NewMissingProperty( "Id" ); + throw new SerializationException( "Property Id is not found." ); } this.Id = id; if ( !unpacker.ReadString( out name ) ) { - throw SerializationExceptions.NewMissingProperty( "Name" ); + throw new SerializationException( "Property Name is not found." ); } this.Name = name; diff --git a/samples/Samples/Sample06_CustomAttributes.cs b/samples/Samples/Sample06_CustomAttributes.cs index 4ee829256..59781a394 100644 --- a/samples/Samples/Sample06_CustomAttributes.cs +++ b/samples/Samples/Sample06_CustomAttributes.cs @@ -26,8 +26,11 @@ namespace Samples { - // You can tweak serialization behavior via custom attributes. - public class MessagePackMemberSample + /// + /// Sample code to describe MessagePackMember usage. + /// + /// You can tweak serialization behavior via custom attributes. + public class MessagePackMemberSample { [MessagePackMember( 0, // Specify 0 based index for serialized array. You should specify this value to ensure interoperability with other platform bindings. @@ -56,8 +59,14 @@ public class DataContractSample public string Title { get; set; } } - // MessagePackMember - // MessagePackEnumMember + // ... You can "opt-out" with MessagePackIgnore + public class OptOutSample + { + [MessagePackIgnore] + public string ShouldNotEmit { get; set; } + + public int ShouldEmit { get; set; } + } } namespace System.Runtime.Serialization @@ -68,4 +77,6 @@ public sealed class DataMemberAttribute : Attribute public string Name { get; set; } public int Order { get; set; } } + + // This is also about MessagePackIgnoreAttribute, MessagePackMemberAttribute, and MessagePackDeserializationConstructorAttribute. } diff --git a/samples/Samples/Sample07_ConstructorBasedDeserialization.cs b/samples/Samples/Sample07_ConstructorBasedDeserialization.cs new file mode 100644 index 000000000..c66f863a5 --- /dev/null +++ b/samples/Samples/Sample07_ConstructorBasedDeserialization.cs @@ -0,0 +1,103 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; + +using MsgPack.Serialization; +using NUnit.Framework; // For running checking + +namespace Samples +{ + /// + /// A sample to describe constructor related behavior. + /// + [TestFixture] + public class ConstructorBasedDeserializationSample + { + /// + /// Demonstrates constructor based deserialization. + /// + [Test] + public void DoConstructorBasedDeserialization() + { + // As of 0.8, constructor based deserialization is relaxed. + // 1. If the type have a constructor with MessagePackDeserializationConstructorAttribute, then it will be used for deserialization. + // 2. Else, if the type have a default public constructor then it will be used for deserialization. + // 3. Otherwise, most parameterful constructor will be used. + + var serializerForSimpleRecord = MessagePackSerializer.Get(); + using ( var buffer = new MemoryStream() ) + { + serializerForSimpleRecord.Pack( buffer, new MySimpleRecordClass( "John Doe" ) ); + buffer.Position = 0; + Assert.That( serializerForSimpleRecord.Unpack( buffer ).Name, Is.EqualTo( "John Doe" ) ); + } + + var serializerForComplexRecord = MessagePackSerializer.Get(); + using ( var buffer = new MemoryStream() ) + { + serializerForComplexRecord.Pack( buffer, new MyComplexRecordClass( "John Doe" ) ); + buffer.Position = 0; + Assert.That( serializerForComplexRecord.Unpack( buffer ).Name, Is.EqualTo( "John Doe" ) ); + } + } + } + + /// + /// "Record" class which has getters and parameterful constructor. + /// + public class MySimpleRecordClass + { + public string Name { get; private set; } + + public MySimpleRecordClass( string name ) + { + this.Name = name; + } + } + + /// + /// A example class which has getters and parameterless and parameterful constructor, + /// and the parameterful constructor is qualified with MessagePackDeserializationConstructor. + /// + public class MyComplexRecordClass + { + public string Name { get; private set; } + + public bool ExtraProperty { get; private set; } + + public MyComplexRecordClass() + { + this.Name = ""; + } + + [MessagePackDeserializationConstructor] + public MyComplexRecordClass( string name ) + { + this.Name = name; + } + + public void SetExtraPropertyFromDomainLogic( bool value ) + { + this.ExtraProperty = value; + } + } +} \ No newline at end of file diff --git a/samples/Samples/Sample08_Polymorphism.cs b/samples/Samples/Sample08_Polymorphism.cs new file mode 100644 index 000000000..587216001 --- /dev/null +++ b/samples/Samples/Sample08_Polymorphism.cs @@ -0,0 +1,199 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using System.IO; + +using MsgPack.Serialization; +using NUnit.Framework; // For running checking + +namespace Samples +{ + /// + /// A sample to describe polymorphism. + /// + [TestFixture] + public class PolymorphismSample + { + /// + /// Demonstrates basic polymorphism. + /// + [Test] + public void Polymorphism() + { + // As of 0.7, polymorphism is implemented. + + // Setup the context to use map for pretty printing. + var context = new SerializationContext { SerializationMethod = SerializationMethod.Map }; + + var serializer = context.GetSerializer(); + + var rootObject = + new PolymorphicHolder + { + WithRuntimeType = new FileObject { Path = "/path/to/file" }, + WithKnownType = new DirectoryObject { Path = "/path/to/dir/" } + }; + + using ( var buffer = new MemoryStream() ) + { + serializer.Pack( + buffer, rootObject + ); + + buffer.Position = 0; + + Print( buffer ); + + buffer.Position = 0; + var deserialized = serializer.Unpack( buffer ); + + Assert.That( deserialized.WithRuntimeType, Is.TypeOf() ); + Assert.That( deserialized.WithRuntimeType.Path, Is.EqualTo( "/path/to/file" ) ); + Assert.That( deserialized.WithKnownType, Is.TypeOf() ); + Assert.That( deserialized.WithKnownType.Path, Is.EqualTo( "/path/to/dir/" ) ); + } + } + + /// + /// Demonstrates polymorphism without enclosing type and its attributes. + /// + [Test] + public void DirectPolymorphism() + { + // As of 0.9, you can serialize polymorphic directly. + + // Setup the context to use map for pretty printing. + var context = new SerializationContext { SerializationMethod = SerializationMethod.Map }; + + // With type information embedding (runtime type) + // The argument is "decoded" info from MessagePackRuntimeTypeAttribute or its family. + var serializerWithTypeInfoEmbedding = + context.GetSerializer( PolymorphismSchema.ForPolymorphicObject( typeof( IFileSystemObject ), SampleTypeVerifier.Verify ) ); + + using ( var buffer = new MemoryStream() ) + { + serializerWithTypeInfoEmbedding.Pack( buffer, new FileObject { Path = "/path/to/file" } ); + buffer.Position = 0; + + Print( buffer ); + + buffer.Position = 0; + var deserialized = serializerWithTypeInfoEmbedding.Unpack( buffer ); + Assert.That( deserialized, Is.TypeOf() ); + Assert.That( deserialized.Path, Is.EqualTo( "/path/to/file" ) ); + } + + // With type code mapping (known type) + // The argument is "decoded" info from MessagePackKnownTypeAttribute or its family. + var serializerWithTypeCodeMapping = + context.GetSerializer( + PolymorphismSchema.ForPolymorphicObject( + typeof( IFileSystemObject ), + new Dictionary + { + { "f", typeof( FileObject ) }, + { "d", typeof( DirectoryObject ) } + } + ) + ); + + using ( var buffer = new MemoryStream() ) + { + serializerWithTypeCodeMapping.Pack( buffer, new DirectoryObject { Path = "/path/to/dir/" } ); + buffer.Position = 0; + + Print( buffer ); + + buffer.Position = 0; + var deserialized = serializerWithTypeCodeMapping.Unpack( buffer ); + Assert.That( deserialized, Is.TypeOf() ); + Assert.That( deserialized.Path, Is.EqualTo( "/path/to/dir/" ) ); + } + } + + private static void Print( Stream serialized ) + { + // Print serialized binary as JSON. + // You can see that the object serialized as [, {}] structure. + Console.WriteLine( MessagePackSerializer.UnpackMessagePackObject( serialized ) ); + } + } + + public class PolymorphicHolder + { + [MessagePackKnownType( "f", typeof( FileObject ) )] + [MessagePackKnownType( "d", typeof( DirectoryObject ) )] + public IFileSystemObject WithKnownType { get; set; } + + [MessagePackRuntimeType(VerifierType = typeof(SampleTypeVerifier), VerifierMethodName = "Verify")] + public IFileSystemObject WithRuntimeType { get; set; } + } + + /// + /// Sample base type. + /// + public interface IFileSystemObject + { + string Path { get; set; } + } + + /// + /// Sample derived type 1. + /// + public class FileObject : IFileSystemObject + { + public string Path { get; set; } + } + + /// + /// Sample derived type 2. + /// + public class DirectoryObject : IFileSystemObject + { + public string Path { get; set; } + } + + /// + /// Sample type verifier. + /// + public static class SampleTypeVerifier + { + /// + /// Sample type verifier. + /// + /// The signature of this method is important. + /// The context which has information of deserializing type. + /// True for accepting; otherwise, false. + public static bool Verify( PolymorphicTypeVerificationContext context ) + { + // You should put type verification logic to prevent unexpected code execution via specified type. + // 1. Check context.LoadingAssemblyName here to verify the assembly is known for you. + // 2. Check context.LoadingTypeFullName here to verify the type name is known for you. + + // Note: You should not get Assembly, Type, or related reflection related objects here + // to prevent potentially malicous code execution in its type initializer etc. + + // True for accepting; otherwise, false. + return true; + } + } +} diff --git a/samples/Samples/Sample09_Async.cs b/samples/Samples/Sample09_Async.cs new file mode 100644 index 000000000..9977dba55 --- /dev/null +++ b/samples/Samples/Sample09_Async.cs @@ -0,0 +1,69 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Threading.Tasks; + +using MsgPack.Serialization; +using NUnit.Framework; // For running checking + +namespace Samples +{ + /// + /// A sample code to describe async methods. + /// + [TestFixture] + public class AsyncSample + { + /// + /// Has object serialized and deserialized asynchronously. + /// + [Test] + public async Task RunAsync() + { + // Now supports async. + var context = new SerializationContext(); + + // Asynchronous is allowed by default. + Assert.True( context.SerializerOptions.WithAsync ); + + var serializer = context.GetSerializer(); + var targetObject = + new PhotoEntry // See Sample01_BasicUsage.cs + { + Id = 123, + Title = "My photo", + Date = DateTime.Now, + Image = new byte[] { 1, 2, 3, 4 }, + Comment = "This is test object to be serialize/deserialize using MsgPack." + }; + + using ( var stream = new MemoryStream() ) + { + // Note: PackAsync/UnpackAsync uses internal BufferedStream to avopid chatty asynchronous call for underlying I/O system. + // If you change this behavior, use PackToAsync/UnpackFromAsync with Packer/Unpacker factories to specify options. + await serializer.PackAsync( stream, targetObject ); + stream.Position = 0; + var roundTripped = await serializer.UnpackAsync( stream ); + } + } + } +} \ No newline at end of file diff --git a/samples/Samples/Sample10_ByteArrayBased.cs b/samples/Samples/Sample10_ByteArrayBased.cs new file mode 100644 index 000000000..d15406d1a --- /dev/null +++ b/samples/Samples/Sample10_ByteArrayBased.cs @@ -0,0 +1,76 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using MsgPack; +using MsgPack.Serialization; +using NUnit.Framework; // For running checking + +namespace Samples +{ + /// + /// A sample code to describe byte array based behavior. + /// + [TestFixture] + public class Sample10_ByteArrayBased + { + /// + /// Uses byte array for serialization and deserialization. + /// + [Test] + public void SimpleBufferCase() + { + // Assumes that we know maximum serialized data size, so just use it! + var buffer = new byte[ 1024 * 64 ]; + + var context = new SerializationContext(); + var serializer = context.GetSerializer(); + + var obj = + new PhotoEntry + { + Id = 123, + Title = "My photo", + Date = DateTime.Now, + Image = new byte[] { 1, 2, 3, 4 }, + Comment = "This is test object to be serialize/deserialize using MsgPack." + }; + // Note that the packer automatically increse buffer. + using ( var bytePacker = Packer.Create( buffer, true, PackerCompatibilityOptions.None ) ) + { + serializer.PackTo( bytePacker, obj ); + // Note: You can get actual bytes with GetResultBytes(), but it causes array copy. + // You can avoid copying using original buffer (when you prohibits buffer allocation on Packer.Create) or GetFinalBuffers() instead. + Console.WriteLine( "Serialized: {0}", BitConverter.ToString( buffer, 0, ( int )bytePacker.BytesUsed ) ); + + using ( var byteUnpacker = Unpacker.Create( buffer ) ) + { + var deserialized = serializer.UnpackFrom( byteUnpacker ); + } + } + } + } + + public class MyArrayBufferManager + { + public IList> Buffers { get; } + } +} diff --git a/samples/Samples/Samples.csproj b/samples/Samples/Samples.csproj index 41b12cbe5..6e669d52e 100644 --- a/samples/Samples/Samples.csproj +++ b/samples/Samples/Samples.csproj @@ -33,9 +33,8 @@ 4 - - ..\..\packages\NUnit.3.2.1\lib\net45\nunit.framework.dll - True + + ..\..\packages\NUnit.3.8.1\lib\net45\nunit.framework.dll @@ -53,6 +52,10 @@ + + + + diff --git a/samples/Samples/packages.config b/samples/Samples/packages.config index 80c54474c..0ee860b3f 100644 --- a/samples/Samples/packages.config +++ b/samples/Samples/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/CommonAssemblyInfo.cs b/src/CommonAssemblyInfo.cs index f226a7b36..51ac2d17d 100644 --- a/src/CommonAssemblyInfo.cs +++ b/src/CommonAssemblyInfo.cs @@ -25,7 +25,7 @@ using System.Resources; using System.Runtime.InteropServices; -[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010-2016" )] +[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010-2017" )] [assembly: AssemblyProduct( "MessagePack" )] [assembly: CLSCompliant( true )] [assembly: ComVisible( false )] @@ -35,7 +35,7 @@ // Major : Represents Major update like re-architecting, remove obsoleted APIs etc. // Minor : Represents Minor update like adding new feature, obsoleting APIs, fix specification issues, etc. // Build/Revision : Always 0 since CLI implementations does not care these number, so these changes cause some binding failures. -[assembly: AssemblyVersion( "0.7.0.0" )] +[assembly: AssemblyVersion( "1.0.0.0" )] // This version represents libarary 'version' for human beings. // Major : Same as AssemblyVersion. @@ -43,5 +43,5 @@ // Build : Bug fixes and improvements, which does not break API contract, but may break some code depends on internal implementation behaviors. // For example, some programs use reflection to retrieve private fields, analyse human readable exception messages or stack trace, or so. // Revision : Reserced. It might be used to indicate target platform or patch. -[assembly: AssemblyInformationalVersion( "0.7.0-alpha2" )] +[assembly: AssemblyInformationalVersion( "1.0.0-dev" )] diff --git a/src/MsgPack.CoreClr/Properties/AssemblyInfo.cs b/src/MsgPack.CoreClr/Properties/AssemblyInfo.cs deleted file mode 100644 index 9277f05d3..000000000 --- a/src/MsgPack.CoreClr/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Security; - -#if NETSTANDARD1_1 -[assembly: AssemblyTitle( "MessagePack for .NET Platform Standard 1.1" )] -#elif NETSTANDARD1_3 -[assembly: AssemblyTitle( "MessagePack for .NET Platform Standard 1.3" )] -#else -[assembly: AssemblyTitle( "MessagePack for .NET Platform Standard" )] -#endif -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library for .NET Platform Standard 1.1 including .NET 4.5.x, Windows App, and Mono without AOT" )] - -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] - -#if DEBUG || PERFORMANCE_TEST -[assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Net45, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions.Net45, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.WinRT, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions.WinRT, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.WinRT.WindowsPhone.8.1, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - - diff --git a/src/MsgPack.CoreClr/project.json b/src/MsgPack.CoreClr/project.json deleted file mode 100644 index 24bc2b754..000000000 --- a/src/MsgPack.CoreClr/project.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "buildOptions": { - "outputName": "MsgPack", - "keyFile": "../MsgPack.snk", - "configurations": { - "Debug": { - "buildOptions": { - "define": [ "DEBUG" ], - "optimize": false - } - }, - "Release": { - "buildOptions": { - "optimize": true - } - } - }, - "define": [ "TRACE", "FEATURE_TAP" ], - "xmlDoc": true, - "compile": { - "include": [ - "../MsgPack/**/*.cs", - "../CommonAssemblyInfo.cs", - "../netstandard/BufferedStream.cs", - "../netstandard/NetStandardCompatibility.cs", - "./**/*.cs" - ], - "exclude": [ - "../MsgPack/Properties/AssemblyInfo.cs", - "../MsgPack/Serialization/AbstractSerializers/**/*.*", - "../MsgPack/Serialization/CodeDomSerializers/**/*.*", - "../MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs", - "../MsgPack/Serialization/EmittingSerializers/**/*.*", - "../MsgPack/Serialization/Metadata/_CultureInfo.cs", - "../MsgPack/Serialization/Metadata/_DateTimeMessagePackSerializerHelpers.cs", - "../MsgPack/Serialization/Metadata/_Decimal.cs", - "../MsgPack/Serialization/Metadata/_DictionaryEntry.cs", - "../MsgPack/Serialization/Metadata/_DynamicUnpackingContext.cs", - "../MsgPack/Serialization/Metadata/_EnumMessagePackSerializerHelpers.cs", - "../MsgPack/Serialization/Metadata/_FieldInfo.cs", - "../MsgPack/Serialization/Metadata/_IDictionaryEnumerator.cs", - "../MsgPack/Serialization/Metadata/_IDisposable.cs", - "../MsgPack/Serialization/Metadata/_IEnumreator.cs", - "../MsgPack/Serialization/Metadata/_MessagePackObject.cs", - "../MsgPack/Serialization/Metadata/_MethodBase.cs", - "../MsgPack/Serialization/Metadata/_Object.cs", - "../MsgPack/Serialization/Metadata/_Packer.cs", - "../MsgPack/Serialization/Metadata/_String.cs", - "../MsgPack/Serialization/Metadata/_Unpacker.cs", - "../MsgPack/Serialization/Metadata/_UnpackHelpers.cs", - "../MsgPack/Serialization/Metadata/_UnpackHelpers.direct.cs", - "../MsgPack/Serialization/Reflection/TracingILGenerator*.cs", - "../MsgPack/Serialization/ISerializerGeneratorConfiguration.cs", - "../MsgPack/Serialization/SerializerAssemblyGenerationConfiguration.cs", - "../MsgPack/Serialization/SerializerCodeGenerationConfiguration.cs", - "../MsgPack/Serialization/SerializerGenerator.cs", - "../MsgPack/Serialization/SerializerCodeGenerationContext.cs", - "../MsgPack/Serialization/SerializerCodeGenerationResult.cs" - ] - } - }, - "dependencies": { - "System.Collections": "4.0.11-rc2-24027", - "System.Collections.Concurrent": "4.0.12-rc2-24027", - "System.Data.Common": "4.0.1-rc2-24027", - "System.Diagnostics.Contracts": "4.0.1-rc2-24027", - "System.Diagnostics.Debug": "4.0.11-rc2-24027 ", - "System.Diagnostics.Tools": "4.0.1-rc2-24027 ", - "System.Globalization": "4.0.11-rc2-24027", - "System.IO": "4.1.0-rc2-24027", - "System.Linq": "4.1.0-rc2-24027", - "System.Linq.Expressions": "4.0.11-rc2-24027", - "System.ObjectModel": "4.0.12-rc2-24027", - "System.Reflection": "4.1.0-rc2-24027", - "System.Reflection.Extensions": "4.0.1-rc2-24027", - "System.Reflection.Primitives": "4.0.1-rc2-24027", - "System.Resources.ResourceManager": "4.0.1-rc2-24027", - "System.Runtime": "4.1.0-rc2-24027", - "System.Runtime.Extensions": "4.1.0-rc2-24027", - "System.Runtime.InteropServices": "4.1.0-rc2-24027", - "System.Runtime.Numerics": "4.0.1-rc2-24027", - "System.Runtime.Serialization.Primitives": "4.1.1-rc2-24027", - "System.Text.Encoding": "4.0.11-rc2-24027", - "System.Text.Encoding.Extensions": "4.0.11-rc2-24027", - "System.Text.RegularExpressions": "4.0.12-rc2-24027", - "System.Threading": "4.0.11-rc2-24027" - }, - "frameworks": { - "netstandard1.1": { - }, - "netstandard1.3": { - "dependencies": { - "System.Collections.NonGeneric": "4.0.1-rc2-24027", - "System.Collections.Specialized": "4.0.1-rc2-24027", - "System.Numerics.Vectors": "4.1.1-rc2-24027" - } - } - } -} diff --git a/src/MsgPack.Net35/MsgPack.Net35.csproj b/src/MsgPack.Net35/MsgPack.Net35.csproj deleted file mode 100644 index 2c2224986..000000000 --- a/src/MsgPack.Net35/MsgPack.Net35.csproj +++ /dev/null @@ -1,1015 +0,0 @@ - - - - - Debug - AnyCPU - {C5490CDC-3B79-42DC-ACFB-75A62E55862C} - Library - Properties - MsgPack - MsgPack - v3.5 - 512 - Client - - - true - full - false - bin\Debug\ - TRACE;DEBUG;NETFX_35 - prompt - 4 - true - bin\Debug\MsgPack.xml - - - pdbonly - true - ..\..\bin\net35-client\ - TRACE;NETFX_35 - prompt - 4 - true - ..\..\bin\net35-client\MsgPack.XML - - - true - - - ..\MsgPack.snk - - - bin\CodeAnalysis\ - TRACE;NETFX_35;CODE_ANALYSIS - true - - - true - pdbonly - AnyCPU - prompt - AllRules.ruleset - true - - - - - - - - Properties\CommonAssemblyInfo.cs - - - AsyncReadResult.cs - - - AsyncReadResult`1.cs - - - BigEndianBinary.cs - - - Binary.cs - - - BufferManager.cs - - - CollectionDebuggerProxy`1.cs - - - CollectionOperation.cs - - - DictionaryDebuggerProxy`2.cs - - - Float32Bits.cs - - - Float64Bits.cs - - - GlobalSuppressions.cs - - - IAsyncPackable.cs - - - IAsyncUnpackable.cs - - - InvalidMessagePackStreamException.cs - - - IPackable.cs - - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs - - - IUnpackable.cs - - - KnownExtTypeCode.cs - - - KnownExtTypeName.cs - - - MessageNotSupportedException.cs - - - MessagePackCode.cs - - - MessagePackConvert.cs - - - MessagePackExtendedTypeObject.cs - - - MessagePackObject.cs - - - MessagePackObject.Utilities.cs - - - MessagePackObjectDictionary.cs - - - MessagePackObjectDictionary.Enumerator.cs - - - MessagePackObjectDictionary.KeySet.cs - - - MessagePackObjectDictionary.KeySet.Enumerator.cs - - - MessagePackObjectDictionary.ValueCollection.cs - - - MessagePackObjectDictionary.ValueCollection.Enumerator.cs - - - MessagePackObjectEqualityComparer.cs - - - MessagePackString.cs - - - MessageTypeException.cs - - - Packer.cs - - - Packer.Nullable.cs - - - Packer.Packing.cs - - - PackerCompatibilityOptions.cs - - - PackerUnpackerExtensions.cs - - - PackerUnpackerStreamOptions.cs - - - PackingOptions.cs - - - PreserveAttribute.cs - - - ReflectionAbstractions.cs - - - Serialization\AbstractSerializers\ActionType.cs - - - Serialization\AbstractSerializers\CachedDelegateInfo.cs - - - Serialization\AbstractSerializers\ConstructorDefinition.cs - - - Serialization\AbstractSerializers\DynamicUnpackingContext.cs - - - Serialization\AbstractSerializers\EnumSerializerMethod.cs - - - Serialization\AbstractSerializers\FieldDefinition.cs - - - Serialization\AbstractSerializers\FieldName.cs - - - Serialization\AbstractSerializers\ICodeConstruct.cs - - - Serialization\AbstractSerializers\ISerializerBuilder.cs - - - Serialization\AbstractSerializers\ISerializerCodeGenerationContext.cs - - - Serialization\AbstractSerializers\ISerializerCodeGenerator.cs - - - Serialization\AbstractSerializers\MethodDefinition.cs - - - Serialization\AbstractSerializers\MethodName.cs - - - Serialization\AbstractSerializers\MethodNamePrefix.cs - - - Serialization\AbstractSerializers\SerializerBuilderHelper.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Collection.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.CommonConstructs.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Enum.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Nullable.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Object.cs - - - Serialization\AbstractSerializers\SerializerFieldKey.cs - - - Serialization\AbstractSerializers\SerializerGenerationContext.cs - - - Serialization\AbstractSerializers\SerializerSpecification.cs - - - Serialization\AbstractSerializers\TypeDefinition.cs - - - Serialization\CodeDomSerializers\CodeDomConstruct.cs - - - Serialization\CodeDomSerializers\CodeDomContext.cs - - - Serialization\CodeDomSerializers\CodeDomSerializerBuilder.cs - - - Serialization\CodeDomSerializers\ExpressionCodeDomConstruct.cs - - - Serialization\CodeDomSerializers\ParameterCodeDomConstruct.cs - - - Serialization\CodeDomSerializers\StatementCodeDomConstruct.cs - - - Serialization\CodeDomSerializers\VariableCodeDomConstruct.cs - - - Serialization\CollectionDetailedKind.cs - - - Serialization\CollectionKind.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ICollectionInstanceFactory.cs - - - Serialization\CollectionSerializers\NonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs - - - Serialization\CollectionTraitOptions.cs - - - Serialization\CollectionTraits.cs - - - Serialization\DataMemberContract.cs - - - Serialization\DateTimeConversionMethod.cs - - - Serialization\DateTimeMemberConversionMethod.cs - - - Serialization\DateTimeMessagePackSerializerHelpers.cs - - - Serialization\DefaultConcreteTypeRepository.cs - - - Serialization\DefaultSerializerNameResolver.cs - - - Serialization\DefaultSerializers\AbstractCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractCollectionSerializerHelper.cs - - - Serialization\DefaultSerializers\AbstractDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\AbstractEnumerableMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractNonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericListMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\ArraySegmentMessageSerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.Primitives.cs - - - Serialization\DefaultSerializers\ArraySerializer`1.cs - - - Serialization\DefaultSerializers\DateTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializer.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DefaultSerializers.cs - - - Serialization\DefaultSerializers\FileTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\GenericSerializer.cs - - - Serialization\DefaultSerializers\InternalDateTimeExtensions.cs - - - Serialization\DefaultSerializers\MessagePackObjectExtensions.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MultidimensionalArraySerializer`1.cs - - - Serialization\DefaultSerializers\NativeDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NativeFileTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NullableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ArraySegment_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ByteArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_CharArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_DictionaryEntryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Stack_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_QueueMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_StackMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_DBNullMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Globalization_CultureInfoMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_ObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_StringMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Text_StringBuilderMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_UriMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocFileTimeMessagePackSerializer.cs - - - Serialization\EmitterFlavor.cs - - - Serialization\EmittingSerializers\AndConditionILConstruct.cs - - - Serialization\EmittingSerializers\AssemblyBuilderCodeGenerationContext.cs - - - Serialization\EmittingSerializers\AssemblyBuilderEmittingContext.cs - - - Serialization\EmittingSerializers\AssemblyBuilderSerializerBuilder.cs - - - Serialization\EmittingSerializers\BinaryOperatorILConstruct.cs - - - Serialization\EmittingSerializers\ConditionalILConstruct.cs - - - Serialization\EmittingSerializers\ContextfulILConstruct.cs - - - Serialization\EmittingSerializers\ILConstruct.cs - - - Serialization\EmittingSerializers\ILMethodConctext.cs - - - Serialization\EmittingSerializers\InvocationILConsruct.cs - - - Serialization\EmittingSerializers\LoadFieldILConstruct.cs - - - Serialization\EmittingSerializers\SequenceILConstruct.cs - - - Serialization\EmittingSerializers\SerializationMethodGeneratorManager.cs - - - Serialization\EmittingSerializers\SerializerEmitter.cs - - - Serialization\EmittingSerializers\SerializerEmitter.enum.cs - - - Serialization\EmittingSerializers\SerializerEmitter.object.cs - - - Serialization\EmittingSerializers\SinglelStepILConstruct.cs - - - Serialization\EmittingSerializers\StatementExpressionILConstruct.cs - - - Serialization\EmittingSerializers\StoreFieldILConstruct.cs - - - Serialization\EmittingSerializers\StoreVariableILConstruct.cs - - - Serialization\EmittingSerializers\UnaryOperatorILConstruct.cs - - - Serialization\EmittingSerializers\VariableILConstruct.cs - - - Serialization\EnumMemberSerializationMethod.cs - - - Serialization\EnumMessagePackSerializerHelpers.cs - - - Serialization\EnumMessagePackSerializerProvider.cs - - - Serialization\EnumMessagePackSerializer`1.cs - - - Serialization\EnumSerializationMethod.cs - - - Serialization\ExtTypeCodeMapping.cs - - - Serialization\FromExpression.cs - - - Serialization\FromExpression.ToMethod.cs - - - Serialization\ICustomizableEnumSerializer.cs - - - Serialization\IdentifierUtility.cs - - - Serialization\IMessagePackSerializer.cs - - - Serialization\IMessagePackSingleObjectSerializer.cs - - - Serialization\INilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\INilImplicationHandlerParameter.cs - - - Serialization\ISerializerGeneratorConfiguration.cs - - - Serialization\LazyDelegatingMessagePackSerializer`1.cs - - - Serialization\MessagePackDateTimeMemberAttribute.cs - - - Serialization\MessagePackDeserializationConstructorAttribute.cs - - - Serialization\MessagePackEnumAttribute.cs - - - Serialization\MessagePackEnumMemberAttribute.cs - - - Serialization\MessagePackIgnoreAttribute.cs - - - Serialization\MessagePackKnownTypeAttributes.cs - - - Serialization\MessagePackMemberAttribute.cs - - - Serialization\MessagePackRuntimeTypeAttributes.cs - - - Serialization\MessagePackSerializer.cs - - - Serialization\MessagePackSerializer.Factories.cs - - - Serialization\MessagePackSerializerExtensions.cs - - - Serialization\MessagePackSerializerProvider.cs - - - Serialization\MessagePackSerializer`1.cs - - - Serialization\Metadata\_CultureInfo.cs - - - Serialization\Metadata\_DateTimeMessagePackSerializerHelpers.cs - - - Serialization\Metadata\_Decimal.cs - - - Serialization\Metadata\_DictionaryEntry.cs - - - Serialization\Metadata\_DynamicUnpackingContext.cs - - - Serialization\Metadata\_EnumMessagePackSerializerHelpers.cs - - - Serialization\Metadata\_FieldInfo.cs - - - Serialization\Metadata\_IDictionaryEnumerator.cs - - - Serialization\Metadata\_IDisposable.cs - - - Serialization\Metadata\_IEnumreator.cs - - - Serialization\Metadata\_MessagePackObject.cs - - - Serialization\Metadata\_MessagePackSerializer.cs - - - Serialization\Metadata\_MethodBase.cs - - - Serialization\Metadata\_Object.cs - - - Serialization\Metadata\_Packer.cs - - - Serialization\Metadata\_SerializationContext.cs - - - Serialization\Metadata\_String.cs - - - Serialization\Metadata\_Unpacker.cs - - - Serialization\Metadata\_UnpackHelpers.cs - - - Serialization\Metadata\_UnpackHelpers.direct.cs - - - Serialization\NilImplication.cs - - - Serialization\NilImplicationHandler`4.cs - - - Serialization\PackHelpers.cs - - - Serialization\Polymorphic\IPolymorphicDeserializer.cs - - - Serialization\Polymorphic\IPolymorphicHelperAttributes.cs - - - Serialization\Polymorphic\KnownTypePolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs - - - Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\TypeInfoEncoder.cs - - - Serialization\Polymorphic\TypeInfoEncoding.cs - - - Serialization\PolymorphismSchema.Constructors.cs - - - Serialization\PolymorphismSchema.cs - - - Serialization\PolymorphismSchema.Internals.cs - - - Serialization\PolymorphismSchemaChildrenType.cs - - - Serialization\PolymorphismTarget.cs - - - Serialization\PolymorphismType.cs - - - Serialization\ReflectionExtensions.cs - - - Serialization\ReflectionHelpers.cs - - - Serialization\ReflectionSerializers\ReflectionCollectionMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionDictionaryMessagePackSerializer`3.cs - - - Serialization\ReflectionSerializers\ReflectionEnumerableMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionEnumMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNilImplicationHandler.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricCollectionMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericListMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionObjectMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerHelper.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - - - Serialization\Reflection\TracingILGenerator.conveniences.cs - - - Serialization\Reflection\TracingILGenerator.cs - - - Serialization\Reflection\TracingILGenerator.emits.cs - - - Serialization\ResolveSerializerEventArgs.cs - - - Serialization\SerializationCompatibilityOptions.cs - - - Serialization\SerializationContext.cs - - - Serialization\SerializationContext.ExtTypeCodes.cs - - - Serialization\SerializationExceptions.cs - - - Serialization\SerializationMethod.cs - - - Serialization\SerializationMethodGeneratorOption.cs - - - Serialization\SerializationTarget.cs - - - Serialization\SerializerAssemblyGenerationConfiguration.cs - - - Serialization\SerializerCapabilities.cs - - - Serialization\SerializerCodeGenerationConfiguration.cs - - - Serialization\SerializerCodeGenerationResult.cs - - - Serialization\SerializerDebugging.cs - - - Serialization\SerializerGenerator.cs - - - Serialization\SerializerOptions.cs - - - Serialization\SerializerRegistrationOptions.cs - - - Serialization\SerializerRepository.cs - - - Serialization\SerializerRepository.defaults.cs - - - Serialization\SerializerTypeKeyRepository.cs - - - Serialization\SerializingMember.cs - - - Serialization\Tracer.cs - - - Serialization\TypeKeyRepository.cs - - - Serialization\UnpackHelpers.cs - - - Serialization\UnpackHelpers.direct.cs - - - Serialization\UnpackHelpers.facade.cs - - - SetOperation.cs - - - StreamPacker.cs - - - StringEscape.cs - - - SubtreeUnpacker.cs - - - SubtreeUnpacker.Unpacking.cs - - - UnassignedMessageTypeException.cs - - - Unpacker.cs - - - Unpacker.Unpacking.cs - - - UnpackException.cs - - - Unpacking.cs - - - Unpacking.Numerics.cs - - - Unpacking.Others.cs - - - Unpacking.Streaming.cs - - - Unpacking.String.cs - - - UnpackingMode.cs - - - UnpackingResult.cs - - - UnpackingStream.cs - - - UnpackingStreamReader.cs - - - UnsafeNativeMethods.cs - - - Validation.cs - - - - True - True - Delegates.tt - - - - - True - True - Tuple`n.tt - - - - - - MsgPack.snk - - - remarks.xml - - - TextTemplatingFileGenerator - Delegates.cs - - - TextTemplatingFileGenerator - Tuple`n.cs - - - - - - - - \ No newline at end of file diff --git a/src/MsgPack.Net35/Properties/AssemblyInfo.cs b/src/MsgPack.Net35/Properties/AssemblyInfo.cs deleted file mode 100644 index b02142e04..000000000 --- a/src/MsgPack.Net35/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Security; - -[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )] -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library for .NET 3.5." )] - -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] - -[assembly: AllowPartiallyTrustedCallers] - -#if DEBUG || PERFORMANCE_TEST -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Net35, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.CodeDom.Net35, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - - diff --git a/src/MsgPack.Net35/Serialization/AbstractSerializers/.directory b/src/MsgPack.Net35/Serialization/AbstractSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net35/Serialization/CodeDomSerializers/.directory b/src/MsgPack.Net35/Serialization/CodeDomSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net35/Serialization/DefaultSerializers/.directory b/src/MsgPack.Net35/Serialization/DefaultSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net35/Serialization/EmittingSerializers/.directory b/src/MsgPack.Net35/Serialization/EmittingSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net35/Serialization/Metadata/.directory b/src/MsgPack.Net35/Serialization/Metadata/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net35/Serialization/Reflection/.directory b/src/MsgPack.Net35/Serialization/Reflection/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net35/Serialization/ReflectionSerializers/.directory b/src/MsgPack.Net35/Serialization/ReflectionSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Net45/MsgPack.Net45.csproj b/src/MsgPack.Net45/MsgPack.Net45.csproj deleted file mode 100644 index f1cfb29e4..000000000 --- a/src/MsgPack.Net45/MsgPack.Net45.csproj +++ /dev/null @@ -1,1021 +0,0 @@ - - - - - Debug - AnyCPU - {9C7B55A6-AF7F-4D26-AB5B-297B7FF25B6D} - Library - Properties - MsgPack - MsgPack - v4.5.2 - 512 - - - true - full - false - bin\Debug\ - TRACE;DEBUG;FEATURE_TAP;NETFX_45 - prompt - 4 - bin\Debug\MsgPack.XML - - - pdbonly - true - ..\..\bin\net452\ - TRACE;FEATURE_TAP;NETFX_45 - prompt - 4 - ..\..\bin\net452\MsgPack.XML - - - true - - - ..\MsgPack.snk - - - bin\CodeAnalysis\ - TRACE;FEATURE_TAP;NETFX_45;CODE_ANALYSIS - - - true - pdbonly - AnyCPU - prompt - AllRules.ruleset - true - - - - - - - - - Properties\CommonAssemblyInfo.cs - - - AsyncReadResult.cs - - - AsyncReadResult`1.cs - - - BigEndianBinary.cs - - - Binary.cs - - - BufferManager.cs - - - CollectionDebuggerProxy`1.cs - - - CollectionOperation.cs - - - DictionaryDebuggerProxy`2.cs - - - Float32Bits.cs - - - Float64Bits.cs - - - GlobalSuppressions.cs - - - IAsyncPackable.cs - - - IAsyncUnpackable.cs - - - InvalidMessagePackStreamException.cs - - - IPackable.cs - - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs - - - IUnpackable.cs - - - KnownExtTypeCode.cs - - - KnownExtTypeName.cs - - - MessageNotSupportedException.cs - - - MessagePackCode.cs - - - MessagePackConvert.cs - - - MessagePackExtendedTypeObject.cs - - - MessagePackObject.cs - - - MessagePackObject.Utilities.cs - - - MessagePackObjectDictionary.cs - - - MessagePackObjectDictionary.Enumerator.cs - - - MessagePackObjectDictionary.KeySet.cs - - - MessagePackObjectDictionary.KeySet.Enumerator.cs - - - MessagePackObjectDictionary.ValueCollection.cs - - - MessagePackObjectDictionary.ValueCollection.Enumerator.cs - - - MessagePackObjectEqualityComparer.cs - - - MessagePackString.cs - - - MessageTypeException.cs - - - Packer.cs - - - Packer.Nullable.cs - - - Packer.Packing.cs - - - PackerCompatibilityOptions.cs - - - PackerUnpackerExtensions.cs - - - PackerUnpackerStreamOptions.cs - - - PackingOptions.cs - - - PreserveAttribute.cs - - - ReflectionAbstractions.cs - - - Serialization\AbstractSerializers\ActionType.cs - - - Serialization\AbstractSerializers\CachedDelegateInfo.cs - - - Serialization\AbstractSerializers\ConstructorDefinition.cs - - - Serialization\AbstractSerializers\DynamicUnpackingContext.cs - - - Serialization\AbstractSerializers\EnumSerializerMethod.cs - - - Serialization\AbstractSerializers\FieldDefinition.cs - - - Serialization\AbstractSerializers\FieldName.cs - - - Serialization\AbstractSerializers\ICodeConstruct.cs - - - Serialization\AbstractSerializers\ISerializerBuilder.cs - - - Serialization\AbstractSerializers\ISerializerCodeGenerationContext.cs - - - Serialization\AbstractSerializers\ISerializerCodeGenerator.cs - - - Serialization\AbstractSerializers\MethodDefinition.cs - - - Serialization\AbstractSerializers\MethodName.cs - - - Serialization\AbstractSerializers\MethodNamePrefix.cs - - - Serialization\AbstractSerializers\SerializerBuilderHelper.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Collection.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.CommonConstructs.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Enum.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Nullable.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Object.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Tuple.cs - - - Serialization\AbstractSerializers\SerializerFieldKey.cs - - - Serialization\AbstractSerializers\SerializerGenerationContext.cs - - - Serialization\AbstractSerializers\SerializerSpecification.cs - - - Serialization\AbstractSerializers\TypeDefinition.cs - - - Serialization\CodeDomSerializers\CodeDomConstruct.cs - - - Serialization\CodeDomSerializers\CodeDomContext.cs - - - Serialization\CodeDomSerializers\CodeDomSerializerBuilder.cs - - - Serialization\CodeDomSerializers\ExpressionCodeDomConstruct.cs - - - Serialization\CodeDomSerializers\ParameterCodeDomConstruct.cs - - - Serialization\CodeDomSerializers\StatementCodeDomConstruct.cs - - - Serialization\CodeDomSerializers\VariableCodeDomConstruct.cs - - - Serialization\CollectionDetailedKind.cs - - - Serialization\CollectionKind.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ICollectionInstanceFactory.cs - - - Serialization\CollectionSerializers\NonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\ReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionTraitOptions.cs - - - Serialization\CollectionTraits.cs - - - Serialization\DataMemberContract.cs - - - Serialization\DateTimeConversionMethod.cs - - - Serialization\DateTimeMemberConversionMethod.cs - - - Serialization\DateTimeMessagePackSerializerHelpers.cs - - - Serialization\DefaultConcreteTypeRepository.cs - - - Serialization\DefaultSerializerNameResolver.cs - - - Serialization\DefaultSerializers\AbstractCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractCollectionSerializerHelper.cs - - - Serialization\DefaultSerializers\AbstractDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\AbstractEnumerableMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractNonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericListMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\ArraySegmentMessageSerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.Primitives.cs - - - Serialization\DefaultSerializers\ArraySerializer`1.cs - - - Serialization\DefaultSerializers\DateTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializer.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DefaultSerializers.cs - - - Serialization\DefaultSerializers\FileTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\GenericSerializer.cs - - - Serialization\DefaultSerializers\ImmutableCollectionSerializer`2.cs - - - Serialization\DefaultSerializers\ImmutableDictionarySerializer`3.cs - - - Serialization\DefaultSerializers\ImmutableStackSerializer`2.cs - - - Serialization\DefaultSerializers\InternalDateTimeExtensions.cs - - - Serialization\DefaultSerializers\MessagePackObjectExtensions.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MultidimensionalArraySerializer`1.cs - - - Serialization\DefaultSerializers\NativeDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NativeFileTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NullableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ArraySegment_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ByteArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_CharArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_DictionaryEntryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Stack_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_QueueMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_StackMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_DBNullMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Globalization_CultureInfoMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Numerics_ComplexMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_ObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_StringMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Text_StringBuilderMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_UriMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocFileTimeMessagePackSerializer.cs - - - Serialization\EmitterFlavor.cs - - - Serialization\EmittingSerializers\AndConditionILConstruct.cs - - - Serialization\EmittingSerializers\AssemblyBuilderCodeGenerationContext.cs - - - Serialization\EmittingSerializers\AssemblyBuilderEmittingContext.cs - - - Serialization\EmittingSerializers\AssemblyBuilderSerializerBuilder.cs - - - Serialization\EmittingSerializers\BinaryOperatorILConstruct.cs - - - Serialization\EmittingSerializers\ConditionalILConstruct.cs - - - Serialization\EmittingSerializers\ContextfulILConstruct.cs - - - Serialization\EmittingSerializers\ILConstruct.cs - - - Serialization\EmittingSerializers\ILMethodConctext.cs - - - Serialization\EmittingSerializers\InvocationILConsruct.cs - - - Serialization\EmittingSerializers\LoadFieldILConstruct.cs - - - Serialization\EmittingSerializers\SequenceILConstruct.cs - - - Serialization\EmittingSerializers\SerializationMethodGeneratorManager.cs - - - Serialization\EmittingSerializers\SerializerEmitter.cs - - - Serialization\EmittingSerializers\SerializerEmitter.enum.cs - - - Serialization\EmittingSerializers\SerializerEmitter.object.cs - - - Serialization\EmittingSerializers\SinglelStepILConstruct.cs - - - Serialization\EmittingSerializers\StatementExpressionILConstruct.cs - - - Serialization\EmittingSerializers\StoreFieldILConstruct.cs - - - Serialization\EmittingSerializers\StoreVariableILConstruct.cs - - - Serialization\EmittingSerializers\UnaryOperatorILConstruct.cs - - - Serialization\EmittingSerializers\VariableILConstruct.cs - - - Serialization\EnumMemberSerializationMethod.cs - - - Serialization\EnumMessagePackSerializerHelpers.cs - - - Serialization\EnumMessagePackSerializerProvider.cs - - - Serialization\EnumMessagePackSerializer`1.cs - - - Serialization\EnumSerializationMethod.cs - - - Serialization\ExtTypeCodeMapping.cs - - - Serialization\FromExpression.cs - - - Serialization\FromExpression.ToMethod.cs - - - Serialization\ICustomizableEnumSerializer.cs - - - Serialization\IdentifierUtility.cs - - - Serialization\IMessagePackSerializer.cs - - - Serialization\IMessagePackSingleObjectSerializer.cs - - - Serialization\INilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\INilImplicationHandlerParameter.cs - - - Serialization\ISerializerGeneratorConfiguration.cs - - - Serialization\LazyDelegatingMessagePackSerializer`1.cs - - - Serialization\MessagePackDateTimeMemberAttribute.cs - - - Serialization\MessagePackDeserializationConstructorAttribute.cs - - - Serialization\MessagePackEnumAttribute.cs - - - Serialization\MessagePackEnumMemberAttribute.cs - - - Serialization\MessagePackIgnoreAttribute.cs - - - Serialization\MessagePackKnownTypeAttributes.cs - - - Serialization\MessagePackMemberAttribute.cs - - - Serialization\MessagePackRuntimeTypeAttributes.cs - - - Serialization\MessagePackSerializer.cs - - - Serialization\MessagePackSerializer.Factories.cs - - - Serialization\MessagePackSerializerExtensions.cs - - - Serialization\MessagePackSerializerProvider.cs - - - Serialization\MessagePackSerializer`1.cs - - - Serialization\Metadata\_CultureInfo.cs - - - Serialization\Metadata\_DateTimeMessagePackSerializerHelpers.cs - - - Serialization\Metadata\_Decimal.cs - - - Serialization\Metadata\_DictionaryEntry.cs - - - Serialization\Metadata\_DynamicUnpackingContext.cs - - - Serialization\Metadata\_EnumMessagePackSerializerHelpers.cs - - - Serialization\Metadata\_FieldInfo.cs - - - Serialization\Metadata\_IDictionaryEnumerator.cs - - - Serialization\Metadata\_IDisposable.cs - - - Serialization\Metadata\_IEnumreator.cs - - - Serialization\Metadata\_MessagePackObject.cs - - - Serialization\Metadata\_MessagePackSerializer.cs - - - Serialization\Metadata\_MethodBase.cs - - - Serialization\Metadata\_Object.cs - - - Serialization\Metadata\_Packer.cs - - - Serialization\Metadata\_SerializationContext.cs - - - Serialization\Metadata\_String.cs - - - Serialization\Metadata\_Unpacker.cs - - - Serialization\Metadata\_UnpackHelpers.cs - - - Serialization\Metadata\_UnpackHelpers.direct.cs - - - Serialization\NilImplication.cs - - - Serialization\NilImplicationHandler`4.cs - - - Serialization\PackHelpers.cs - - - Serialization\Polymorphic\IPolymorphicDeserializer.cs - - - Serialization\Polymorphic\IPolymorphicHelperAttributes.cs - - - Serialization\Polymorphic\KnownTypePolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs - - - Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\TypeInfoEncoder.cs - - - Serialization\Polymorphic\TypeInfoEncoding.cs - - - Serialization\PolymorphismSchema.Constructors.cs - - - Serialization\PolymorphismSchema.cs - - - Serialization\PolymorphismSchema.Internals.cs - - - Serialization\PolymorphismSchemaChildrenType.cs - - - Serialization\PolymorphismTarget.cs - - - Serialization\PolymorphismType.cs - - - Serialization\ReflectionExtensions.cs - - - Serialization\ReflectionHelpers.cs - - - Serialization\ReflectionSerializers\ReflectionCollectionMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionDictionaryMessagePackSerializer`3.cs - - - Serialization\ReflectionSerializers\ReflectionEnumerableMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionEnumMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNilImplicationHandler.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricCollectionMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericListMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionObjectMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerHelper.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - - Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - - - Serialization\Reflection\TracingILGenerator.conveniences.cs - - - Serialization\Reflection\TracingILGenerator.cs - - - Serialization\Reflection\TracingILGenerator.emits.cs - - - Serialization\ResolveSerializerEventArgs.cs - - - Serialization\SerializationCompatibilityOptions.cs - - - Serialization\SerializationContext.cs - - - Serialization\SerializationContext.ExtTypeCodes.cs - - - Serialization\SerializationExceptions.cs - - - Serialization\SerializationMethod.cs - - - Serialization\SerializationMethodGeneratorOption.cs - - - Serialization\SerializationTarget.cs - - - Serialization\SerializerAssemblyGenerationConfiguration.cs - - - Serialization\SerializerCapabilities.cs - - - Serialization\SerializerCodeGenerationConfiguration.cs - - - Serialization\SerializerCodeGenerationResult.cs - - - Serialization\SerializerDebugging.cs - - - Serialization\SerializerGenerator.cs - - - Serialization\SerializerOptions.cs - - - Serialization\SerializerRegistrationOptions.cs - - - Serialization\SerializerRepository.cs - - - Serialization\SerializerRepository.defaults.cs - - - Serialization\SerializerTypeKeyRepository.cs - - - Serialization\SerializingMember.cs - - - Serialization\Tracer.cs - - - Serialization\TypeKeyRepository.cs - - - Serialization\UnpackHelpers.cs - - - Serialization\UnpackHelpers.direct.cs - - - Serialization\UnpackHelpers.facade.cs - - - SetOperation.cs - - - StreamPacker.cs - - - StringEscape.cs - - - SubtreeUnpacker.cs - - - SubtreeUnpacker.Unpacking.cs - - - TupleItems.cs - - - UnassignedMessageTypeException.cs - - - Unpacker.cs - - - Unpacker.Unpacking.cs - - - UnpackException.cs - - - Unpacking.cs - - - Unpacking.Numerics.cs - - - Unpacking.Others.cs - - - Unpacking.Streaming.cs - - - Unpacking.String.cs - - - UnpackingMode.cs - - - UnpackingResult.cs - - - UnpackingStream.cs - - - UnpackingStreamReader.cs - - - UnsafeNativeMethods.cs - - - Validation.cs - - - - - - MsgPack.snk - - - remarks.xml - - - - - \ No newline at end of file diff --git a/src/MsgPack.Net45/Properties/AssemblyInfo.cs b/src/MsgPack.Net45/Properties/AssemblyInfo.cs deleted file mode 100644 index cecb1474f..000000000 --- a/src/MsgPack.Net45/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2015-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Security; - -[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )] -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library." )] - -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] - -[assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )] -[assembly: AllowPartiallyTrustedCallers] - -#if DEBUG || PERFORMANCE_TEST -[assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.CodeDom, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - - diff --git a/src/MsgPack.Silverlight.5/MsgPack.Silverlight.5.csproj b/src/MsgPack.Silverlight.5/MsgPack.Silverlight.5.csproj index eab34d3ff..83eac8e7c 100644 --- a/src/MsgPack.Silverlight.5/MsgPack.Silverlight.5.csproj +++ b/src/MsgPack.Silverlight.5/MsgPack.Silverlight.5.csproj @@ -1,15 +1,11 @@  - Debug - AnyCPU 8.0.50727 2.0 {F9477829-6A6D-4540-9F0D-68F8C6D8E18B} {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} Library - Properties - MsgPack MsgPack Silverlight v5.0 @@ -24,48 +20,15 @@ v3.5 - - true - full - false - Bin\Debug - DEBUG;TRACE;SILVERLIGHT - true - true - prompt - 4 - Bin\Debug\MsgPack.XML - - - pdbonly - true - ..\..\bin\sl5\ - TRACE;SILVERLIGHT - true - true - prompt - 4 - ..\..\bin\sl5\MsgPack.XML - - - true - + - ..\MsgPack.snk - - - bin\CodeAnalysis\ - TRACE;SILVERLIGHT;CODE_ANALYSIS - - - true true - pdbonly - AnyCPU - prompt - AllRules.ruleset true - true + $(DefineConstants);SILVERLIGHT + + + $(SolutionDir)\bin\sl5\ + $(SolutionDir)\bin\sl5\MsgPack.XML @@ -78,9 +41,6 @@ Properties\CommonAssemblyInfo.cs - - Volatile.cs - AsyncReadResult.cs @@ -96,15 +56,33 @@ BufferManager.cs + + ByteArrayPacker.cs + + + ByteArrayUnpacker.cs + + + ByteBufferAllocator.cs + CollectionDebuggerProxy`1.cs CollectionOperation.cs + + CollectionType.cs + DictionaryDebuggerProxy`2.cs + + EncodingExtensions.cs + + + FixedArrayBufferAllocator.cs + Float32Bits.cs @@ -120,23 +98,20 @@ IAsyncUnpackable.cs + + Int32OffsetValue`1.cs + + + Int64OffsetValue`1.cs + InvalidMessagePackStreamException.cs IPackable.cs - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs + + IRootUnpacker.cs IUnpackable.cs @@ -150,6 +125,18 @@ MessageNotSupportedException.cs + + MessagePackByteArrayPacker.cs + + + MessagePackByteArrayPacker.Pack.cs + + + MessagePackByteArrayUnpacker.cs + + + MessagePackByteArrayUnpacker.Unpack.cs + MessagePackCode.cs @@ -186,6 +173,18 @@ MessagePackObjectEqualityComparer.cs + + MessagePackStreamPacker.cs + + + MessagePackStreamPacker.Pack.cs + + + MessagePackStreamUnpacker.cs + + + MessagePackStreamUnpacker.Unpack.cs + MessagePackString.cs @@ -195,6 +194,9 @@ Packer.cs + + Packer.Factory.cs + Packer.Nullable.cs @@ -216,36 +218,63 @@ PreserveAttribute.cs + + ReadValueResult.cs + + + ReadValueResults.cs + ReflectionAbstractions.cs + + Serialization\Metadata\_MessagePackSerializer.cs + + + Serialization\Metadata\_SerializationContext.cs + + + Serialization\Reflection\TracingILGenerator.conveniences.cs + + + Serialization\Reflection\TracingILGenerator.cs + + + Serialization\Reflection\TracingILGenerator.emits.cs + + + Serialization\ReflectionExtensions.ConstructorDelegate.cs + + + Serialization\BindingOptions.cs + Serialization\CollectionDetailedKind.cs Serialization\CollectionKind.cs - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + + Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\ICollectionInstanceFactory.cs @@ -255,12 +284,12 @@ Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs + + Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs + Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs @@ -378,12 +407,12 @@ Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs + + Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs + Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs @@ -414,36 +443,51 @@ Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs + + Serialization\DefaultSerializers\TimestampDateTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializerProvider.cs + Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs + + Serialization\DictionaryKeyTransformers.cs + + + Serialization\DictionarySerializationOptions.cs + Serialization\EmitterFlavor.cs Serialization\EnumMemberSerializationMethod.cs + + Serialization\EnumMessagePackSerializer`1.cs + Serialization\EnumMessagePackSerializerHelpers.cs Serialization\EnumMessagePackSerializerProvider.cs - - Serialization\EnumMessagePackSerializer`1.cs + + Serialization\EnumNameTransformers.cs Serialization\EnumSerializationMethod.cs + + Serialization\EnumSerializationOptions.cs + Serialization\ExtTypeCodeMapping.cs - - Serialization\FromExpression.cs - - - Serialization\FromExpression.ToMethod.cs - Serialization\ICustomizableEnumSerializer.cs @@ -462,6 +506,9 @@ Serialization\INilImplicationHandlerParameter.cs + + Serialization\KeyNameTransformers.cs + Serialization\LazyDelegatingMessagePackSerializer`1.cs @@ -495,27 +542,27 @@ Serialization\MessagePackSerializer.Factories.cs + + Serialization\MessagePackSerializer`1.cs + Serialization\MessagePackSerializerExtensions.cs Serialization\MessagePackSerializerProvider.cs - - Serialization\MessagePackSerializer`1.cs - - - Serialization\Metadata\_MessagePackSerializer.cs - - - Serialization\Metadata\_SerializationContext.cs - Serialization\NilImplication.cs Serialization\NilImplicationHandler`4.cs + + Serialization\NullTextWriter.cs + + + Serialization\PackHelperParameters.cs + Serialization\PackHelpers.cs @@ -531,6 +578,9 @@ Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs + + Serialization\Polymorphic\RuntimeTypeVerifier.cs + Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs @@ -540,6 +590,9 @@ Serialization\Polymorphic\TypeInfoEncoding.cs + + Serialization\PolymorphicTypeVerificationContext.cs + Serialization\PolymorphismSchema.Constructors.cs @@ -558,9 +611,21 @@ Serialization\PolymorphismType.cs + + Serialization\Reflection\GenericTypeExtensions.cs + + + Serialization\Reflection\ReflectionExtensions.cs + + + Serialization\ReflectionExtensions.CollectionTraits.cs + Serialization\ReflectionExtensions.cs + + Serialization\ReflectionExtensions.InvokePreservingExtension.cs + Serialization\ReflectionHelpers.cs @@ -606,15 +671,12 @@ Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - Serialization\ResolveSerializerEventArgs.cs + + Serialization\SerializationCompatibilityLevel.cs + Serialization\SerializationCompatibilityOptions.cs @@ -663,6 +725,9 @@ Serialization\TypeKeyRepository.cs + + Serialization\UnpackHelperParameters.cs + Serialization\UnpackHelpers.cs @@ -675,8 +740,8 @@ SetOperation.cs - - StreamPacker.cs + + SingleArrayBufferAllocator.cs StringEscape.cs @@ -687,6 +752,42 @@ SubtreeUnpacker.Unpacking.cs + + Timestamp.Calculation.cs + + + Timestamp.Comparison.cs + + + Timestamp.Conversion.cs + + + Timestamp.cs + + + Timestamp.ParseExact.cs + + + Timestamp.Properties.cs + + + Timestamp.ToString.cs + + + Timestamp.TryParseExact.cs + + + TimestampParseResult.cs + + + TimestampStringConverter.cs + + + TimestampStringConverter.Parse.cs + + + TimestampStringConverter.ToString.cs + TupleItems.cs @@ -696,9 +797,18 @@ Unpacker.cs + + Unpacker.Leaf.cs + Unpacker.Unpacking.cs + + UnpackerOptions.cs + + + UnpackerValidationLevel.cs + UnpackException.cs @@ -732,6 +842,9 @@ UnsafeNativeMethods.cs + + Volatile.cs + diff --git a/src/MsgPack.Silverlight.5/Serialization/SourceLevels.cs b/src/MsgPack.Silverlight.5/Serialization/SourceLevels.cs deleted file mode 100644 index a16953c12..000000000 --- a/src/MsgPack.Silverlight.5/Serialization/SourceLevels.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if SILVERLIGHT || XAMDROID -using System; - -namespace MsgPack.Serialization -{ - /// - /// System.Diagnostics.SourceLevels alternative. - /// - [Flags] - internal enum SourceLevels - { - Verbose = 0x1, - Information = 0x2, - All = unchecked( ( int )0xffffffff ) - } -} -#endif // if SILVERLIGHT || XAMDROID diff --git a/src/MsgPack.Silverlight.5/Serialization/SourceSwitch.cs b/src/MsgPack.Silverlight.5/Serialization/SourceSwitch.cs deleted file mode 100644 index c75aeacfc..000000000 --- a/src/MsgPack.Silverlight.5/Serialization/SourceSwitch.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if SILVERLIGHT || XAMDROID -using System; - -namespace MsgPack.Serialization -{ - /// - /// System.Diagnostics.SourceSwitch alternative. - /// - internal sealed class SourceSwitch - { - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For API compatibility" )] - public SourceLevels Level - { - get; - set; - } - - internal SourceSwitch() { } - } -} -#endif // if SILVERLIGHT || XAMDROID \ No newline at end of file diff --git a/src/MsgPack.Silverlight.5/Serialization/TraceEventType.cs b/src/MsgPack.Silverlight.5/Serialization/TraceEventType.cs deleted file mode 100644 index eca98b1c5..000000000 --- a/src/MsgPack.Silverlight.5/Serialization/TraceEventType.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if SILVERLIGHT || XAMDROID -using System; - -namespace MsgPack.Serialization -{ - /// - /// System.Diagnostics.TraceEventType alternative. - /// - internal enum TraceEventType - { - Verbose, - Information - } -} -#endif // if SILVERLIGHT || XAMDROID \ No newline at end of file diff --git a/src/MsgPack.Silverlight.5/Serialization/TraceSource.cs b/src/MsgPack.Silverlight.5/Serialization/TraceSource.cs deleted file mode 100644 index a6cfbd05a..000000000 --- a/src/MsgPack.Silverlight.5/Serialization/TraceSource.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if SILVERLIGHT || XAMDROID -using System; -using System.Diagnostics; -using System.Globalization; - -namespace MsgPack.Serialization -{ - /// - /// System.Diagnostics.TraceSource alternative. - /// - internal sealed class TraceSource - { - private const string _template = "{0} {1}: {2} :{3}"; - - private readonly SourceSwitch _switch = new SourceSwitch() { Level = SourceLevels.All }; - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For API compatibility" )] - public SourceSwitch Switch - { - get { return this._switch; } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Debugging code only" )] - private readonly string _name; - - public TraceSource( string name ) - { - this._name = name; - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "For API compatibility" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "eventType", Justification = "Debugging code only" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "eventId", Justification = "Debugging code only" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "data", Justification = "Debugging code only" )] - public void TraceData( TraceEventType eventType, int eventId, object data ) - { - Debug.WriteLine( _template, this._name, eventType, eventId, data ); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "For API compatibility" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "eventType", Justification = "Debugging code only" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "eventId", Justification = "Debugging code only" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "format", Justification = "Debugging code only" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args", Justification = "Debugging code only" )] - public void TraceEvent( TraceEventType eventType, int eventId, string format, params object[] args ) - { - Debug.WriteLine( _template, this._name, eventType, eventId, String.Format( CultureInfo.CurrentCulture, format, args ) ); - } - } -} -#endif // if SILVERLIGHT || XAMDROID \ No newline at end of file diff --git a/src/MsgPack.Silverlight.WindowsPhone/MsgPack.Silverlight.WindowsPhone.csproj b/src/MsgPack.Silverlight.WindowsPhone/MsgPack.Silverlight.WindowsPhone.csproj index e3e7e4256..c9c2841e9 100644 --- a/src/MsgPack.Silverlight.WindowsPhone/MsgPack.Silverlight.WindowsPhone.csproj +++ b/src/MsgPack.Silverlight.WindowsPhone/MsgPack.Silverlight.WindowsPhone.csproj @@ -1,15 +1,11 @@  - Debug - AnyCPU 10.0.20506 2.0 {336AC996-060D-4109-B99B-854CCEEEA695} {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} Library - Properties - MsgPack MsgPack WindowsPhone v8.0 @@ -19,102 +15,16 @@ 11.0 true - - true - full - false - Bin\Debug - TRACE;DEBUG;SILVERLIGHT;WINDOWS_PHONE;AOT - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\windowsphone8\ - TRACE;SILVERLIGHT;WINDOWS_PHONE;AOT - true - true - prompt - 4 - ..\..\bin\windowsphone8\MsgPack.XML - - - true - full - false - Bin\x86\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - pdbonly - true - Bin\x86\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - true - full - false - Bin\ARM\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - pdbonly - true - Bin\ARM\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE + + true true - prompt - 4 + $(DefineConstants);SILVERLIGHT;WINDOWS_PHONE;AOT + false - - bin\CodeAnalysis\ - TRACE;SILVERLIGHT;WINDOWS_PHONE;AOT;CODE_ANALYSIS - - - true - true - pdbonly - AnyCPU - prompt - AllRules.ruleset - true - - - bin\x86\CodeAnalysis\ - TRACE;SILVERLIGHT;WINDOWS_PHONE;CODE_ANALYSIS - true - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\ARM\CodeAnalysis\ - TRACE;SILVERLIGHT;WINDOWS_PHONE;CODE_ANALYSIS - true - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset + + $(SolutionDir)\bin\windowsphone8\ + $(SolutionDir)\bin\windowsphone8\MsgPack.XML @@ -135,15 +45,33 @@ BufferManager.cs + + ByteArrayPacker.cs + + + ByteArrayUnpacker.cs + + + ByteBufferAllocator.cs + CollectionDebuggerProxy`1.cs CollectionOperation.cs + + CollectionType.cs + DictionaryDebuggerProxy`2.cs + + EncodingExtensions.cs + + + FixedArrayBufferAllocator.cs + Float32Bits.cs @@ -159,23 +87,20 @@ IAsyncUnpackable.cs + + Int32OffsetValue`1.cs + + + Int64OffsetValue`1.cs + InvalidMessagePackStreamException.cs IPackable.cs - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs + + IRootUnpacker.cs IUnpackable.cs @@ -189,6 +114,18 @@ MessageNotSupportedException.cs + + MessagePackByteArrayPacker.cs + + + MessagePackByteArrayPacker.Pack.cs + + + MessagePackByteArrayUnpacker.cs + + + MessagePackByteArrayUnpacker.Unpack.cs + MessagePackCode.cs @@ -225,6 +162,18 @@ MessagePackObjectEqualityComparer.cs + + MessagePackStreamPacker.cs + + + MessagePackStreamPacker.Pack.cs + + + MessagePackStreamUnpacker.cs + + + MessagePackStreamUnpacker.Unpack.cs + MessagePackString.cs @@ -234,6 +183,9 @@ Packer.cs + + Packer.Factory.cs + Packer.Nullable.cs @@ -255,36 +207,45 @@ PreserveAttribute.cs + + ReadValueResult.cs + + + ReadValueResults.cs + ReflectionAbstractions.cs + + Serialization\BindingOptions.cs + Serialization\CollectionDetailedKind.cs Serialization\CollectionKind.cs - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + + Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\ICollectionInstanceFactory.cs @@ -294,12 +255,12 @@ Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs + + Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs + Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs @@ -387,6 +348,12 @@ Serialization\DefaultSerializers\FileTimeMessagePackSerializerProvider.cs + + Serialization\DefaultSerializers\FSharpCollectionSerializer`2.cs + + + Serialization\DefaultSerializers\FSharpMapSerializer`3.cs + Serialization\DefaultSerializers\GenericSerializer.cs @@ -444,12 +411,12 @@ Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs + + Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs + Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs @@ -477,30 +444,54 @@ Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs + + Serialization\DefaultSerializers\TimestampDateTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampFileTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializerProvider.cs + Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs Serialization\DefaultSerializers\UnixEpocFileTimeMessagePackSerializer.cs + + Serialization\DictionaryKeyTransformers.cs + + + Serialization\DictionarySerializationOptions.cs + Serialization\EmitterFlavor.cs Serialization\EnumMemberSerializationMethod.cs + + Serialization\EnumMessagePackSerializer`1.cs + Serialization\EnumMessagePackSerializerHelpers.cs Serialization\EnumMessagePackSerializerProvider.cs - - Serialization\EnumMessagePackSerializer`1.cs + + Serialization\EnumNameTransformers.cs Serialization\EnumSerializationMethod.cs + + Serialization\EnumSerializationOptions.cs + Serialization\ExtTypeCodeMapping.cs @@ -522,6 +513,9 @@ Serialization\INilImplicationHandlerParameter.cs + + Serialization\KeyNameTransformers.cs + Serialization\LazyDelegatingMessagePackSerializer`1.cs @@ -555,21 +549,27 @@ Serialization\MessagePackSerializer.Factories.cs + + Serialization\MessagePackSerializer`1.cs + Serialization\MessagePackSerializerExtensions.cs Serialization\MessagePackSerializerProvider.cs - - Serialization\MessagePackSerializer`1.cs - Serialization\NilImplication.cs Serialization\NilImplicationHandler`4.cs + + Serialization\NullTextWriter.cs + + + Serialization\PackHelperParameters.cs + Serialization\PackHelpers.cs @@ -585,6 +585,9 @@ Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs + + Serialization\Polymorphic\RuntimeTypeVerifier.cs + Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs @@ -594,6 +597,9 @@ Serialization\Polymorphic\TypeInfoEncoding.cs + + Serialization\PolymorphicTypeVerificationContext.cs + Serialization\PolymorphismSchema.Constructors.cs @@ -612,9 +618,21 @@ Serialization\PolymorphismType.cs + + Serialization\Reflection\GenericTypeExtensions.cs + + + Serialization\Reflection\ReflectionExtensions.cs + + + Serialization\ReflectionExtensions.CollectionTraits.cs + Serialization\ReflectionExtensions.cs + + Serialization\ReflectionExtensions.InvokePreservingExtension.cs + Serialization\ReflectionHelpers.cs @@ -660,15 +678,12 @@ Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - Serialization\ResolveSerializerEventArgs.cs + + Serialization\SerializationCompatibilityLevel.cs + Serialization\SerializationCompatibilityOptions.cs @@ -717,6 +732,9 @@ Serialization\TypeKeyRepository.cs + + Serialization\UnpackHelperParameters.cs + Serialization\UnpackHelpers.cs @@ -729,8 +747,8 @@ SetOperation.cs - - StreamPacker.cs + + SingleArrayBufferAllocator.cs StringEscape.cs @@ -741,6 +759,42 @@ SubtreeUnpacker.Unpacking.cs + + Timestamp.Calculation.cs + + + Timestamp.Comparison.cs + + + Timestamp.Conversion.cs + + + Timestamp.cs + + + Timestamp.ParseExact.cs + + + Timestamp.Properties.cs + + + Timestamp.ToString.cs + + + Timestamp.TryParseExact.cs + + + TimestampParseResult.cs + + + TimestampStringConverter.cs + + + TimestampStringConverter.Parse.cs + + + TimestampStringConverter.ToString.cs + TupleItems.cs @@ -750,9 +804,18 @@ Unpacker.cs + + Unpacker.Leaf.cs + Unpacker.Unpacking.cs + + UnpackerOptions.cs + + + UnpackerValidationLevel.cs + UnpackException.cs diff --git a/src/MsgPack.Unity.Full/CorLibOnlyHelper.cs b/src/MsgPack.Unity.Full/CorLibOnlyHelper.cs index 6dfaa0a3e..46f76803a 100644 --- a/src/MsgPack.Unity.Full/CorLibOnlyHelper.cs +++ b/src/MsgPack.Unity.Full/CorLibOnlyHelper.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // diff --git a/src/MsgPack.Unity.Full/MsgPack.Unity.Full.csproj b/src/MsgPack.Unity.Full/MsgPack.Unity.Full.csproj index 502be308e..5eb7d60dd 100644 --- a/src/MsgPack.Unity.Full/MsgPack.Unity.Full.csproj +++ b/src/MsgPack.Unity.Full/MsgPack.Unity.Full.csproj @@ -2,8 +2,6 @@ - Debug - AnyCPU {30581B4A-BCA5-4446-B5E7-4F890A3E9514} Library Properties @@ -11,48 +9,25 @@ MsgPack v3.5 512 - - - true - full - false - bin\Debug\ - TRACE;DEBUG;UNITY_IPHONE;MSGPACK_UNITY_FULL;AOT - prompt - 4 - bin\Debug\MsgPack.XML + true 3001,3002 - - pdbonly - true - ..\..\build\MsgPack-CLI\unity-full\ - TRACE;UNITY_IPHONE;MSGPACK_UNITY_FULL;AOT - prompt - 4 - ..\..\build\MsgPack-CLI\unity-full\MsgPack.XML - 3001,3002 + + + $(DefineConstants);FEATURE_MPCONTRACT;UNITY_IPHONE;MSGPACK_UNITY_FULL;AOT + false - - bin\CodeAnalysis\ - TRACE;UNITY_IPHONE;MSGPACK_UNITY_FULL;AOT;CODE_ANALYSIS - - - true - 3001,3002 - pdbonly - AnyCPU - prompt - AllRules.ruleset - true + + $(NoWarn),1591 + + + $(SolutionDir)\build\MsgPack-CLI\unity-full\ + $(SolutionDir)\build\MsgPack-CLI\unity-full\MsgPack.XML Properties\CommonAssemblyInfo.cs - - Volatile.cs - AsyncReadResult.cs @@ -68,15 +43,33 @@ BufferManager.cs + + ByteArrayPacker.cs + + + ByteArrayUnpacker.cs + + + ByteBufferAllocator.cs + CollectionDebuggerProxy`1.cs CollectionOperation.cs + + CollectionType.cs + DictionaryDebuggerProxy`2.cs + + EncodingExtensions.cs + + + FixedArrayBufferAllocator.cs + Float32Bits.cs @@ -92,23 +85,20 @@ IAsyncUnpackable.cs + + Int32OffsetValue`1.cs + + + Int64OffsetValue`1.cs + InvalidMessagePackStreamException.cs IPackable.cs - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs + + IRootUnpacker.cs IUnpackable.cs @@ -122,6 +112,18 @@ MessageNotSupportedException.cs + + MessagePackByteArrayPacker.cs + + + MessagePackByteArrayPacker.Pack.cs + + + MessagePackByteArrayUnpacker.cs + + + MessagePackByteArrayUnpacker.Unpack.cs + MessagePackCode.cs @@ -158,15 +160,33 @@ MessagePackObjectEqualityComparer.cs + + MessagePackStreamPacker.cs + + + MessagePackStreamPacker.Pack.cs + + + MessagePackStreamUnpacker.cs + + + MessagePackStreamUnpacker.Unpack.cs + MessagePackString.cs MessageTypeException.cs + + MPContract.cs + Packer.cs + + Packer.Factory.cs + Packer.Nullable.cs @@ -188,36 +208,48 @@ PreserveAttribute.cs + + ReadValueResult.cs + + + ReadValueResults.cs + ReflectionAbstractions.cs + + Serialization\Tracer.cs + + + Serialization\BindingOptions.cs + Serialization\CollectionDetailedKind.cs Serialization\CollectionKind.cs - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + + Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\ICollectionInstanceFactory.cs @@ -227,12 +259,12 @@ Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs + + Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs + Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs @@ -350,12 +382,12 @@ Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs + + Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs + Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs @@ -392,27 +424,48 @@ Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs + + Serialization\DefaultSerializers\TimestampDateTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializerProvider.cs + Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs + + Serialization\DictionaryKeyTransformers.cs + + + Serialization\DictionarySerializationOptions.cs + Serialization\EmitterFlavor.cs Serialization\EnumMemberSerializationMethod.cs + + Serialization\EnumMessagePackSerializer`1.cs + Serialization\EnumMessagePackSerializerHelpers.cs Serialization\EnumMessagePackSerializerProvider.cs - - Serialization\EnumMessagePackSerializer`1.cs + + Serialization\EnumNameTransformers.cs Serialization\EnumSerializationMethod.cs + + Serialization\EnumSerializationOptions.cs + Serialization\ExtTypeCodeMapping.cs @@ -434,6 +487,9 @@ Serialization\INilImplicationHandlerParameter.cs + + Serialization\KeyNameTransformers.cs + Serialization\LazyDelegatingMessagePackSerializer`1.cs @@ -467,21 +523,27 @@ Serialization\MessagePackSerializer.Factories.cs + + Serialization\MessagePackSerializer`1.cs + Serialization\MessagePackSerializerExtensions.cs Serialization\MessagePackSerializerProvider.cs - - Serialization\MessagePackSerializer`1.cs - Serialization\NilImplication.cs Serialization\NilImplicationHandler`4.cs + + Serialization\NullTextWriter.cs + + + Serialization\PackHelperParameters.cs + Serialization\PackHelpers.cs @@ -497,6 +559,9 @@ Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs + + Serialization\Polymorphic\RuntimeTypeVerifier.cs + Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs @@ -506,6 +571,9 @@ Serialization\Polymorphic\TypeInfoEncoding.cs + + Serialization\PolymorphicTypeVerificationContext.cs + Serialization\PolymorphismSchema.Constructors.cs @@ -524,9 +592,21 @@ Serialization\PolymorphismType.cs + + Serialization\Reflection\GenericTypeExtensions.cs + + + Serialization\Reflection\ReflectionExtensions.cs + + + Serialization\ReflectionExtensions.CollectionTraits.cs + Serialization\ReflectionExtensions.cs + + Serialization\ReflectionExtensions.InvokePreservingExtension.cs + Serialization\ReflectionHelpers.cs @@ -569,15 +649,12 @@ Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - Serialization\ResolveSerializerEventArgs.cs + + Serialization\SerializationCompatibilityLevel.cs + Serialization\SerializationCompatibilityOptions.cs @@ -626,6 +703,9 @@ Serialization\TypeKeyRepository.cs + + Serialization\UnpackHelperParameters.cs + Serialization\UnpackHelpers.cs @@ -638,8 +718,8 @@ SetOperation.cs - - StreamPacker.cs + + SingleArrayBufferAllocator.cs StringEscape.cs @@ -650,6 +730,42 @@ SubtreeUnpacker.Unpacking.cs + + Timestamp.Calculation.cs + + + Timestamp.Comparison.cs + + + Timestamp.Conversion.cs + + + Timestamp.cs + + + Timestamp.ParseExact.cs + + + Timestamp.Properties.cs + + + Timestamp.ToString.cs + + + Timestamp.TryParseExact.cs + + + TimestampParseResult.cs + + + TimestampStringConverter.cs + + + TimestampStringConverter.Parse.cs + + + TimestampStringConverter.ToString.cs + TupleItems.cs @@ -659,9 +775,18 @@ Unpacker.cs + + Unpacker.Leaf.cs + Unpacker.Unpacking.cs + + UnpackerOptions.cs + + + UnpackerValidationLevel.cs + UnpackException.cs @@ -692,8 +817,8 @@ UnpackingStreamReader.cs - - MPContract.cs + + Volatile.cs True diff --git a/src/MsgPack.Unity.Full/Serialization/AotHelper.EqualityComparers.tt b/src/MsgPack.Unity.Full/Serialization/AotHelper.EqualityComparers.tt index 304c28d0f..8a3691ea2 100644 --- a/src/MsgPack.Unity.Full/Serialization/AotHelper.EqualityComparers.tt +++ b/src/MsgPack.Unity.Full/Serialization/AotHelper.EqualityComparers.tt @@ -31,6 +31,7 @@ var excludingTypes = new HashSet { "System.ArgIterator", + "System.ValueTuple", "System.RuntimeArgumentHandle", "System.TypedReference", "System.Void", @@ -60,8 +61,14 @@ var excludingTypes = "System.Security.Cryptography.CngProperty", "System.Security.Cryptography.CngPropertyOptions", "System.Security.Cryptography.CngUIProtectionLevels", + "System.Security.Cryptography.ECCurve", "System.Security.Cryptography.ECDiffieHellmanKeyDerivationFunction", "System.Security.Cryptography.ECKeyXmlFormat", + "System.Security.Cryptography.ECParameters", + "System.Security.Cryptography.ECPoint", + "System.Security.Cryptography.HashAlgorithmName", + "System.Security.Cryptography.RSAEncryptionPaddingMode", + "System.Security.Cryptography.RSASignaturePaddingMode", "System.Security.Cryptography.SignatureVerificationResult", "System.Security.Cryptography.X509Certificates.TrustStatus", "System.Reflection.AssemblyContentType", diff --git a/src/MsgPack.Unity.Full/Serialization/AotHelper.cs b/src/MsgPack.Unity.Full/Serialization/AotHelper.cs index 8bd31ceb7..325e8e77b 100644 --- a/src/MsgPack.Unity.Full/Serialization/AotHelper.cs +++ b/src/MsgPack.Unity.Full/Serialization/AotHelper.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Collections.Generic; using System.Globalization; @@ -28,7 +32,12 @@ namespace MsgPack.Serialization { - internal static partial class AotHelper +#if UNITY && DEBUG + public +#else + internal +#endif + static partial class AotHelper { public static void HandleAotError( Type mayBeGenericArgument, Exception mayBeAotError ) { @@ -95,12 +104,12 @@ public static object CreateSystemCollectionsGenericDictionary( ConstructorInfo c return constructor.InvokePreservingExceptionType( initialCapacity, GetEqualityComparer( keyType ) ); } - internal static IEqualityComparer GetEqualityComparer() + public static IEqualityComparer GetEqualityComparer() { return ( IEqualityComparer ) GetEqualityComparer( typeof( T ) ); } - internal static object GetEqualityComparer( Type type ) + public static object GetEqualityComparer( Type type ) { lock ( EqualityComparerTable ) { @@ -118,7 +127,7 @@ internal static object GetEqualityComparer( Type type ) } } - internal static void PrepareEqualityComparer() + public static void PrepareEqualityComparer() { lock ( EqualityComparerTable ) { diff --git a/src/MsgPack.Unity.Full/Serialization/NonGenericMessagePackSerializer.cs b/src/MsgPack.Unity.Full/Serialization/NonGenericMessagePackSerializer.cs index ed60424b3..112ecef1b 100644 --- a/src/MsgPack.Unity.Full/Serialization/NonGenericMessagePackSerializer.cs +++ b/src/MsgPack.Unity.Full/Serialization/NonGenericMessagePackSerializer.cs @@ -40,9 +40,10 @@ protected Type TargetType /// /// A which owns this serializer. /// The type to be serialized. + /// The capability flags for this instance. /// is null. - protected NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType ) - : this( ownerContext, targetType, null ) { } + protected NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType, SerializerCapabilities capabilities ) + : this( ownerContext, targetType, null, capabilities ) { } /// /// Initializes a new instance of the class with explicitly specified compatibility option. @@ -50,16 +51,16 @@ protected NonGenericMessagePackSerializer( SerializationContext ownerContext, Ty /// A which owns this serializer. /// The type to be serialized. /// The for new packer creation. + /// The capability flags for this instance. /// is null. /// /// This method also supports backword compatibility with 0.4. /// - protected NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType, PackerCompatibilityOptions packerCompatibilityOptions ) - : this( ownerContext, targetType, new PackerCompatibilityOptions?( packerCompatibilityOptions ) ) { } + protected NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType, PackerCompatibilityOptions packerCompatibilityOptions, SerializerCapabilities capabilities ) + : this( ownerContext, targetType, new PackerCompatibilityOptions?( packerCompatibilityOptions ), capabilities ) { } - private NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType, PackerCompatibilityOptions? packerCompatibilityOptions ) -#warning TODO: capabilities from derived class - : base( ownerContext, packerCompatibilityOptions, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) + private NonGenericMessagePackSerializer( SerializationContext ownerContext, Type targetType, PackerCompatibilityOptions? packerCompatibilityOptions, SerializerCapabilities capabilities ) + : base( ownerContext, packerCompatibilityOptions, capabilities ) { this._targetType = targetType; this._isNullable = JudgeNullable( targetType ); diff --git a/src/MsgPack.Unity.Full/Serialization/TypedMessagePackSerializerWrapper`1.cs b/src/MsgPack.Unity.Full/Serialization/TypedMessagePackSerializerWrapper`1.cs index 198c3d718..d408d8e79 100644 --- a/src/MsgPack.Unity.Full/Serialization/TypedMessagePackSerializerWrapper`1.cs +++ b/src/MsgPack.Unity.Full/Serialization/TypedMessagePackSerializerWrapper`1.cs @@ -32,7 +32,7 @@ namespace MsgPack.Serialization { /// - /// Wraps non-generic to avoid AOT issue. + /// Wraps non-generic to avoid AOT issue. /// /// The type to be serialized. internal class TypedMessagePackSerializerWrapper : MessagePackSerializer, ICollectionInstanceFactory @@ -47,6 +47,11 @@ public TypedMessagePackSerializerWrapper( SerializationContext context, MessageP this._underlyingFactory = underlying as ICollectionInstanceFactory; } + internal override SerializerCapabilities InternalGetCapabilities() + { + return this._underlyingSerializer.InternalGetCapabilities(); + } + protected internal override void PackToCore( Packer packer, T objectTree ) { this._underlyingSerializer.PackTo( packer, objectTree ); diff --git a/src/MsgPack.Unity/MsgPack.Unity.csproj b/src/MsgPack.Unity/MsgPack.Unity.csproj index 5ba780291..6312a3916 100644 --- a/src/MsgPack.Unity/MsgPack.Unity.csproj +++ b/src/MsgPack.Unity/MsgPack.Unity.csproj @@ -2,60 +2,32 @@ - Debug - AnyCPU {04774100-60EE-4FD5-ACED-593394DFF7B7} Library - Properties - MsgPack MsgPack v3.5 512 ..\..\ true - - - true - full - false - bin\Debug\ - TRACE;DEBUG;UNITY_IPHONE;AOT - prompt - 4 - bin\Debug\MsgPack.XML + true 3001,3002 - AllRules.ruleset - - pdbonly - true - ..\..\build\MsgPack-CLI\unity\ - TRACE;UNITY_IPHONE;AOT - prompt - 4 - ..\..\build\MsgPack-CLI\unity\MsgPack.XML - 3001,3002 - AllRules.ruleset + + + $(DefineConstants);FEATURE_MPCONTRACT;UNITY_IPHONE;AOT + false - - bin\CodeAnalysis\ - TRACE;UNITY_IPHONE;AOT;CODE_ANALYSIS - ..\..\bin\unity3d\MsgPack.XML - true - 3001,3002 - pdbonly - AnyCPU - prompt - AllRules.ruleset - true + + $(NoWarn),1591 + + + $(SolutionDir)\build\MsgPack-CLI\unity\ + $(SolutionDir)\build\MsgPack-CLI\unity\MsgPack.XML Properties\CommonAssemblyInfo.cs - - Volatile.cs - CorLibOnlyHelper.cs @@ -89,15 +61,33 @@ BufferManager.cs + + ByteArrayPacker.cs + + + ByteArrayUnpacker.cs + + + ByteBufferAllocator.cs + CollectionDebuggerProxy`1.cs CollectionOperation.cs + + CollectionType.cs + DictionaryDebuggerProxy`2.cs + + EncodingExtensions.cs + + + FixedArrayBufferAllocator.cs + Float32Bits.cs @@ -113,23 +103,20 @@ IAsyncUnpackable.cs + + Int32OffsetValue`1.cs + + + Int64OffsetValue`1.cs + InvalidMessagePackStreamException.cs IPackable.cs - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs + + IRootUnpacker.cs IUnpackable.cs @@ -143,6 +130,18 @@ MessageNotSupportedException.cs + + MessagePackByteArrayPacker.cs + + + MessagePackByteArrayPacker.Pack.cs + + + MessagePackByteArrayUnpacker.cs + + + MessagePackByteArrayUnpacker.Unpack.cs + MessagePackCode.cs @@ -179,15 +178,33 @@ MessagePackObjectEqualityComparer.cs + + MessagePackStreamPacker.cs + + + MessagePackStreamPacker.Pack.cs + + + MessagePackStreamUnpacker.cs + + + MessagePackStreamUnpacker.Unpack.cs + MessagePackString.cs MessageTypeException.cs + + MPContract.cs + Packer.cs + + Packer.Factory.cs + Packer.Nullable.cs @@ -209,36 +226,48 @@ PreserveAttribute.cs + + ReadValueResult.cs + + + ReadValueResults.cs + ReflectionAbstractions.cs + + Serialization\Tracer.cs + + + Serialization\BindingOptions.cs + Serialization\CollectionDetailedKind.cs Serialization\CollectionKind.cs - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + + Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\ICollectionInstanceFactory.cs @@ -248,12 +277,12 @@ Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs + + Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs + Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs @@ -371,12 +400,12 @@ Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs + + Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs + Serialization\DefaultSerializers\System_Collections_QueueMessagePackSerializer.cs @@ -401,27 +430,48 @@ Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs + + Serialization\DefaultSerializers\TimestampDateTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializerProvider.cs + Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs + + Serialization\DictionaryKeyTransformers.cs + + + Serialization\DictionarySerializationOptions.cs + Serialization\EmitterFlavor.cs Serialization\EnumMemberSerializationMethod.cs + + Serialization\EnumMessagePackSerializer`1.cs + Serialization\EnumMessagePackSerializerHelpers.cs Serialization\EnumMessagePackSerializerProvider.cs - - Serialization\EnumMessagePackSerializer`1.cs + + Serialization\EnumNameTransformers.cs Serialization\EnumSerializationMethod.cs + + Serialization\EnumSerializationOptions.cs + Serialization\ExtTypeCodeMapping.cs @@ -443,6 +493,9 @@ Serialization\INilImplicationHandlerParameter.cs + + Serialization\KeyNameTransformers.cs + Serialization\LazyDelegatingMessagePackSerializer`1.cs @@ -476,21 +529,27 @@ Serialization\MessagePackSerializer.Factories.cs + + Serialization\MessagePackSerializer`1.cs + Serialization\MessagePackSerializerExtensions.cs Serialization\MessagePackSerializerProvider.cs - - Serialization\MessagePackSerializer`1.cs - Serialization\NilImplication.cs Serialization\NilImplicationHandler`4.cs + + Serialization\NullTextWriter.cs + + + Serialization\PackHelperParameters.cs + Serialization\PackHelpers.cs @@ -506,6 +565,9 @@ Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs + + Serialization\Polymorphic\RuntimeTypeVerifier.cs + Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs @@ -515,6 +577,9 @@ Serialization\Polymorphic\TypeInfoEncoding.cs + + Serialization\PolymorphicTypeVerificationContext.cs + Serialization\PolymorphismSchema.Constructors.cs @@ -533,9 +598,21 @@ Serialization\PolymorphismType.cs + + Serialization\Reflection\GenericTypeExtensions.cs + + + Serialization\Reflection\ReflectionExtensions.cs + + + Serialization\ReflectionExtensions.CollectionTraits.cs + Serialization\ReflectionExtensions.cs + + Serialization\ReflectionExtensions.InvokePreservingExtension.cs + Serialization\ReflectionHelpers.cs @@ -578,15 +655,12 @@ Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - Serialization\ResolveSerializerEventArgs.cs + + Serialization\SerializationCompatibilityLevel.cs + Serialization\SerializationCompatibilityOptions.cs @@ -635,6 +709,9 @@ Serialization\TypeKeyRepository.cs + + Serialization\UnpackHelperParameters.cs + Serialization\UnpackHelpers.cs @@ -647,8 +724,8 @@ SetOperation.cs - - StreamPacker.cs + + SingleArrayBufferAllocator.cs StringEscape.cs @@ -659,6 +736,42 @@ SubtreeUnpacker.Unpacking.cs + + Timestamp.Calculation.cs + + + Timestamp.Comparison.cs + + + Timestamp.Conversion.cs + + + Timestamp.cs + + + Timestamp.ParseExact.cs + + + Timestamp.Properties.cs + + + Timestamp.ToString.cs + + + Timestamp.TryParseExact.cs + + + TimestampParseResult.cs + + + TimestampStringConverter.cs + + + TimestampStringConverter.Parse.cs + + + TimestampStringConverter.ToString.cs + TupleItems.cs @@ -668,9 +781,18 @@ Unpacker.cs + + Unpacker.Leaf.cs + Unpacker.Unpacking.cs + + UnpackerOptions.cs + + + UnpackerValidationLevel.cs + UnpackException.cs @@ -701,8 +823,8 @@ UnpackingStreamReader.cs - - MPContract.cs + + Volatile.cs diff --git a/src/MsgPack.Uwp/MsgPack.Uwp.csproj b/src/MsgPack.Uwp/MsgPack.Uwp.csproj index 5c1e7f491..61b2896aa 100644 --- a/src/MsgPack.Uwp/MsgPack.Uwp.csproj +++ b/src/MsgPack.Uwp/MsgPack.Uwp.csproj @@ -2,105 +2,41 @@ - Debug - AnyCPU {9D65A105-FB03-40DB-9185-8C695B8EE8D6} Library - Properties - MsgPack MsgPack - ja-JP + en-US UAP 10.0.10586.0 10.0.10240.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + true + 2008,3001,3002 - - AnyCPU - true - full - false - bin\Debug\ - TRACE;DEBUG;NETFX_CORE;WINDOWS_UWP;AOT;NETSTANDARD1_3;FEATURE_TAP - prompt - 4 + + + $(DefineConstants);NETFX_CORE;WINDOWS_UWP;AOT;NETSTANDARD1_3;FEATURE_TAP;FEATURE_CONCURRENT;FEATURE_MEMCOPY - - AnyCPU - pdbonly - true - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;AOT;NETSTANDARD1_3;FEATURE_TAP - prompt - 4 + + $(SolutionDir)\bin\uap10\ + $(SolutionDir)\bin\uap10\MsgPack.XML - - x86 - true - bin\x86\Debug\ - TRACE;DEBUG;NETFX_CORE;WINDOWS_UWP;NETSTD_13;AOT - ;2008 - full - x86 - false - prompt + + AnyCPU - - x86 - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;NETSTD_13;AOT - true - ;2008 - pdbonly + x86 false - prompt - - - ARM - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM - false - prompt - - ARM - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly + ARM false - prompt - - - x64 - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - - x64 - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly + x64 false - prompt @@ -128,18 +64,39 @@ Binary.cs + + BufferedStream.cs + BufferManager.cs + + ByteArrayPacker.cs + + + ByteArrayUnpacker.cs + + + ByteBufferAllocator.cs + CollectionDebuggerProxy`1.cs CollectionOperation.cs + + CollectionType.cs + DictionaryDebuggerProxy`2.cs + + EncodingExtensions.cs + + + FixedArrayBufferAllocator.cs + Float32Bits.cs @@ -155,23 +112,20 @@ IAsyncUnpackable.cs + + Int32OffsetValue`1.cs + + + Int64OffsetValue`1.cs + InvalidMessagePackStreamException.cs IPackable.cs - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs + + IRootUnpacker.cs IUnpackable.cs @@ -185,6 +139,18 @@ MessageNotSupportedException.cs + + MessagePackByteArrayPacker.cs + + + MessagePackByteArrayPacker.Pack.cs + + + MessagePackByteArrayUnpacker.cs + + + MessagePackByteArrayUnpacker.Unpack.cs + MessagePackCode.cs @@ -221,15 +187,33 @@ MessagePackObjectEqualityComparer.cs + + MessagePackStreamPacker.cs + + + MessagePackStreamPacker.Pack.cs + + + MessagePackStreamUnpacker.cs + + + MessagePackStreamUnpacker.Unpack.cs + MessagePackString.cs MessageTypeException.cs + + NetStandardCompatibility.cs + Packer.cs + + Packer.Factory.cs + Packer.Nullable.cs @@ -251,36 +235,45 @@ PreserveAttribute.cs + + ReadValueResult.cs + + + ReadValueResults.cs + ReflectionAbstractions.cs + + Serialization\BindingOptions.cs + Serialization\CollectionDetailedKind.cs Serialization\CollectionKind.cs - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + + Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs + + Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs + Serialization\CollectionSerializers\ICollectionInstanceFactory.cs @@ -290,12 +283,12 @@ Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs + + Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs + Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs @@ -383,6 +376,12 @@ Serialization\DefaultSerializers\FileTimeMessagePackSerializerProvider.cs + + Serialization\DefaultSerializers\FSharpCollectionSerializer`2.cs + + + Serialization\DefaultSerializers\FSharpMapSerializer`3.cs + Serialization\DefaultSerializers\GenericSerializer.cs @@ -443,12 +442,12 @@ Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs + + Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs + Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs @@ -488,30 +487,54 @@ Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs + + Serialization\DefaultSerializers\TimestampDateTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampFileTimeMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializer.cs + + + Serialization\DefaultSerializers\TimestampMessagePackSerializerProvider.cs + Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs Serialization\DefaultSerializers\UnixEpocFileTimeMessagePackSerializer.cs + + Serialization\DictionaryKeyTransformers.cs + + + Serialization\DictionarySerializationOptions.cs + Serialization\EmitterFlavor.cs Serialization\EnumMemberSerializationMethod.cs + + Serialization\EnumMessagePackSerializer`1.cs + Serialization\EnumMessagePackSerializerHelpers.cs Serialization\EnumMessagePackSerializerProvider.cs - - Serialization\EnumMessagePackSerializer`1.cs + + Serialization\EnumNameTransformers.cs Serialization\EnumSerializationMethod.cs + + Serialization\EnumSerializationOptions.cs + Serialization\ExtTypeCodeMapping.cs @@ -533,6 +556,9 @@ Serialization\INilImplicationHandlerParameter.cs + + Serialization\KeyNameTransformers.cs + Serialization\LazyDelegatingMessagePackSerializer`1.cs @@ -566,21 +592,27 @@ Serialization\MessagePackSerializer.Factories.cs + + Serialization\MessagePackSerializer`1.cs + Serialization\MessagePackSerializerExtensions.cs Serialization\MessagePackSerializerProvider.cs - - Serialization\MessagePackSerializer`1.cs - Serialization\NilImplication.cs Serialization\NilImplicationHandler`4.cs + + Serialization\NullTextWriter.cs + + + Serialization\PackHelperParameters.cs + Serialization\PackHelpers.cs @@ -596,6 +628,9 @@ Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs + + Serialization\Polymorphic\RuntimeTypeVerifier.cs + Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs @@ -605,6 +640,9 @@ Serialization\Polymorphic\TypeInfoEncoding.cs + + Serialization\PolymorphicTypeVerificationContext.cs + Serialization\PolymorphismSchema.Constructors.cs @@ -623,9 +661,21 @@ Serialization\PolymorphismType.cs + + Serialization\Reflection\GenericTypeExtensions.cs + + + Serialization\Reflection\ReflectionExtensions.cs + + + Serialization\ReflectionExtensions.CollectionTraits.cs + Serialization\ReflectionExtensions.cs + + Serialization\ReflectionExtensions.InvokePreservingExtension.cs + Serialization\ReflectionHelpers.cs @@ -671,15 +721,12 @@ Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - Serialization\ResolveSerializerEventArgs.cs + + Serialization\SerializationCompatibilityLevel.cs + Serialization\SerializationCompatibilityOptions.cs @@ -728,6 +775,9 @@ Serialization\TypeKeyRepository.cs + + Serialization\UnpackHelperParameters.cs + Serialization\UnpackHelpers.cs @@ -740,8 +790,8 @@ SetOperation.cs - - StreamPacker.cs + + SingleArrayBufferAllocator.cs StringEscape.cs @@ -752,6 +802,45 @@ SubtreeUnpacker.Unpacking.cs + + TaskAugument.cs + + + Timestamp.Calculation.cs + + + Timestamp.Comparison.cs + + + Timestamp.Conversion.cs + + + Timestamp.cs + + + Timestamp.ParseExact.cs + + + Timestamp.Properties.cs + + + Timestamp.ToString.cs + + + Timestamp.TryParseExact.cs + + + TimestampParseResult.cs + + + TimestampStringConverter.cs + + + TimestampStringConverter.Parse.cs + + + TimestampStringConverter.ToString.cs + TupleItems.cs @@ -761,9 +850,18 @@ Unpacker.cs + + Unpacker.Leaf.cs + Unpacker.Unpacking.cs + + UnpackerOptions.cs + + + UnpackerValidationLevel.cs + UnpackException.cs @@ -794,12 +892,6 @@ UnpackingStreamReader.cs - - BufferedStream.cs - - - NetStandardCompatibility.cs - @@ -818,6 +910,7 @@ false prompt MinimumRecommendedRules.ruleset + true bin\x86\CodeAnalysis\ diff --git a/src/MsgPack.Uwp/project.json b/src/MsgPack.Uwp/project.json index 1489870f0..56b464697 100644 --- a/src/MsgPack.Uwp/project.json +++ b/src/MsgPack.Uwp/project.json @@ -50,7 +50,15 @@ "../MsgPack/Serialization/Tracer.cs" ], "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0" + "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.3", + "System.Collections.NonGeneric": "4.3.0", + "System.Collections.Specialized": "4.3.0", + "System.Diagnostics.Contracts": "4.3.0", + "System.Net.NameResolution": "4.3.0", + "System.Net.Primitives": "4.3.0", + "System.Runtime.WindowsRuntime" : "4.3.0", + "System.Threading.Overlapped": "4.3.0", + "Microsoft.Win32.Primitives": "4.3.0" }, "frameworks": { "uap10.0": {} diff --git a/src/MsgPack.WinRT.Portable/MsgPack.WinRT.Portable.csproj b/src/MsgPack.WinRT.Portable/MsgPack.WinRT.Portable.csproj deleted file mode 100644 index 9b5d51ac2..000000000 --- a/src/MsgPack.WinRT.Portable/MsgPack.WinRT.Portable.csproj +++ /dev/null @@ -1,923 +0,0 @@ - - - - - 11.0 - Debug - AnyCPU - {E2817364-F217-465F-BE3B-A5F85E2F8667} - Library - Properties - MsgPack - MsgPack - ja-JP - 512 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Profile111 - v4.5 - - - true - full - false - bin\Debug\ - TRACE;DEBUG;NETFX_CORE;FEATURE_TAP - prompt - 4 - - - pdbonly - true - ..\..\bin\portable-net45+win+wpa81\ - TRACE;NETFX_CORE;FEATURE_TAP - prompt - 4 - ..\..\bin\portable-net45+win+wpa81\MsgPack.XML - false - - - true - - - ..\MsgPack.snk - - - bin\CodeAnalysis\ - TRACE;NETFX_CORE;CODE_ANALYSIS;FEATURE_TAP - ..\..\bin\portable-windows8+wpa\MsgPack.XML - true - pdbonly - AnyCPU - prompt - AllRules.ruleset - - - - - MsgPack.snk - - - remarks.xml - - - - - Properties\CommonAssemblyInfo.cs - - - AsyncReadResult.cs - - - AsyncReadResult`1.cs - - - BigEndianBinary.cs - - - Binary.cs - - - BufferManager.cs - - - BufferPool.cs - - - CollectionDebuggerProxy`1.cs - - - CollectionOperation.cs - - - DictionaryDebuggerProxy`2.cs - - - Float32Bits.cs - - - Float64Bits.cs - - - GlobalSuppressions.cs - - - IAsyncPackable.cs - - - IAsyncUnpackable.cs - - - InvalidMessagePackStreamException.cs - - - IPackable.cs - - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs - - - IUnpackable.cs - - - KnownExtTypeCode.cs - - - KnownExtTypeName.cs - - - MessageNotSupportedException.cs - - - MessagePackCode.cs - - - MessagePackConvert.cs - - - MessagePackExtendedTypeObject.cs - - - MessagePackObject.cs - - - MessagePackObject.Utilities.cs - - - MessagePackObjectDictionary.cs - - - MessagePackObjectDictionary.Enumerator.cs - - - MessagePackObjectDictionary.KeySet.cs - - - MessagePackObjectDictionary.KeySet.Enumerator.cs - - - MessagePackObjectDictionary.ValueCollection.cs - - - MessagePackObjectDictionary.ValueCollection.Enumerator.cs - - - MessagePackObjectEqualityComparer.cs - - - MessagePackString.cs - - - MessageTypeException.cs - - - Packer.cs - - - Packer.Nullable.cs - - - Packer.Packing.cs - - - PackerCompatibilityOptions.cs - - - PackerUnpackerExtensions.cs - - - PackerUnpackerStreamOptions.cs - - - PackingOptions.cs - - - ReflectionAbstractions.cs - - - Serialization\AbstractSerializers\ActionType.cs - - - Serialization\AbstractSerializers\CachedDelegateInfo.cs - - - Serialization\AbstractSerializers\ConstructorDefinition.cs - - - Serialization\AbstractSerializers\DynamicUnpackingContext.cs - - - Serialization\AbstractSerializers\EnumSerializerMethod.cs - - - Serialization\AbstractSerializers\FieldDefinition.cs - - - Serialization\AbstractSerializers\FieldName.cs - - - Serialization\AbstractSerializers\ICodeConstruct.cs - - - Serialization\AbstractSerializers\ISerializerBuilder.cs - - - Serialization\AbstractSerializers\MethodDefinition.cs - - - Serialization\AbstractSerializers\MethodName.cs - - - Serialization\AbstractSerializers\MethodNamePrefix.cs - - - Serialization\AbstractSerializers\SerializerBuilderHelper.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Collection.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.CommonConstructs.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Enum.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Nullable.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Object.cs - - - Serialization\AbstractSerializers\SerializerBuilder`2.Tuple.cs - - - Serialization\AbstractSerializers\SerializerGenerationContext.cs - - - Serialization\AbstractSerializers\TypeDefinition.cs - - - Serialization\CollectionDetailedKind.cs - - - Serialization\CollectionKind.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ICollectionInstanceFactory.cs - - - Serialization\CollectionSerializers\NonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\ReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionTraits.cs - - - Serialization\DataMemberContract.cs - - - Serialization\DateTimeConversionMethod.cs - - - Serialization\DateTimeMemberConversionMethod.cs - - - Serialization\DateTimeMessagePackSerializerHelpers.cs - - - Serialization\DefaultConcreteTypeRepository.cs - - - Serialization\DefaultSerializers\AbstractCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractCollectionSerializerHelper.cs - - - Serialization\DefaultSerializers\AbstractDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\AbstractEnumerableMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractNonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericListMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\ArraySegmentMessageSerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.Primitives.cs - - - Serialization\DefaultSerializers\ArraySerializer`1.cs - - - Serialization\DefaultSerializers\DateTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializer.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DefaultSerializers.cs - - - Serialization\DefaultSerializers\FileTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\GenericSerializer.cs - - - Serialization\DefaultSerializers\ImmutableCollectionSerializer`2.cs - - - Serialization\DefaultSerializers\ImmutableDictionarySerializer`3.cs - - - Serialization\DefaultSerializers\ImmutableStackSerializer`2.cs - - - Serialization\DefaultSerializers\InternalDateTimeExtensions.cs - - - Serialization\DefaultSerializers\MessagePackObjectExtensions.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MultidimensionalArraySerializer`1.cs - - - Serialization\DefaultSerializers\NativeDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NativeFileTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NullableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ArraySegment_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ByteArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_CharArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_DictionaryEntryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Stack_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Globalization_CultureInfoMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Numerics_ComplexMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_ObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_StringMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Text_StringBuilderMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_UriMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocFileTimeMessagePackSerializer.cs - - - Serialization\EmitterFlavor.cs - - - Serialization\EnumMemberSerializationMethod.cs - - - Serialization\EnumMessagePackSerializerHelpers.cs - - - Serialization\EnumMessagePackSerializerProvider.cs - - - Serialization\EnumMessagePackSerializer`1.cs - - - Serialization\EnumSerializationMethod.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackCollectionMessagePackSerializer`2.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackDictionaryMessagePackSerializer`3.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackEnumerableMessagePackSerializer`2.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackEnumMessagePackSerializer`1.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackMessagePackSerializer`1.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackNonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackNonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackNonGenericListMessagePackSerializer`1.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\ExpressionSerializers\ExpressionCallbackReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\ExpressionSerializers\ExpressionConstruct.cs - - - Serialization\ExpressionSerializers\ExpressionDumper.cs - - - Serialization\ExpressionSerializers\ExpressionTreeContext.cs - - - Serialization\ExpressionSerializers\ExpressionTreeSerializerBuilder.cs - - - Serialization\ExpressionSerializers\ExpressionTreeSerializerBuilderHelpers.cs - - - Serialization\ExtTypeCodeMapping.cs - - - Serialization\FromExpression.cs - - - Serialization\FromExpression.ToMethod.cs - - - Serialization\ICustomizableEnumSerializer.cs - - - Serialization\IMessagePackSerializer.cs - - - Serialization\IMessagePackSingleObjectSerializer.cs - - - Serialization\INilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\INilImplicationHandlerParameter.cs - - - Serialization\ISupportMessagePackSerializerCapability.cs - - - Serialization\LazyDelegatingMessagePackSerializer`1.cs - - - Serialization\MessagePackDateTimeMemberAttribute.cs - - - Serialization\MessagePackDeserializationConstructorAttribute.cs - - - Serialization\MessagePackEnumAttribute.cs - - - Serialization\MessagePackEnumMemberAttribute.cs - - - Serialization\MessagePackIgnoreAttribute.cs - - - Serialization\MessagePackKnownTypeAttributes.cs - - - Serialization\MessagePackMemberAttribute.cs - - - Serialization\MessagePackRuntimeTypeAttributes.cs - - - Serialization\MessagePackSerializer.cs - - - Serialization\MessagePackSerializer.Factories.cs - - - Serialization\MessagePackSerializerExtensions.cs - - - Serialization\MessagePackSerializerProvider.cs - - - Serialization\MessagePackSerializer`1.cs - - - Serialization\Metadata\_CultureInfo.cs - - - Serialization\Metadata\_DateTimeMessagePackSerializerHelpers.cs - - - Serialization\Metadata\_Decimal.cs - - - Serialization\Metadata\_Delegate.cs - - - Serialization\Metadata\_DictionaryEntry.cs - - - Serialization\Metadata\_DynamicUnpackingContext.cs - - - Serialization\Metadata\_EnumMessagePackSerializerHelpers.cs - - - Serialization\Metadata\_FieldInfo.cs - - - Serialization\Metadata\_IDictionaryEnumerator.cs - - - Serialization\Metadata\_IEnumreator.cs - - - Serialization\Metadata\_MessagePackObject.cs - - - Serialization\Metadata\_MessagePackSerializer.cs - - - Serialization\Metadata\_MethodBase.cs - - - Serialization\Metadata\_MethodInfo.cs - - - Serialization\Metadata\_Object.cs - - - Serialization\Metadata\_Packer.cs - - - Serialization\Metadata\_SerializationContext.cs - - - Serialization\Metadata\_String.cs - - - Serialization\Metadata\_Type.cs - - - Serialization\Metadata\_Unpacker.cs - - - Serialization\Metadata\_UnpackHelpers.cs - - - Serialization\Metadata\_UnpackHelpers.direct.cs - - - Serialization\NilImplication.cs - - - Serialization\NilImplicationHandler`4.cs - - - Serialization\PackHelpers.cs - - - Serialization\Polymorphic\IPolymorphicDeserializer.cs - - - Serialization\Polymorphic\IPolymorphicHelperAttributes.cs - - - Serialization\Polymorphic\KnownTypePolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs - - - Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\TypeInfoEncoder.cs - - - Serialization\Polymorphic\TypeInfoEncoding.cs - - - Serialization\PolymorphismSchema.Constructors.cs - - - Serialization\PolymorphismSchema.cs - - - Serialization\PolymorphismSchema.Internals.cs - - - Serialization\PolymorphismSchemaChildrenType.cs - - - Serialization\PolymorphismTarget.cs - - - Serialization\PolymorphismType.cs - - - Serialization\ReflectionExtensions.cs - - - Serialization\ReflectionSerializers\ReflectionCollectionMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionDictionaryMessagePackSerializer`3.cs - - - Serialization\ReflectionSerializers\ReflectionEnumerableMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionEnumMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNilImplicationHandler.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricCollectionMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericListMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionObjectMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerHelper.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - - Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - - - Serialization\ResolveSerializerEventArgs.cs - - - Serialization\SerializationCompatibilityOptions.cs - - - Serialization\SerializationContext.cs - - - Serialization\SerializationContext.ExtTypeCodes.cs - - - Serialization\SerializationExceptions.cs - - - Serialization\SerializationMethod.cs - - - Serialization\SerializationMethodGeneratorOption.cs - - - Serialization\SerializationTarget.cs - - - Serialization\SerializerCapabilities.cs - - - Serialization\SerializerDebugging.cs - - - Serialization\SerializerOptions.cs - - - Serialization\SerializerRegistrationOptions.cs - - - Serialization\SerializerRepository.cs - - - Serialization\SerializerRepository.defaults.cs - - - Serialization\SerializerTypeKeyRepository.cs - - - Serialization\SerializingMember.cs - - - Serialization\TypeKeyRepository.cs - - - Serialization\UnpackHelpers.cs - - - Serialization\UnpackHelpers.direct.cs - - - Serialization\UnpackHelpers.facade.cs - - - SetOperation.cs - - - StreamPacker.cs - - - StringEscape.cs - - - SubtreeUnpacker.cs - - - SubtreeUnpacker.Unpacking.cs - - - TupleItems.cs - - - UnassignedMessageTypeException.cs - - - Unpacker.cs - - - Unpacker.Unpacking.cs - - - UnpackException.cs - - - Unpacking.cs - - - Unpacking.Numerics.cs - - - Unpacking.Others.cs - - - Unpacking.Streaming.cs - - - Unpacking.String.cs - - - UnpackingMode.cs - - - UnpackingResult.cs - - - UnpackingStream.cs - - - UnpackingStreamReader.cs - - - - - - - - - \ No newline at end of file diff --git a/src/MsgPack.WinRT.Portable/Properties/AssemblyInfo.cs b/src/MsgPack.WinRT.Portable/Properties/AssemblyInfo.cs deleted file mode 100644 index 68d95553d..000000000 --- a/src/MsgPack.WinRT.Portable/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Security; - -[assembly: AssemblyTitle( "MessagePack for WinRT Universal Apps" )] -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library for Windows Runtime Universal Apps." )] - -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] - -#if DEBUG || PERFORMANCE_TEST -[assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - - diff --git a/src/MsgPack.WinRT.Portable/Serialization/.directory b/src/MsgPack.WinRT.Portable/Serialization/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/AbstractSerializers/.directory b/src/MsgPack.WinRT.Portable/Serialization/AbstractSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/CodeDomSerializers/.directory b/src/MsgPack.WinRT.Portable/Serialization/CodeDomSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/DefaultSerializers/.directory b/src/MsgPack.WinRT.Portable/Serialization/DefaultSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/ExpressionSerializers/.directory b/src/MsgPack.WinRT.Portable/Serialization/ExpressionSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/Metadata/.directory b/src/MsgPack.WinRT.Portable/Serialization/Metadata/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/Reflection/.directory b/src/MsgPack.WinRT.Portable/Serialization/Reflection/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.WinRT.Portable/Serialization/Reflection/ReflectionHelpers.cs b/src/MsgPack.WinRT.Portable/Serialization/Reflection/ReflectionHelpers.cs deleted file mode 100644 index 503b63de0..000000000 --- a/src/MsgPack.WinRT.Portable/Serialization/Reflection/ReflectionHelpers.cs +++ /dev/null @@ -1,103 +0,0 @@ -#region -- License Terms -- -// -// NLiblet -// -// Copyright (C) 2015 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System; -using System.ComponentModel; -using System.Linq; -using System.Reflection; - -namespace MsgPack.Serialization.Reflection -{ - /// - /// This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - /// Defines serialization helper APIs. - /// - [EditorBrowsable( EditorBrowsableState.Never )] - public static class ReflectionHelpers - { - internal static readonly MethodInfo GetRuntimeMethodMethod = - FromExpression.ToMethod( - ( Type source, string name, Type[] parameterTypes ) => GetRuntimeMethod( source, name, parameterTypes ) - ); - - /// - /// Gets a specific method even if the candidate is not public. - /// - /// The target type. - /// The name of the method. - /// The types of the parameter. - /// A if found; otherwise, null. - /// is null. - /// is empty. - [EditorBrowsable( EditorBrowsableState.Never )] - public static MethodInfo GetRuntimeMethod( this Type source, string name, params Type[] parameterTypes ) - { - if ( name == null ) - { - throw new ArgumentNullException( "name" ); - } - - if ( name.Length == 0 ) - { - throw new ArgumentException( "'name' cannot be empty.", "name" ); - } - - var safeParameterTypes = parameterTypes ?? ReflectionAbstractions.EmptyTypes; - - return - source.GetRuntimeMethods() - .SingleOrDefault( - m => m.Name == name && m.GetParameters().Select( p => p.ParameterType ).SequenceEqual( safeParameterTypes ) - ); - } - internal static readonly MethodInfo GetRuntimeFieldMethod = - FromExpression.ToMethod( - ( Type source, string name ) => GetRuntimeField( source, name ) - ); - - /// - /// Gets a specific field even if the candidate is not public. - /// - /// The target type. - /// The name of the method. - /// A if found; otherwise, null. - /// is null. - /// is empty. - [EditorBrowsable( EditorBrowsableState.Never )] - public static FieldInfo GetRuntimeField( this Type source, string name ) - { - if ( name == null ) - { - throw new ArgumentNullException( "name" ); - } - - if ( name.Length == 0 ) - { - throw new ArgumentException( "'name' cannot be empty.", "name" ); - } - - return - source.GetRuntimeFields() - .SingleOrDefault( - m => m.Name == name - ); - } - } -} diff --git a/src/MsgPack.WinRT.Portable/Serialization/ReflectionSerializers/.directory b/src/MsgPack.WinRT.Portable/Serialization/ReflectionSerializers/.directory deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Xamarin.Android/MsgPack.Xamarin.Android.csproj b/src/MsgPack.Xamarin.Android/MsgPack.Xamarin.Android.csproj deleted file mode 100644 index faa896d1b..000000000 --- a/src/MsgPack.Xamarin.Android/MsgPack.Xamarin.Android.csproj +++ /dev/null @@ -1,729 +0,0 @@ - - - - Debug - AnyCPU - {A6210C9C-1614-46C5-97B2-6A37032AF143} - {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - MsgPack - Resources\Resource.designer.cs - Resource - Resources - Assets - False - MsgPack - true - ..\MsgPack.snk - v2.3 - - - true - full - false - bin\Debug - DEBUG;__MOBILE__;__ANDROID__;AOT;XAMARIN;FEATURE_TAP - prompt - 4 - None - false - bin\Debug\MsgPack.xml - - - true - ..\..\bin\MonoAndroid10\ - __MOBILE__;__ANDROID__;AOT;XAMARIN;FEATURE_TAP - prompt - 4 - false - false - ..\..\bin\MonoAndroid10\MsgPack.xml - - - - - - - - - - - Properties\CommonAssemblyInfo.cs - - - AsyncReadResult.cs - - - AsyncReadResult`1.cs - - - BigEndianBinary.cs - - - Binary.cs - - - BufferManager.cs - - - CollectionDebuggerProxy`1.cs - - - CollectionOperation.cs - - - DictionaryDebuggerProxy`2.cs - - - Float32Bits.cs - - - Float64Bits.cs - - - GlobalSuppressions.cs - - - IAsyncPackable.cs - - - IAsyncUnpackable.cs - - - InvalidMessagePackStreamException.cs - - - IPackable.cs - - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs - - - IUnpackable.cs - - - KnownExtTypeCode.cs - - - KnownExtTypeName.cs - - - MessageNotSupportedException.cs - - - MessagePackCode.cs - - - MessagePackConvert.cs - - - MessagePackExtendedTypeObject.cs - - - MessagePackObject.cs - - - MessagePackObject.Utilities.cs - - - MessagePackObjectDictionary.cs - - - MessagePackObjectDictionary.Enumerator.cs - - - MessagePackObjectDictionary.KeySet.cs - - - MessagePackObjectDictionary.KeySet.Enumerator.cs - - - MessagePackObjectDictionary.ValueCollection.cs - - - MessagePackObjectDictionary.ValueCollection.Enumerator.cs - - - MessagePackObjectEqualityComparer.cs - - - MessagePackString.cs - - - MessageTypeException.cs - - - Packer.cs - - - Packer.Nullable.cs - - - Packer.Packing.cs - - - PackerCompatibilityOptions.cs - - - PackerUnpackerExtensions.cs - - - PackerUnpackerStreamOptions.cs - - - PackingOptions.cs - - - PreserveAttribute.cs - - - ReflectionAbstractions.cs - - - Serialization\CollectionDetailedKind.cs - - - Serialization\CollectionKind.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ICollectionInstanceFactory.cs - - - Serialization\CollectionSerializers\NonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\ReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionTraitOptions.cs - - - Serialization\CollectionTraits.cs - - - Serialization\DataMemberContract.cs - - - Serialization\DateTimeConversionMethod.cs - - - Serialization\DateTimeMemberConversionMethod.cs - - - Serialization\DateTimeMessagePackSerializerHelpers.cs - - - Serialization\DefaultConcreteTypeRepository.cs - - - Serialization\DefaultSerializers\AbstractCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractCollectionSerializerHelper.cs - - - Serialization\DefaultSerializers\AbstractDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\AbstractEnumerableMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractNonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericListMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\ArraySegmentMessageSerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.Primitives.cs - - - Serialization\DefaultSerializers\ArraySerializer`1.cs - - - Serialization\DefaultSerializers\DateTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializer.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DefaultSerializers.cs - - - Serialization\DefaultSerializers\GenericSerializer.cs - - - Serialization\DefaultSerializers\ImmutableCollectionSerializer`2.cs - - - Serialization\DefaultSerializers\ImmutableDictionarySerializer`3.cs - - - Serialization\DefaultSerializers\ImmutableStackSerializer`2.cs - - - Serialization\DefaultSerializers\InternalDateTimeExtensions.cs - - - Serialization\DefaultSerializers\MessagePackObjectExtensions.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MultidimensionalArraySerializer`1.cs - - - Serialization\DefaultSerializers\NativeDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NullableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ArraySegment_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ByteArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_CharArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_DictionaryEntryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Stack_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_QueueMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_StackMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_DBNullMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Globalization_CultureInfoMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Numerics_ComplexMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_ObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_StringMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Text_StringBuilderMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_UriMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs - - - Serialization\EmitterFlavor.cs - - - Serialization\EnumMemberSerializationMethod.cs - - - Serialization\EnumMessagePackSerializerHelpers.cs - - - Serialization\EnumMessagePackSerializerProvider.cs - - - Serialization\EnumMessagePackSerializer`1.cs - - - Serialization\EnumSerializationMethod.cs - - - Serialization\ExtTypeCodeMapping.cs - - - Serialization\ICustomizableEnumSerializer.cs - - - Serialization\IdentifierUtility.cs - - - Serialization\IMessagePackSerializer.cs - - - Serialization\IMessagePackSingleObjectSerializer.cs - - - Serialization\INilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\INilImplicationHandlerParameter.cs - - - Serialization\LazyDelegatingMessagePackSerializer`1.cs - - - Serialization\MessagePackDateTimeMemberAttribute.cs - - - Serialization\MessagePackDeserializationConstructorAttribute.cs - - - Serialization\MessagePackEnumAttribute.cs - - - Serialization\MessagePackEnumMemberAttribute.cs - - - Serialization\MessagePackIgnoreAttribute.cs - - - Serialization\MessagePackKnownTypeAttributes.cs - - - Serialization\MessagePackMemberAttribute.cs - - - Serialization\MessagePackRuntimeTypeAttributes.cs - - - Serialization\MessagePackSerializer.cs - - - Serialization\MessagePackSerializer.Factories.cs - - - Serialization\MessagePackSerializerExtensions.cs - - - Serialization\MessagePackSerializerProvider.cs - - - Serialization\MessagePackSerializer`1.cs - - - Serialization\NilImplication.cs - - - Serialization\NilImplicationHandler`4.cs - - - Serialization\PackHelpers.cs - - - Serialization\Polymorphic\IPolymorphicDeserializer.cs - - - Serialization\Polymorphic\IPolymorphicHelperAttributes.cs - - - Serialization\Polymorphic\KnownTypePolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs - - - Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\TypeInfoEncoder.cs - - - Serialization\Polymorphic\TypeInfoEncoding.cs - - - Serialization\PolymorphismSchema.Constructors.cs - - - Serialization\PolymorphismSchema.cs - - - Serialization\PolymorphismSchema.Internals.cs - - - Serialization\PolymorphismSchemaChildrenType.cs - - - Serialization\PolymorphismTarget.cs - - - Serialization\PolymorphismType.cs - - - Serialization\ReflectionExtensions.cs - - - Serialization\ReflectionHelpers.cs - - - Serialization\ReflectionSerializers\ReflectionCollectionMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionDictionaryMessagePackSerializer`3.cs - - - Serialization\ReflectionSerializers\ReflectionEnumerableMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionEnumMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNilImplicationHandler.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricCollectionMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericListMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionObjectMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerHelper.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - - Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - - - Serialization\ResolveSerializerEventArgs.cs - - - Serialization\SerializationCompatibilityOptions.cs - - - Serialization\SerializationContext.cs - - - Serialization\SerializationContext.ExtTypeCodes.cs - - - Serialization\SerializationExceptions.cs - - - Serialization\SerializationMethod.cs - - - Serialization\SerializationMethodGeneratorOption.cs - - - Serialization\SerializationTarget.cs - - - Serialization\SerializerCapabilities.cs - - - Serialization\SerializerDebugging.cs - - - Serialization\SerializerOptions.cs - - - Serialization\SerializerRegistrationOptions.cs - - - Serialization\SerializerRepository.cs - - - Serialization\SerializerRepository.defaults.cs - - - Serialization\SerializerTypeKeyRepository.cs - - - Serialization\SerializingMember.cs - - - Serialization\TypeKeyRepository.cs - - - Serialization\UnpackHelpers.cs - - - Serialization\UnpackHelpers.direct.cs - - - Serialization\UnpackHelpers.facade.cs - - - SetOperation.cs - - - StreamPacker.cs - - - StringEscape.cs - - - SubtreeUnpacker.cs - - - SubtreeUnpacker.Unpacking.cs - - - TupleItems.cs - - - UnassignedMessageTypeException.cs - - - Unpacker.cs - - - Unpacker.Unpacking.cs - - - UnpackException.cs - - - Unpacking.cs - - - Unpacking.Numerics.cs - - - Unpacking.Others.cs - - - Unpacking.Streaming.cs - - - Unpacking.String.cs - - - UnpackingMode.cs - - - UnpackingResult.cs - - - UnpackingStream.cs - - - UnpackingStreamReader.cs - - - UnsafeNativeMethods.cs - - - - - - remarks.xml - - - \ No newline at end of file diff --git a/src/MsgPack.Xamarin.Android/Properties/AssemblyInfo.cs b/src/MsgPack.Xamarin.Android/Properties/AssemblyInfo.cs deleted file mode 100644 index d56404773..000000000 --- a/src/MsgPack.Xamarin.Android/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Security; - -[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )] -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library for Xamarin.Android." )] - -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] - -[assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )] -[assembly: AllowPartiallyTrustedCallers] - -#if DEBUG || PERFORMANCE_TEST -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -[assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - - diff --git a/src/MsgPack.Xamarin.Android/Resources/Resource.designer.cs b/src/MsgPack.Xamarin.Android/Resources/Resource.designer.cs deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/MsgPack.Xamarin.iOS/MsgPack.Xamarin.iOS.csproj b/src/MsgPack.Xamarin.iOS/MsgPack.Xamarin.iOS.csproj deleted file mode 100644 index 0eb7b6eb6..000000000 --- a/src/MsgPack.Xamarin.iOS/MsgPack.Xamarin.iOS.csproj +++ /dev/null @@ -1,726 +0,0 @@ - - - - Debug - AnyCPU - {346B55F0-94FA-4B90-9C11-06031043B685} - {6BC8ED88-2882-458C-8E55-DFD12B67127B};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - MsgPack - Resources - MsgPack - true - ..\MsgPack.snk - - - true - full - false - bin\Debug - DEBUG;__MOBILE__;__IOS__;__MOBILE__;__IOS__;__MOBILE__;__IOS__;AOT;XAMARIN;FEATURE_TAP; - prompt - 4 - false - bin\Debug\MsgPack.xml - - - true - ..\..\bin\MonoTouch10\ - prompt - 4 - false - __MOBILE__;__IOS__;__MOBILE__;__IOS__;__MOBILE__;__IOS__;AOT;NETSTANDARD1_3;XAMARIN;FEATURE_TAP; - ..\..\bin\MonoTouch10\MsgPack.xml - - - - - - - - - - - - - - - Properties\CommonAssemblyInfo.cs - - - AsyncReadResult.cs - - - AsyncReadResult`1.cs - - - BigEndianBinary.cs - - - Binary.cs - - - BufferManager.cs - - - CollectionDebuggerProxy`1.cs - - - CollectionOperation.cs - - - DictionaryDebuggerProxy`2.cs - - - Float32Bits.cs - - - Float64Bits.cs - - - GlobalSuppressions.cs - - - IAsyncPackable.cs - - - IAsyncUnpackable.cs - - - InvalidMessagePackStreamException.cs - - - IPackable.cs - - - ItemsUnpacker.cs - - - ItemsUnpacker.Read.cs - - - ItemsUnpacker.Skipping.cs - - - ItemsUnpacker.Unpacking.cs - - - IUnpackable.cs - - - KnownExtTypeCode.cs - - - KnownExtTypeName.cs - - - MessageNotSupportedException.cs - - - MessagePackCode.cs - - - MessagePackConvert.cs - - - MessagePackExtendedTypeObject.cs - - - MessagePackObject.cs - - - MessagePackObject.Utilities.cs - - - MessagePackObjectDictionary.cs - - - MessagePackObjectDictionary.Enumerator.cs - - - MessagePackObjectDictionary.KeySet.cs - - - MessagePackObjectDictionary.KeySet.Enumerator.cs - - - MessagePackObjectDictionary.ValueCollection.cs - - - MessagePackObjectDictionary.ValueCollection.Enumerator.cs - - - MessagePackObjectEqualityComparer.cs - - - MessagePackString.cs - - - MessageTypeException.cs - - - Packer.cs - - - Packer.Nullable.cs - - - Packer.Packing.cs - - - PackerCompatibilityOptions.cs - - - PackerUnpackerExtensions.cs - - - PackerUnpackerStreamOptions.cs - - - PackingOptions.cs - - - PreserveAttribute.cs - - - ReflectionAbstractions.cs - - - Serialization\CollectionDetailedKind.cs - - - Serialization\CollectionKind.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\CollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\CollectionSerializerHelpers.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializerBase`3.cs - - - Serialization\CollectionSerializers\DictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializerBase`2.cs - - - Serialization\CollectionSerializers\EnumerableMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ICollectionInstanceFactory.cs - - - Serialization\CollectionSerializers\NonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializerBase`1.cs - - - Serialization\CollectionSerializers\NonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\NonGenericListMessagePackSerializer`1.cs - - - Serialization\CollectionSerializers\ReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\CollectionSerializers\ReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\CollectionTraitOptions.cs - - - Serialization\CollectionTraits.cs - - - Serialization\DataMemberContract.cs - - - Serialization\DateTimeConversionMethod.cs - - - Serialization\DateTimeMemberConversionMethod.cs - - - Serialization\DateTimeMessagePackSerializerHelpers.cs - - - Serialization\DefaultConcreteTypeRepository.cs - - - Serialization\DefaultSerializers\AbstractCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractCollectionSerializerHelper.cs - - - Serialization\DefaultSerializers\AbstractDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\AbstractEnumerableMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractNonGenericCollectionMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericEnumerableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractNonGenericListMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyCollectionMessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\AbstractReadOnlyDictionaryMessagePackSerializer`3.cs - - - Serialization\DefaultSerializers\ArraySegmentMessageSerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.cs - - - Serialization\DefaultSerializers\ArraySerializer.Primitives.cs - - - Serialization\DefaultSerializers\ArraySerializer`1.cs - - - Serialization\DefaultSerializers\DateTimeMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializer.cs - - - Serialization\DefaultSerializers\DateTimeOffsetMessagePackSerializerProvider.cs - - - Serialization\DefaultSerializers\DefaultSerializers.cs - - - Serialization\DefaultSerializers\GenericSerializer.cs - - - Serialization\DefaultSerializers\ImmutableCollectionSerializer`2.cs - - - Serialization\DefaultSerializers\ImmutableDictionarySerializer`3.cs - - - Serialization\DefaultSerializers\ImmutableStackSerializer`2.cs - - - Serialization\DefaultSerializers\InternalDateTimeExtensions.cs - - - Serialization\DefaultSerializers\MessagePackObjectExtensions.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MsgPack_MessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\MultidimensionalArraySerializer`1.cs - - - Serialization\DefaultSerializers\NativeDateTimeMessagePackSerializer.cs - - - Serialization\DefaultSerializers\NullableMessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ArraySegment_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_ByteArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_CharArrayMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_DictionaryEntryMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_KeyValuePair_2MessagePackSerializer`2.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_List_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Queue_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_Generic_Stack_1MessagePackSerializer`1.cs - - - Serialization\DefaultSerializers\System_Collections_QueueMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Collections_StackMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_DBNullMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Globalization_CultureInfoMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Numerics_ComplexMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_ObjectMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_StringMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_Text_StringBuilderMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_UriMessagePackSerializer.cs - - - Serialization\DefaultSerializers\System_VersionMessagePackSerializer.cs - - - Serialization\DefaultSerializers\UnixEpocDateTimeMessagePackSerializer.cs - - - Serialization\EmitterFlavor.cs - - - Serialization\EnumMemberSerializationMethod.cs - - - Serialization\EnumMessagePackSerializerHelpers.cs - - - Serialization\EnumMessagePackSerializerProvider.cs - - - Serialization\EnumMessagePackSerializer`1.cs - - - Serialization\EnumSerializationMethod.cs - - - Serialization\ExtTypeCodeMapping.cs - - - Serialization\ICustomizableEnumSerializer.cs - - - Serialization\IdentifierUtility.cs - - - Serialization\IMessagePackSerializer.cs - - - Serialization\IMessagePackSingleObjectSerializer.cs - - - Serialization\INilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\INilImplicationHandlerParameter.cs - - - Serialization\LazyDelegatingMessagePackSerializer`1.cs - - - Serialization\MessagePackDateTimeMemberAttribute.cs - - - Serialization\MessagePackDeserializationConstructorAttribute.cs - - - Serialization\MessagePackEnumAttribute.cs - - - Serialization\MessagePackEnumMemberAttribute.cs - - - Serialization\MessagePackIgnoreAttribute.cs - - - Serialization\MessagePackKnownTypeAttributes.cs - - - Serialization\MessagePackMemberAttribute.cs - - - Serialization\MessagePackRuntimeTypeAttributes.cs - - - Serialization\MessagePackSerializer.cs - - - Serialization\MessagePackSerializer.Factories.cs - - - Serialization\MessagePackSerializerExtensions.cs - - - Serialization\MessagePackSerializerProvider.cs - - - Serialization\MessagePackSerializer`1.cs - - - Serialization\NilImplication.cs - - - Serialization\NilImplicationHandler`4.cs - - - Serialization\PackHelpers.cs - - - Serialization\Polymorphic\IPolymorphicDeserializer.cs - - - Serialization\Polymorphic\IPolymorphicHelperAttributes.cs - - - Serialization\Polymorphic\KnownTypePolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\PolymorphicSerializerProvider`1.cs - - - Serialization\Polymorphic\TypeEmbedingPolymorphicMessagePackSerializer`1.cs - - - Serialization\Polymorphic\TypeInfoEncoder.cs - - - Serialization\Polymorphic\TypeInfoEncoding.cs - - - Serialization\PolymorphismSchema.Constructors.cs - - - Serialization\PolymorphismSchema.cs - - - Serialization\PolymorphismSchema.Internals.cs - - - Serialization\PolymorphismSchemaChildrenType.cs - - - Serialization\PolymorphismTarget.cs - - - Serialization\PolymorphismType.cs - - - Serialization\ReflectionExtensions.cs - - - Serialization\ReflectionHelpers.cs - - - Serialization\ReflectionSerializers\ReflectionCollectionMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionDictionaryMessagePackSerializer`3.cs - - - Serialization\ReflectionSerializers\ReflectionEnumerableMessagePackSerializer`2.cs - - - Serialization\ReflectionSerializers\ReflectionEnumMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNilImplicationHandler.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricCollectionMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericDictionaryMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionNonGenericListMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionObjectMessagePackSerializer`1.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerHelper.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerOnUnpackedParameter.cs - - - Serialization\ReflectionSerializers\ReflectionSerializerNilImplicationHandlerParameter.cs - - - Serialization\ReflectionSerializers\ReflectionTupleMessagePackSerializer`1.cs - - - Serialization\Reflection\GenericTypeExtensions.cs - - - Serialization\Reflection\ReflectionExtensions.cs - - - Serialization\ResolveSerializerEventArgs.cs - - - Serialization\SerializationCompatibilityOptions.cs - - - Serialization\SerializationContext.cs - - - Serialization\SerializationContext.ExtTypeCodes.cs - - - Serialization\SerializationExceptions.cs - - - Serialization\SerializationMethod.cs - - - Serialization\SerializationMethodGeneratorOption.cs - - - Serialization\SerializationTarget.cs - - - Serialization\SerializerCapabilities.cs - - - Serialization\SerializerDebugging.cs - - - Serialization\SerializerOptions.cs - - - Serialization\SerializerRegistrationOptions.cs - - - Serialization\SerializerRepository.cs - - - Serialization\SerializerRepository.defaults.cs - - - Serialization\SerializerTypeKeyRepository.cs - - - Serialization\SerializingMember.cs - - - Serialization\TypeKeyRepository.cs - - - Serialization\UnpackHelpers.cs - - - Serialization\UnpackHelpers.direct.cs - - - Serialization\UnpackHelpers.facade.cs - - - SetOperation.cs - - - StreamPacker.cs - - - StringEscape.cs - - - SubtreeUnpacker.cs - - - SubtreeUnpacker.Unpacking.cs - - - TupleItems.cs - - - UnassignedMessageTypeException.cs - - - Unpacker.cs - - - Unpacker.Unpacking.cs - - - UnpackException.cs - - - Unpacking.cs - - - Unpacking.Numerics.cs - - - Unpacking.Others.cs - - - Unpacking.Streaming.cs - - - Unpacking.String.cs - - - UnpackingMode.cs - - - UnpackingResult.cs - - - UnpackingStream.cs - - - UnpackingStreamReader.cs - - - UnsafeNativeMethods.cs - - - - - - remarks.xml - - - \ No newline at end of file diff --git a/src/MsgPack.Xamarin.iOS/Properties/AssemblyInfo.cs b/src/MsgPack.Xamarin.iOS/Properties/AssemblyInfo.cs deleted file mode 100644 index 0c8299d24..000000000 --- a/src/MsgPack.Xamarin.iOS/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Security; - -using MonoTouch.Foundation; - -[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )] -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library for Xamarin.iOS." )] - -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] - -[assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )] -[assembly: AllowPartiallyTrustedCallers] - -#if DEBUG || PERFORMANCE_TEST -[assembly: InternalsVisibleTo( "MsgPackUnitTestXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - -[assembly: LinkerSafe] - diff --git a/src/MsgPack/AsyncReadResult.cs b/src/MsgPack/AsyncReadResult.cs index 029e614d2..7c428149f 100644 --- a/src/MsgPack/AsyncReadResult.cs +++ b/src/MsgPack/AsyncReadResult.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,15 +18,10 @@ // #endregion -- License Terms -- -#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - using System; namespace MsgPack { -#if FEATURE_TAP /// /// Provides static utility methods for . /// @@ -53,6 +48,15 @@ public static AsyncReadResult Fail() // Fast-path return default( AsyncReadResult ); } + + internal static AsyncReadResult> Success( T returnValue, int offset ) + { + return new AsyncReadResult>( new Int32OffsetValue( returnValue, offset ), true ); + } + + internal static AsyncReadResult> Success( T returnValue, long offset ) + { + return new AsyncReadResult>( new Int64OffsetValue( returnValue, offset ), true ); + } } -#endif // FEATURE_TAP } \ No newline at end of file diff --git a/src/MsgPack/AsyncReadResult`1.cs b/src/MsgPack/AsyncReadResult`1.cs index 0bcd69301..191ea8159 100644 --- a/src/MsgPack/AsyncReadResult`1.cs +++ b/src/MsgPack/AsyncReadResult`1.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,16 +18,11 @@ // #endregion -- License Terms -- -#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - using System; using System.Collections.Generic; namespace MsgPack { -#if FEATURE_TAP /// /// Represents asynchronous reading result. /// @@ -137,5 +132,4 @@ public override string ToString() return !left.Equals( right ); } } -#endif // FEATURE_TAP } \ No newline at end of file diff --git a/src/MsgPack/BigEndianBinary.cs b/src/MsgPack/BigEndianBinary.cs index f553f714e..906efdaf7 100644 --- a/src/MsgPack/BigEndianBinary.cs +++ b/src/MsgPack/BigEndianBinary.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,18 +23,23 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack { /// - /// Define bit operations which enforce big endian. + /// Defines bit operations which enforce big endian. /// - internal static class BigEndianBinary +#if UNITY && DEBUG + public +#else + internal +#endif + static class BigEndianBinary { public static sbyte ToSByte( byte[] buffer, int offset ) { diff --git a/src/MsgPack/Binary.cs b/src/MsgPack/Binary.cs index 5c4af062d..e86aeac43 100644 --- a/src/MsgPack/Binary.cs +++ b/src/MsgPack/Binary.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Text; @@ -26,7 +30,12 @@ namespace MsgPack /// /// Defines binary related utilities. /// - internal static class Binary +#if UNITY && DEBUG + public +#else + internal +#endif + static class Binary { /// /// Singleton empty []. @@ -85,5 +94,34 @@ private static char ToHexChar( int b ) return unchecked( ( char )( 'A' + ( b - 10 ) ) ); } } + + public static int ToBits( float value ) + { + var bits = new Float32Bits( value ); + var result = default( int ); + + // Float32Bits usage is effectively pointer dereference operation rather than shifting operators, so we must consider endianness here. + if ( BitConverter.IsLittleEndian ) + { + result = bits.Byte3 << 24; + result |= bits.Byte2 << 16; + result |= bits.Byte1 << 8; + result |= bits.Byte0; + } + else + { + result = bits.Byte0 << 24; + result |= bits.Byte1 << 16; + result |= bits.Byte2 << 8; + result |= bits.Byte3; + } + + return result; + } + + public static long ToBits( double value ) + { + return BitConverter.DoubleToInt64Bits( value ); + } } } diff --git a/src/netstandard/BufferedStream.cs b/src/MsgPack/BufferedStream.cs similarity index 99% rename from src/netstandard/BufferedStream.cs rename to src/MsgPack/BufferedStream.cs index 2093bf8a0..c75a05c93 100644 --- a/src/netstandard/BufferedStream.cs +++ b/src/MsgPack/BufferedStream.cs @@ -44,14 +44,14 @@ namespace System.IO /// greater than the internal buffer size, then this class may not even allocate the internal buffer. /// See a large comment in Write for the details of the write buffer heuristic. /// - /// This class buffers reads & writes in a shared buffer. + /// This class buffers reads & writes in a shared buffer. /// (If you maintained two buffers separately, one operation would always trash the other buffer /// anyways, so we might as well use one buffer.) /// The assumption here is you will almost always be doing a series of reads or writes, but rarely /// alternate between the two of them on the same stream. /// /// Class Invariants: - /// The class has one buffer, shared for reading & writing. + /// The class has one buffer, shared for reading & writing. /// It can only be used for one or the other at any point in time - not both. /// The following should be true: /// + /// Defines interface and basic functionality for byte array based . + /// + public abstract class ByteArrayPacker : Packer + { + /// + /// Gets the bytes used by this instance. + /// + /// + /// The bytes used by this instance. The initial state is 0. + /// + public abstract int BytesUsed { get; } + + /// + /// Gets the initial offset of the destination buffer. + /// + /// + /// The initial index of the destination buffer. + /// This value is greater than or equal to 0 and less than the destination buffer's length. + /// + public abstract int InitialBufferOffset { get; } + + /// + /// Initializes a new instance of the class. + /// + protected ByteArrayPacker() { } + + /// + /// Initializes a new instance of the class with specified . + /// + /// A which specifies compatibility options. + protected ByteArrayPacker( PackerCompatibilityOptions compatibilityOptions ) + : base( compatibilityOptions ) { } + + /// + /// Gets the final effective (written) bytes as single array segment. + /// + /// The final buffers as single . Its size will be . + /// + /// The result segment contains the array returned from , and reflects and . + /// + public ArraySegment GetResultBytes() + { + return new ArraySegment( this.GetFinalBuffer(), this.InitialBufferOffset, this.BytesUsed ); + } + + /// + /// Gets the final buffer which may be reallocated. + /// + /// The final buffer which may be reallocated. + /// + /// If the packer was allowed re-allocation, you can get new byte array from this method. + /// Otherwise, the returned buffer should be same as the array passed in the constructor. + /// + public abstract byte[] GetFinalBuffer(); + } +} diff --git a/src/MsgPack/ByteArrayUnpacker.cs b/src/MsgPack/ByteArrayUnpacker.cs new file mode 100644 index 000000000..9d808b6be --- /dev/null +++ b/src/MsgPack/ByteArrayUnpacker.cs @@ -0,0 +1,43 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Defines interface and basic functionality for byte array based . + /// + public abstract class ByteArrayUnpacker : Unpacker + { + /// + /// Gets the current offset of the source. + /// + /// + /// The current offset of the source. + /// + public abstract int Offset { get; } + + /// + /// Initializes a new instance of the class. + /// + protected ByteArrayUnpacker() { } + } +} diff --git a/src/MsgPack/ByteBufferAllocator.cs b/src/MsgPack/ByteBufferAllocator.cs new file mode 100644 index 000000000..cfaa3d775 --- /dev/null +++ b/src/MsgPack/ByteBufferAllocator.cs @@ -0,0 +1,43 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; + +namespace MsgPack +{ + /// + /// Defines common interface for byte buffer allocators. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + abstract class ByteBufferAllocator + { + // This type should be public when the design is fixed for Span + + public abstract bool TryAllocate( byte[] oldBuffer, int requestSize, out byte[] newBuffer ); + } +} diff --git a/src/MsgPack/CollectionOperation.cs b/src/MsgPack/CollectionOperation.cs index 10887c3ba..4134032b1 100644 --- a/src/MsgPack/CollectionOperation.cs +++ b/src/MsgPack/CollectionOperation.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -24,11 +24,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; namespace MsgPack diff --git a/src/MsgPack/CollectionType.cs b/src/MsgPack/CollectionType.cs new file mode 100644 index 000000000..9182626ac --- /dev/null +++ b/src/MsgPack/CollectionType.cs @@ -0,0 +1,35 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Represents collection type. + /// + internal enum CollectionType + { + // Value must be items count of collection element. + None = 0, + Array = 1, + Map = 2 + } +} diff --git a/src/MsgPack.Net35/Contract.cs b/src/MsgPack/Contract.cs similarity index 100% rename from src/MsgPack.Net35/Contract.cs rename to src/MsgPack/Contract.cs diff --git a/src/MsgPack.Net35/Delegates.cs b/src/MsgPack/Delegates.cs similarity index 100% rename from src/MsgPack.Net35/Delegates.cs rename to src/MsgPack/Delegates.cs diff --git a/src/MsgPack.Net35/Delegates.tt b/src/MsgPack/Delegates.tt similarity index 100% rename from src/MsgPack.Net35/Delegates.tt rename to src/MsgPack/Delegates.tt diff --git a/src/MsgPack/EncodingExtensions.cs b/src/MsgPack/EncodingExtensions.cs new file mode 100644 index 000000000..3f980be1a --- /dev/null +++ b/src/MsgPack/EncodingExtensions.cs @@ -0,0 +1,114 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +#if MPCONTRACT +using Contract = MsgPack.MPContract; +#else +#endif // MPCONTRACT +using System.Text; +#if FEATURE_TAP +#endif // FEATURE_TAP + +namespace MsgPack +{ + /// + /// Common encoding extensions for streaming encoding/decoding. + /// + internal static class EncodingExtensions + { +#if FEATURE_POINTER_CONVERSION +#if !NET35 && !UNITY + [System.Security.SecuritySafeCritical] +#endif // !NET35 && !UNITY + public static unsafe bool EncodeString( this Encoder source, char* pChar, int charsLength, byte* pBuffer, int bufferCount, out int charsUsed, out int bytesUsed ) + { + bool isCompleted; + source.Convert( + pChar, + charsLength, + pBuffer, + bufferCount, + false, + out charsUsed, + out bytesUsed, + out isCompleted + ); + + return isCompleted; + } +#else +#if NETSTANDARD2_0 +#warning TODO: Use pointer based API. +#endif // NETSTANDARD2_0 + public static bool EncodeString( this Encoder source, char[] chars, int charsOffset, int charsLength, byte[] buffer, int bufferOffset, int bufferCount, out int charsUsed, out int bytesUsed ) + { + bool isCompleted; + source.Convert( + chars, + charsOffset, + charsLength, + buffer, + bufferOffset, + bufferCount, + false, + out charsUsed, + out bytesUsed, + out isCompleted + ); + + return isCompleted; + } +#endif // FEATURE_POINTER_CONVERSION + + public static bool DecodeString( this Decoder source, byte[] bytes, int bytesOffset, int bytesLength, char[] buffer, StringBuilder result ) + { + bool isCompleted; + + // Loop + do + { + int bytesUsed; + int charsUsed; + source.Convert( + bytes, + bytesOffset, + bytesLength, + buffer, + 0, + buffer.Length, + false, + out bytesUsed, + out charsUsed, + out isCompleted + ); + + result.Append( buffer, 0, charsUsed ); + bytesOffset += bytesUsed; + bytesLength -= bytesUsed; + } while ( bytesLength > 0 ); + + return isCompleted; + } + } +} diff --git a/src/MsgPack/FixedArrayBufferAllocator.cs b/src/MsgPack/FixedArrayBufferAllocator.cs new file mode 100644 index 000000000..eb1eb1873 --- /dev/null +++ b/src/MsgPack/FixedArrayBufferAllocator.cs @@ -0,0 +1,41 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; + +namespace MsgPack +{ + /// + /// An implementation of which does not do any allocation and forces reuse of original array. + /// + internal sealed class FixedArrayBufferAllocator : ByteBufferAllocator + { + public static readonly ByteBufferAllocator Instance = new FixedArrayBufferAllocator(); + + private FixedArrayBufferAllocator() { } + + public override bool TryAllocate( byte[] oldBuffer, int requestSize, out byte[] newBuffer ) + { + newBuffer = null; + return false; + } + } +} diff --git a/src/MsgPack/Float32Bits.cs b/src/MsgPack/Float32Bits.cs index 1ed5cae17..d340e05e7 100644 --- a/src/MsgPack/Float32Bits.cs +++ b/src/MsgPack/Float32Bits.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Runtime.InteropServices; namespace MsgPack diff --git a/src/MsgPack/Float64Bits.cs b/src/MsgPack/Float64Bits.cs index a7e17bcc4..e597393f5 100644 --- a/src/MsgPack/Float64Bits.cs +++ b/src/MsgPack/Float64Bits.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Runtime.InteropServices; namespace MsgPack diff --git a/src/MsgPack/GlobalSuppressions.cs b/src/MsgPack/GlobalSuppressions.cs index ff4048c20..acefc1e6a 100644 --- a/src/MsgPack/GlobalSuppressions.cs +++ b/src/MsgPack/GlobalSuppressions.cs @@ -22,6 +22,7 @@ [module: SuppressMessage( "Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "MsgPack.Collections", Justification = "Under construction." )] [assembly: SuppressMessage( "Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "MsgPack.Serialization.UnpackHelpers+UnpackerTraceContext" )] +[assembly: SuppressMessage( "Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.IO.TextWriter.#ctor", Scope = "member", Target = "MsgPack.Serialization.NullTextWriter.#.ctor()", Justification = "NullTextWriter does not do any action." )] #if SILVERLIGHT && WINDOWS_PHONE [assembly: SuppressMessage( "Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames" )] #endif // SILVERLIGHT && WINDOWS_PHONE diff --git a/src/MsgPack/IAsyncUnpackable.cs b/src/MsgPack/IAsyncUnpackable.cs index b4e94dff4..b1055f0c0 100644 --- a/src/MsgPack/IAsyncUnpackable.cs +++ b/src/MsgPack/IAsyncUnpackable.cs @@ -21,7 +21,6 @@ #if FEATURE_TAP using System; -using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; diff --git a/src/MsgPack/IRootUnpacker.cs b/src/MsgPack/IRootUnpacker.cs new file mode 100644 index 000000000..5da8f2499 --- /dev/null +++ b/src/MsgPack/IRootUnpacker.cs @@ -0,0 +1,42 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Defines accessor for internal, domestic Unpacker implementations. + /// + internal interface IRootUnpacker + { + CollectionType CollectionType { get; } + + MessagePackObject? Data { get; set; } + + MessagePackObject LastReadData { get; set; } + +#if DEBUG + long? UnderlyingStreamPosition { get; } +#endif // DEBUG + + bool ReadObject( bool isDeep, out MessagePackObject result ); + } +} diff --git a/src/MsgPack/Int32OffsetValue`1.cs b/src/MsgPack/Int32OffsetValue`1.cs new file mode 100644 index 000000000..e55a11719 --- /dev/null +++ b/src/MsgPack/Int32OffsetValue`1.cs @@ -0,0 +1,41 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Represents offset and value pair. + /// + /// A type of the value. + internal struct Int32OffsetValue + { + public readonly int Offset; + + public readonly T Result; + + public Int32OffsetValue( T result, int offset ) + { + this.Result = result; + this.Offset = offset; + } + } +} diff --git a/src/MsgPack/Int64OffsetValue`1.cs b/src/MsgPack/Int64OffsetValue`1.cs new file mode 100644 index 000000000..cd9f6af63 --- /dev/null +++ b/src/MsgPack/Int64OffsetValue`1.cs @@ -0,0 +1,41 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Represents offset and value pair. + /// + /// A type of the value. + internal struct Int64OffsetValue + { + public readonly long Offset; + + public readonly T Result; + + public Int64OffsetValue( T result, long offset ) + { + this.Result = result; + this.Offset = offset; + } + } +} diff --git a/src/MsgPack/ItemsUnpacker.Read.cs b/src/MsgPack/ItemsUnpacker.Read.cs deleted file mode 100644 index 34658a4ad..000000000 --- a/src/MsgPack/ItemsUnpacker.Read.cs +++ /dev/null @@ -1,3640 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -using System.Collections.Generic; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - // This file was generated from ItemsUnpacker.Read.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit ItemsUnpacker.Read.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class ItemsUnpacker - { - public override bool ReadBoolean( out Boolean result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeBoolean( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadBooleanAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeBooleanAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeBoolean( out Boolean result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Boolean ); - return false; - } - case ReadValueResult.Boolean: - { - this.InternalCollectionType = CollectionType.None; - result = integral != 0; - return true; - } - default: - { - this.ThrowTypeException( typeof( Boolean ), header ); - // Never reach - result = default( Boolean ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeBooleanAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Boolean: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.integral != 0 ); - } - default: - { - this.ThrowTypeException( typeof( Boolean ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableBoolean( out Boolean? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableBoolean( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableBooleanAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableBooleanAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableBoolean( out Boolean? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Boolean? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Boolean? ); - return true; - } - case ReadValueResult.Boolean: - { - this.InternalCollectionType = CollectionType.None; - result = integral != 0; - return true; - } - default: - { - this.ThrowTypeException( typeof( Boolean? ), header ); - // Never reach - result = default( Boolean? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableBooleanAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Boolean? ) ); - } - case ReadValueResult.Boolean: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.integral != 0 ); - } - default: - { - this.ThrowTypeException( typeof( Boolean? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadByte( out Byte result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeByte( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadByteAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeByteAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeByte( out Byte result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Byte ); - return false; - } - case ReadValueResult.Byte: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Byte )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Byte ), header ); - // Never reach - result = default( Byte ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeByteAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Byte: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( Byte )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Byte ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableByte( out Byte? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableByte( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableByteAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableByteAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableByte( out Byte? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Byte? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Byte? ); - return true; - } - case ReadValueResult.Byte: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Byte )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Byte )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Byte? ), header ); - // Never reach - result = default( Byte? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableByteAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Byte? ) ); - } - case ReadValueResult.Byte: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( Byte )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Byte )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Byte? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadSByte( out SByte result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeSByte( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadSByteAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeSByteAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeSByte( out SByte result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( SByte ); - return false; - } - case ReadValueResult.SByte: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( SByte )integral ); - return true; - } - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( SByte ), header ); - // Never reach - result = default( SByte ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeSByteAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.SByte: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( SByte )asyncResult.integral ) ); - } - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( SByte ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableSByte( out SByte? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableSByte( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableSByteAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableSByteAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableSByte( out SByte? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( SByte? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( SByte? ); - return true; - } - case ReadValueResult.SByte: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( SByte )integral ); - return true; - } - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( SByte )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( SByte? ), header ); - // Never reach - result = default( SByte? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableSByteAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( SByte? ) ); - } - case ReadValueResult.SByte: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( SByte )asyncResult.integral ) ); - } - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( SByte )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( SByte? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadInt16( out Int16 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeInt16( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadInt16Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeInt16Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeInt16( out Int16 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int16 ); - return false; - } - case ReadValueResult.Int16: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Int16 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int16 ), header ); - // Never reach - result = default( Int16 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeInt16Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Int16: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( Int16 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Int16 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableInt16( out Int16? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableInt16( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableInt16Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableInt16Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableInt16( out Int16? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int16? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Int16? ); - return true; - } - case ReadValueResult.Int16: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Int16 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int16 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int16? ), header ); - // Never reach - result = default( Int16? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableInt16Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Int16? ) ); - } - case ReadValueResult.Int16: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( Int16 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int16 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Int16? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadUInt16( out UInt16 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeUInt16( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadUInt16Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeUInt16Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeUInt16( out UInt16 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( UInt16 ); - return false; - } - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt16 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( UInt16 ), header ); - // Never reach - result = default( UInt16 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeUInt16Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( UInt16 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( UInt16 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableUInt16( out UInt16? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableUInt16( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableUInt16Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableUInt16Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableUInt16( out UInt16? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( UInt16? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( UInt16? ); - return true; - } - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt16 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt16 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( UInt16? ), header ); - // Never reach - result = default( UInt16? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableUInt16Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( UInt16? ) ); - } - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( UInt16 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt16 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( UInt16? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadInt32( out Int32 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeInt32( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadInt32Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeInt32Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeInt32( out Int32 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int32 ); - return false; - } - case ReadValueResult.Int32: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Int32 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int32 ), header ); - // Never reach - result = default( Int32 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeInt32Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Int32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( Int32 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Int32 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableInt32( out Int32? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableInt32( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableInt32Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableInt32Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableInt32( out Int32? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int32? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Int32? ); - return true; - } - case ReadValueResult.Int32: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Int32 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int32 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int32? ), header ); - // Never reach - result = default( Int32? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableInt32Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Int32? ) ); - } - case ReadValueResult.Int32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( Int32 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int32 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Int32? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadUInt32( out UInt32 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeUInt32( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadUInt32Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeUInt32Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeUInt32( out UInt32 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( UInt32 ); - return false; - } - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt32 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( UInt32 ), header ); - // Never reach - result = default( UInt32 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeUInt32Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( UInt32 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( UInt32 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableUInt32( out UInt32? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableUInt32( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableUInt32Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableUInt32Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableUInt32( out UInt32? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( UInt32? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( UInt32? ); - return true; - } - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt32 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )integral ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt32 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( UInt32? ), header ); - // Never reach - result = default( UInt32? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableUInt32Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( UInt32? ) ); - } - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( UInt32 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt32 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( UInt32? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadInt64( out Int64 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeInt64( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadInt64Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeInt64Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeInt64( out Int64 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int64 ); - return false; - } - case ReadValueResult.Int64: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int64 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int64 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int64 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int64 ), header ); - // Never reach - result = default( Int64 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeInt64Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Int64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.integral ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.integral ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int64 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int64 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int64 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Int64 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableInt64( out Int64? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableInt64( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableInt64Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableInt64Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableInt64( out Int64? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int64? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Int64? ); - return true; - } - case ReadValueResult.Int64: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int64 )( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int64 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Int64 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int64? ), header ); - // Never reach - result = default( Int64? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableInt64Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Int64? ) ); - } - case ReadValueResult.Int64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.integral ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.integral ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int64 )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int64 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Int64 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Int64? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadUInt64( out UInt64 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeUInt64( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadUInt64Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeUInt64Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeUInt64( out UInt64 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( UInt64 ); - return false; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt64 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt64 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( UInt64 ), header ); - // Never reach - result = default( UInt64 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeUInt64Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt64 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt64 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( UInt64 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableUInt64( out UInt64? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableUInt64( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableUInt64Async( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableUInt64Async( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableUInt64( out UInt64? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( UInt64? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( UInt64? ); - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt64 )real32 ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( UInt64 )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( UInt64? ), header ); - // Never reach - result = default( UInt64? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableUInt64Async( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( UInt64? ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( unchecked( ( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt64 )asyncResult.real32 ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( UInt64 )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( UInt64? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadSingle( out Single result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeSingle( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadSingleAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeSingleAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeSingle( out Single result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Single ); - return false; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = real32; - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Single )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Single ), header ); - // Never reach - result = default( Single ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeSingleAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.real32 ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Single )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Single )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Single )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Single ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableSingle( out Single? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableSingle( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableSingleAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableSingleAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableSingle( out Single? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Single? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Single? ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = real32; - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = checked( ( Single )real64 ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Single? ), header ); - // Never reach - result = default( Single? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableSingleAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Single? ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.real32 ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Single )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Single )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Single )asyncResult.real64 ) ); - } - default: - { - this.ThrowTypeException( typeof( Single? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadDouble( out Double result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeDouble( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadDoubleAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeDoubleAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeDouble( out Double result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Double ); - return false; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = real64; - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = real32; - return true; - } - default: - { - this.ThrowTypeException( typeof( Double ), header ); - // Never reach - result = default( Double ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeDoubleAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.real64 ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Double )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Double )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Double )asyncResult.real32 ) ); - } - default: - { - this.ThrowTypeException( typeof( Double ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadNullableDouble( out Double? result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableDouble( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadNullableDoubleAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeNullableDoubleAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeNullableDouble( out Double? result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Double? ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Double? ); - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = real64; - return true; - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = real32; - return true; - } - default: - { - this.ThrowTypeException( typeof( Double? ), header ); - // Never reach - result = default( Double? ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeNullableDoubleAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Double? ) ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( asyncResult.real64 ); - } - case ReadValueResult.SByte: - case ReadValueResult.Int16: - case ReadValueResult.Int32: - case ReadValueResult.Int64: - case ReadValueResult.Byte: - case ReadValueResult.UInt16: - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Double )asyncResult.integral ) ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Double )( UInt64 )asyncResult.integral ) ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( checked( ( Double )asyncResult.real32 ) ); - } - default: - { - this.ThrowTypeException( typeof( Double? ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadBinary( out Byte[] result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeBinary( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadBinaryAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeBinaryAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeBinary( out Byte[] result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Byte[] ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( Byte[] ); - return true; - } - case ReadValueResult.String: - case ReadValueResult.Binary: - { - result = this.ReadBinaryCore( integral ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Byte[] ), header ); - // Never reach - result = default( Byte[] ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeBinaryAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( Byte[] ) ); - } - case ReadValueResult.String: - case ReadValueResult.Binary: - { - return AsyncReadResult.Success( await this.ReadBinaryAsyncCore( asyncResult.integral, cancellationToken ).ConfigureAwait( false ) ); - } - default: - { - this.ThrowTypeException( typeof( Byte[] ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadString( out String result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeString( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadStringAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeStringAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeString( out String result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( String ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = default( String ); - return true; - } - case ReadValueResult.String: - case ReadValueResult.Binary: - { - result = this.ReadStringCore( integral ); - return true; - } - default: - { - this.ThrowTypeException( typeof( String ), header ); - // Never reach - result = default( String ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeStringAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - return AsyncReadResult.Success( default( String ) ); - } - case ReadValueResult.String: - case ReadValueResult.Binary: - { - return AsyncReadResult.Success( await this.ReadStringAsyncCore( asyncResult.integral, cancellationToken ).ConfigureAwait( false ) ); - } - default: - { - this.ThrowTypeException( typeof( String ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadObject( out MessagePackObject result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeObject( /* isDeep */true, out result ); - } - -#if FEATURE_TAP - - public override Task> ReadObjectAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeObjectAsync( /* isDeep */true, cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeObject( bool isDeep, out MessagePackObject result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( MessagePackObject ); - return false; - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - result = MessagePackObject.Nil; - this.InternalData = result; - return true; - } - case ReadValueResult.Boolean: - { - this.InternalCollectionType = CollectionType.None; - result = integral != 0; - this.InternalData = result; - return true; - } - case ReadValueResult.SByte: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( SByte )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.Int16: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Int16 )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.Int32: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Int32 )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.Int64: - { - this.InternalCollectionType = CollectionType.None; - result = integral; - this.InternalData = result; - return true; - } - case ReadValueResult.Byte: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( Byte )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt16 )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt32 )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - result = unchecked( ( UInt64 )integral ); - this.InternalData = result; - return true; - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - result = real32; - this.InternalData = result; - return true; - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - result = real64; - this.InternalData = result; - return true; - } - case ReadValueResult.ArrayLength: - { - var length = unchecked( ( UInt32 )this.ReadArrayLengthCore( integral ) ); - if ( !isDeep ) - { - result = length; - this.InternalData = result; - return true; - } - - this.CheckLength( length, ReadValueResult.ArrayLength ); - var collection = new List( unchecked( ( int ) length ) ); - for( var i = 0; i < length; i++ ) - { - MessagePackObject item; - if( !this.ReadSubtreeObject( /* isDeep */true, out item ) ) - { - result = default( MessagePackObject ); - return false; - } - - collection.Add( item ); - } - - { - result = new MessagePackObject( collection, /* isImmutable */true ); - this.InternalData = result; - return true; - } - } - case ReadValueResult.MapLength: - { - var length = unchecked( ( UInt32 )this.ReadMapLengthCore( integral ) ); - if ( !isDeep ) - { - result = length; - this.InternalData = result; - return true; - } - - this.CheckLength( length, ReadValueResult.MapLength ); - var collection = new MessagePackObjectDictionary( unchecked( ( int ) length ) ); - for( var i = 0; i < length; i++ ) - { - MessagePackObject key; - if( !this.ReadSubtreeObject( /* isDeep */true, out key ) ) - { - result = default( MessagePackObject ); - return false; - } - - MessagePackObject value; - if( !this.ReadSubtreeObject( /* isDeep */true, out value ) ) - { - result = default( MessagePackObject ); - return false; - } - - collection.Add( key, value ); - } - - { - result = new MessagePackObject( collection, /* isImmutable */true ); - this.InternalData = result; - return true; - } - } - - case ReadValueResult.String: - { - result = new MessagePackObject( new MessagePackString( this.ReadBinaryCore( integral ), false ) ); - this.InternalData = result; - return true; - } - case ReadValueResult.Binary: - { - result = new MessagePackObject( new MessagePackString( this.ReadBinaryCore( integral ), true ) ); - this.InternalData = result; - return true; - } - case ReadValueResult.FixExt1: - case ReadValueResult.FixExt2: - case ReadValueResult.FixExt4: - case ReadValueResult.FixExt8: - case ReadValueResult.FixExt16: - case ReadValueResult.Ext8: - case ReadValueResult.Ext16: - case ReadValueResult.Ext32: - { - result = this.ReadMessagePackExtendedTypeObjectCore( type ); - this.InternalData = result; - return true; - } - default: - { - this.ThrowTypeException( typeof( MessagePackObject ), header ); - // Never reach - result = default( MessagePackObject ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeObjectAsync( bool isDeep, CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.Nil: - { - this.InternalCollectionType = CollectionType.None; - var result = MessagePackObject.Nil; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Boolean: - { - this.InternalCollectionType = CollectionType.None; - var result = asyncResult.integral != 0; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.SByte: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( SByte )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Int16: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( Int16 )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Int32: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( Int32 )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Int64: - { - this.InternalCollectionType = CollectionType.None; - var result = asyncResult.integral; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Byte: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( Byte )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.UInt16: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( UInt16 )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.UInt32: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( UInt32 )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.UInt64: - { - this.InternalCollectionType = CollectionType.None; - var result = unchecked( ( UInt64 )asyncResult.integral ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Single: - { - this.InternalCollectionType = CollectionType.None; - var result = asyncResult.real32; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Double: - { - this.InternalCollectionType = CollectionType.None; - var result = asyncResult.real64; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.ArrayLength: - { - // ReadArrayLengthCore does not perform I/O, so no ReadArrayLengthAsyncCore exists. - var length = unchecked( ( UInt32 )this.ReadArrayLengthCore( asyncResult.integral ) ); - if ( !isDeep ) - { - var result = length; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - - this.CheckLength( length, ReadValueResult.ArrayLength ); - var collection = new List( unchecked( ( int ) length ) ); - for( var i = 0; i < length; i++ ) - { - MessagePackObject item; - if( !this.ReadSubtreeObject( /* isDeep */true, out item ) ) - { - return AsyncReadResult.Fail(); - } - - collection.Add( item ); - } - - { - var result = new MessagePackObject( collection, /* isImmutable */true ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - } - case ReadValueResult.MapLength: - { - // ReadMapLengthCore does not perform I/O, so no ReadMapLengthAsyncCore exists. - var length = unchecked( ( UInt32 )this.ReadMapLengthCore( asyncResult.integral ) ); - if ( !isDeep ) - { - var result = length; - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - - this.CheckLength( length, ReadValueResult.MapLength ); - var collection = new MessagePackObjectDictionary( unchecked( ( int ) length ) ); - for( var i = 0; i < length; i++ ) - { - MessagePackObject key; - if( !this.ReadSubtreeObject( /* isDeep */true, out key ) ) - { - return AsyncReadResult.Fail(); - } - - MessagePackObject value; - if( !this.ReadSubtreeObject( /* isDeep */true, out value ) ) - { - return AsyncReadResult.Fail(); - } - - collection.Add( key, value ); - } - - { - var result = new MessagePackObject( collection, /* isImmutable */true ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - } - - case ReadValueResult.String: - { - var result = new MessagePackObject( new MessagePackString( await this.ReadBinaryAsyncCore( asyncResult.integral, cancellationToken ).ConfigureAwait( false ), false ) ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.Binary: - { - var result = new MessagePackObject( new MessagePackString( await this.ReadBinaryAsyncCore( asyncResult.integral, cancellationToken ).ConfigureAwait( false ), true ) ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - case ReadValueResult.FixExt1: - case ReadValueResult.FixExt2: - case ReadValueResult.FixExt4: - case ReadValueResult.FixExt8: - case ReadValueResult.FixExt16: - case ReadValueResult.Ext8: - case ReadValueResult.Ext16: - case ReadValueResult.Ext32: - { - var result = await this.ReadMessagePackExtendedTypeObjectAsyncCore( type, cancellationToken ).ConfigureAwait( false ); - this.InternalData = result; - return AsyncReadResult.Success( result ); - } - default: - { - this.ThrowTypeException( typeof( MessagePackObject ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadArrayLength( out Int64 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeArrayLength( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadArrayLengthAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeArrayLengthAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeArrayLength( out Int64 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int64 ); - return false; - } - case ReadValueResult.ArrayLength: - { - result = this.ReadArrayLengthCore( integral); - this.CheckLength( result, ReadValueResult.ArrayLength ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int64 ), header ); - // Never reach - result = default( Int64 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeArrayLengthAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.ArrayLength: - { - // ReadArrayLengthCore does not perform I/O, so no ReadArrayLengthAsyncCore exists. - var result = this.ReadArrayLengthCore( asyncResult.integral); - this.CheckLength( result, ReadValueResult.ArrayLength ); - return AsyncReadResult.Success( result ); - } - default: - { - this.ThrowTypeException( typeof( Int64 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadMapLength( out Int64 result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeMapLength( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadMapLengthAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeMapLengthAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeMapLength( out Int64 result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( Int64 ); - return false; - } - case ReadValueResult.MapLength: - { - result = this.ReadMapLengthCore( integral); - this.CheckLength( result, ReadValueResult.MapLength ); - return true; - } - default: - { - this.ThrowTypeException( typeof( Int64 ), header ); - // Never reach - result = default( Int64 ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeMapLengthAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.MapLength: - { - // ReadMapLengthCore does not perform I/O, so no ReadMapLengthAsyncCore exists. - var result = this.ReadMapLengthCore( asyncResult.integral); - this.CheckLength( result, ReadValueResult.MapLength ); - return AsyncReadResult.Success( result ); - } - default: - { - this.ThrowTypeException( typeof( Int64 ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - public override bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeMessagePackExtendedTypeObject( out result ); - } - -#if FEATURE_TAP - - public override Task> ReadMessagePackExtendedTypeObjectAsync( CancellationToken cancellationToken ) - { - this.EnsureNotInSubtreeMode(); - return this.ReadSubtreeMessagePackExtendedTypeObjectAsync( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal bool ReadSubtreeMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result ) - { - byte header; - long integral; - float real32; - double real64; - var type = this.ReadValue( out header, out integral, out real32, out real64 ); - switch( type ) - { - case ReadValueResult.Eof: - { - result = default( MessagePackExtendedTypeObject ); - return false; - } - case ReadValueResult.FixExt1: - case ReadValueResult.FixExt2: - case ReadValueResult.FixExt4: - case ReadValueResult.FixExt8: - case ReadValueResult.FixExt16: - case ReadValueResult.Ext8: - case ReadValueResult.Ext16: - case ReadValueResult.Ext32: - { - result = this.ReadMessagePackExtendedTypeObjectCore( type ); - return true; - } - default: - { - this.ThrowTypeException( typeof( MessagePackExtendedTypeObject ), header ); - // Never reach - result = default( MessagePackExtendedTypeObject ); - return false; - } - } - } - -#if FEATURE_TAP - - internal async Task> ReadSubtreeMessagePackExtendedTypeObjectAsync( CancellationToken cancellationToken ) - { - var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); - var type = asyncResult.type; - switch( type ) - { - case ReadValueResult.Eof: - { - return AsyncReadResult.Fail(); - } - case ReadValueResult.FixExt1: - case ReadValueResult.FixExt2: - case ReadValueResult.FixExt4: - case ReadValueResult.FixExt8: - case ReadValueResult.FixExt16: - case ReadValueResult.Ext8: - case ReadValueResult.Ext16: - case ReadValueResult.Ext32: - { - return AsyncReadResult.Success( await this.ReadMessagePackExtendedTypeObjectAsyncCore( type, cancellationToken ).ConfigureAwait( false ) ); - } - default: - { - this.ThrowTypeException( typeof( MessagePackExtendedTypeObject ), asyncResult.header ); - // Never reach - return AsyncReadResult.Fail(); - } - } - } - -#endif // FEATURE_TAP - - } -} - diff --git a/src/MsgPack/ItemsUnpacker.Read.tt b/src/MsgPack/ItemsUnpacker.Read.tt deleted file mode 100644 index 9aad84929..000000000 --- a/src/MsgPack/ItemsUnpacker.Read.tt +++ /dev/null @@ -1,876 +0,0 @@ -<#@ template debug="true" hostSpecific="true" language="C#" #> -<#@ output extension=".cs" #> -<#@ Assembly Name="System.Core.dll" #> -<#@ include file="..\Core.ttinclude" #> -<#@ import namespace="System" #> -<#@ import namespace="System.Collections" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Diagnostics" #> -<#@ import namespace="System.Globalization" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Runtime.InteropServices" #> -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -using System.Collections.Generic; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - // This file was generated from ItemsUnpacker.Read.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit ItemsUnpacker.Read.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class ItemsUnpacker - { -<# -this.PushIndent( 2 ); - -foreach( var type in - new [] - { - typeof( bool ), - typeof( byte ), typeof( sbyte ), - typeof( short ), typeof( ushort ), - typeof( int ), typeof( uint ), - typeof( long ), typeof( ulong ), - typeof( float ), typeof( double ), - } -) -{ - this.WriteReadBody( type.Name, type.Name, false, false, isAsync => this.WriteReadScalar( type, isAsync ) ); - this.WriteReadBody( type.Name, type.Name, false, true, isAsync => this.WriteReadScalar( type, isAsync ) ); - this.WriteReadBody( type.Name, type.Name, true, false, isAsync => this.WriteReadScalar( type, isAsync ) ); - this.WriteReadBody( type.Name, type.Name, true, true, isAsync => this.WriteReadScalar( type, isAsync ) ); - - this.WriteReadBody( "Nullable" + type.Name, type.Name + "?", false, false, isAsync => this.WriteReadScalar( typeof( Nullable<> ).MakeGenericType( type ), isAsync ) ); - this.WriteReadBody( "Nullable" + type.Name, type.Name + "?", false, true, isAsync => this.WriteReadScalar( typeof( Nullable<> ).MakeGenericType( type ), isAsync ) ); - this.WriteReadBody( "Nullable" + type.Name, type.Name + "?", true, false, isAsync => this.WriteReadScalar( typeof( Nullable<> ).MakeGenericType( type ), isAsync ) ); - this.WriteReadBody( "Nullable" + type.Name, type.Name + "?", true, true, isAsync => this.WriteReadScalar( typeof( Nullable<> ).MakeGenericType( type ), isAsync ) ); -} - -this.WriteReadBody( "Binary", "Byte[]", false, false, isAsync => this.WriteReadRaw( "Byte[]", "Binary", isAsync ) ); -this.WriteReadBody( "Binary", "Byte[]", false, true, isAsync => this.WriteReadRaw( "Byte[]", "Binary", isAsync ) ); -this.WriteReadBody( "Binary", "Byte[]", true, false, isAsync => this.WriteReadRaw( "Byte[]", "Binary", isAsync ) ); -this.WriteReadBody( "Binary", "Byte[]", true, true, isAsync => this.WriteReadRaw( "Byte[]", "Binary", isAsync ) ); -this.WriteReadBody( "String", "String", false, false, isAsync => this.WriteReadRaw( "String", "String", isAsync ) ); -this.WriteReadBody( "String", "String", false, true, isAsync => this.WriteReadRaw( "String", "String", isAsync ) ); -this.WriteReadBody( "String", "String", true, false, isAsync => this.WriteReadRaw( "String", "String", isAsync ) ); -this.WriteReadBody( "String", "String", true, true, isAsync => this.WriteReadRaw( "String", "String", isAsync ) ); - -this.WriteReadBody( "Object", "MessagePackObject", false, false, isAsync => this.WriteReadObject( isAsync ) ); -this.WriteReadBody( "Object", "MessagePackObject", false, true, isAsync => this.WriteReadObject( isAsync ) ); -this.WriteReadBody( "Object", "MessagePackObject", true, false, isAsync => this.WriteReadObject( isAsync ) ); -this.WriteReadBody( "Object", "MessagePackObject", true, true, isAsync => this.WriteReadObject( isAsync ) ); -this.WriteReadBody( "ArrayLength", "Int64", false, false, isAsync => this.WriteReadLength( "ArrayLength", isAsync ) ); -this.WriteReadBody( "ArrayLength", "Int64", false, true, isAsync => this.WriteReadLength( "ArrayLength", isAsync ) ); -this.WriteReadBody( "ArrayLength", "Int64", true, false, isAsync => this.WriteReadLength( "ArrayLength", isAsync ) ); -this.WriteReadBody( "ArrayLength", "Int64", true, true, isAsync => this.WriteReadLength( "ArrayLength", isAsync ) ); -this.WriteReadBody( "MapLength", "Int64", false, false, isAsync => this.WriteReadLength( "MapLength", isAsync ) ); -this.WriteReadBody( "MapLength", "Int64", false, true, isAsync => this.WriteReadLength( "MapLength", isAsync ) ); -this.WriteReadBody( "MapLength", "Int64", true, false, isAsync => this.WriteReadLength( "MapLength", isAsync ) ); -this.WriteReadBody( "MapLength", "Int64", true, true, isAsync => this.WriteReadLength( "MapLength", isAsync ) ); - -this.WriteReadBody( "MessagePackExtendedTypeObject", "MessagePackExtendedTypeObject", false, false, isAsync => this.WriteReadExt( isAsync ) ); -this.WriteReadBody( "MessagePackExtendedTypeObject", "MessagePackExtendedTypeObject", false, true, isAsync => this.WriteReadExt( isAsync ) ); -this.WriteReadBody( "MessagePackExtendedTypeObject", "MessagePackExtendedTypeObject", true, false, isAsync => this.WriteReadExt( isAsync ) ); -this.WriteReadBody( "MessagePackExtendedTypeObject", "MessagePackExtendedTypeObject", true, true, isAsync => this.WriteReadExt( isAsync ) ); -this.PopIndent(); -#> - } -} - -<#+ - -private static readonly Type[] ScalarTypes = - new [] - { - typeof( sbyte ), typeof( short ), typeof( int ), typeof( long ), - typeof( byte ), typeof( ushort ), typeof( uint ), typeof( ulong ), - typeof( float ), typeof( double ) - }; - -private static readonly string[] ExtCodes = new [] { "FixExt1", "FixExt2", "FixExt4", "FixExt8", "FixExt16", "Ext8", "Ext16", "Ext32" }; - -private class TypeCodeMapping -{ - public string Code { get; set; } - public Type CodeType { get; set; } - public int Size { get; set; } -} - -private static readonly TypeCodeMapping[] TypeCodeMappings = - new [] - { - "SByte", "Int16", "Int32", "Int64", - "Byte", "UInt16", "UInt32", "UInt64", - "Single", "Double" - }.Zip( ScalarTypes, - ( code, codeType ) => new TypeCodeMapping{ Code = code, CodeType = codeType, Size = Marshal.SizeOf( codeType ) } - ).ToArray(); - -private void WriteReadBody( string typeName, string fullTypeName, bool isForSubtree, bool isAsync, Action bodyWriter ) -{ - if( isAsync ) - { - this.PopIndent(); -#> -#if FEATURE_TAP - -<#+ - this.PushIndent( 2 ); - } - - var firstParameter = ( isForSubtree && typeName == "Object" ) ? "bool isDeep, " : String.Empty; - var firstArgument = ( !isForSubtree && typeName == "Object" ) ? "/* isDeep */true, " : String.Empty; -#> -<#= isForSubtree ? "internal" : "public override" #> <#= isAsync ? ( isForSubtree ? "async " : String.Empty ) + "Task>" : "bool" #> Read<#= isForSubtree ? "Subtree" : String.Empty #><#= typeName #><#= !isAsync ? "( " + firstParameter + "out " + fullTypeName + " result )" : "Async( " + firstParameter + "CancellationToken cancellationToken )" #> -{ -<#+ - if( !isForSubtree ) - { - this.PopIndent(); -#> - this.EnsureNotInSubtreeMode(); -<#+ - this.PushIndent( 2 ); - - if( !isAsync ) - { -#> - return this.ReadSubtree<#= typeName #>( <#= firstArgument #>out result ); -<#+ - } - else - { -#> - return this.ReadSubtree<#= typeName #>Async( <#= firstArgument #>cancellationToken ); -<#+ - } - } - else - { - this.PushIndent( 1 ); - bodyWriter( isAsync ); - this.PopIndent(); - } -#> -} - -<#+ - if( isAsync ) - { - this.PopIndent(); -#> -#endif // FEATURE_TAP - -<#+ - this.PushIndent( 2 ); - } -} // WriteReadBody - -private void WriteReadBodyCore( string typeName, Nullability nullability, Action bodyWriter, bool isAsync ) -{ - var actualTypeName = typeName; - if( nullability == Nullability.Nullable ) - { - actualTypeName += "?"; - } - - if( !isAsync ) - { -#> -byte header; -long integral; -float real32; -double real64; -var type = this.ReadValue( out header, out integral, out real32, out real64 ); -<#+ - } - else - { -#> -var asyncResult = await this.ReadValueAsync( cancellationToken ).ConfigureAwait( false ); -var type = asyncResult.type; -<#+ - } -#> -switch( type ) -{ - case ReadValueResult.Eof: - { -<#+ - this.PushIndent( 2 ); - this.Fail( "result", actualTypeName, isAsync ); - this.PopIndent(); -#> - } -<#+ - if( nullability != Nullability.Value ) - { -#> - case ReadValueResult.Nil: - { -<#+ - this.PushIndent( 2 ); - this.OnReturnScalar(); - this.Success( null, "result", "default( " + actualTypeName + " )", isAsync ); - this.PopIndent(); -#> - } -<#+ - } // if( isNullable ) - - this.PushIndent( 1 ); - bodyWriter( "type", new DecodedVariable( "integral", "real32", "real64", "asyncResult" ), "result", isAsync ); - this.PopIndent(); -#> - default: - { - this.ThrowTypeException( typeof( <#= actualTypeName #> ), <#= !isAsync ? "header" : "asyncResult.header" #> ); - // Never reach -<#+ - this.PushIndent( 2 ); - this.Fail( "result", actualTypeName, isAsync ); - this.PopIndent(); -#> - } -} -<#+ -} // WriteReadBodyCore( Type type, bool isNullable, Action bodyWriter ) - -private void WriteReadScalar( Type type, bool isAsync ) -{ - var nullableUnderlying = Nullable.GetUnderlyingType( type ); - WriteReadBodyCore( ( nullableUnderlying ?? type ).Name, nullableUnderlying != null ? Nullability.Nullable : Nullability.Value, ( t, valueVar, resultVar, isAsync0 ) => WriteReadScalarCore( nullableUnderlying ?? type, nullableUnderlying != null, valueVar, resultVar, isAsync0 ), isAsync ); -} - -private void WriteReadScalarCore( Type type, bool isNullable, DecodedVariable valueVariable, string resultVariable, bool isAsync ) -{ - var nullableType = - ( isNullable && type.IsValueType ) ? type.Name + "?" : null; - - if( type == typeof( bool ) ) - { -#> -case ReadValueResult.Boolean: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.Success( nullableType, resultVariable, valueVariable.Integral( isAsync ) + " != 0", isAsync ); - this.PopIndent(); -#> -} -<#+ - return; // bool is done. - } // if( type == typeof( bool ) ) - - var thisEntry = TypeCodeMappings.SingleOrDefault( e => e.CodeType == type ); - if( thisEntry != null ) - { - // For same type -#> -case ReadValueResult.<#= thisEntry.Code #>: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.Success( nullableType, resultVariable, CastIfNecessary( GetSourceType( type ), type, false, valueVariable.Get( type, isAsync ), false, isAsync ), isAsync ); - this.PopIndent(); -#> -} -<#+ - } // if - - foreach( var entry in TypeCodeMappings.Where( e => CanConvertTo( type, e.Size ) && e.CodeType != type ) ) - { - if ( entry.CodeType == typeof( ulong ) || entry.CodeType == typeof( float ) || entry.CodeType == typeof( double ) ) - { - // UInt64 and Reals should be treated as spetially. - continue; - } -#> -case ReadValueResult.<#= entry.Code #>: -<#+ - } // foreach -#> -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.Success( nullableType, resultVariable, CastIfNecessary( typeof( long ), type, true, valueVariable.Integral( isAsync ), false, isAsync ), isAsync ); - this.PopIndent(); -#> -} -<#+ - - if( type != typeof( ulong ) ) - { -#> -case ReadValueResult.UInt64: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.Success( nullableType, resultVariable, CastIfNecessary( typeof( ulong ), type, true, valueVariable.Integral( isAsync ), true, isAsync ), isAsync ); - this.PopIndent(); -#> -} -<#+ - } - - if( type != typeof( float ) ) - { -#> -case ReadValueResult.Single: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.Success( nullableType, resultVariable, CastIfNecessary( typeof( float ), type, true, valueVariable.Real32( isAsync ), false, isAsync ), isAsync ); - this.PopIndent(); -#> -} -<#+ - } - - if( type != typeof( double ) ) - { -#> -case ReadValueResult.Double: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.Success( nullableType, resultVariable, CastIfNecessary( typeof( double ), type, true, valueVariable.Real64( isAsync ), false, isAsync ), isAsync ); - this.PopIndent(); -#> -} -<#+ - } -} // WriteReadScalarCore( Type type, bool isNullable, DecodedVariable valueVariable, string resultVariable, bool isAsync ) - -private void WriteReadLength( string code, bool isAsync ) -{ - WriteReadBodyCore( "Int64", Nullability.Value, ( t, valueVar, resultVar, isAsync0 ) => this.WriteReadLengthCore( code, valueVar, resultVar, isAsync0 ), isAsync ); -} // WriteReadLength( string code, bool isAsync ) - -private void WriteReadLengthCore( string code, DecodedVariable valueVariable, string resultVariable, bool isAsync ) -{ -#> -case ReadValueResult.<#= code #>: -{ -<#+ - if( isAsync ) - { -#> - // Read<#= code #>Core does not perform I/O, so no Read<#= code #>AsyncCore exists. -<#+ - } - - this.PushIndent( 1 ); - this.SuccessWithLengthCheck( code, resultVariable, "this.Read" + code + "Core( " + valueVariable.Integral( isAsync ) + ")", isAsync ); - this.PopIndent(); -#> -} -<#+ -} // WriteReadLengthCore( string code, string headerVariable, DecodedVariable valueVariable, string resultVariable, bool isAsync ) - - -private void WriteReadRaw( string typeName, string code, bool isAsync ) -{ - WriteReadBodyCore( typeName, Nullability.Reference, ( t, valueVar, resultVar, isAsync0 ) => this.WriteReadRawCore( code, valueVar, resultVar, isAsync0 ), isAsync ); -} // WriteReadRaw( string typeName, string code ) - -private void WriteReadRawCore( string code, DecodedVariable valueVariable, string resultVariable, bool isAsync ) -{ -#> -case ReadValueResult.String: -case ReadValueResult.Binary: -{ -<#+ - this.PushIndent( 1 ); - this.Success( null, resultVariable, Await( isAsync, "this.Read" + code + AsyncSuffix( isAsync ) + "Core( " + valueVariable.Integral( isAsync ) + LastArgument( isAsync ) + " )" ), isAsync ); - this.PopIndent(); -#> -} -<#+ -} // WriteReadRawCore( string code, string headerVariable, DecodedVariable valueVariable, string resultVariable, bool isAsync ) - -private void WriteReadObject( bool isAsync ) -{ - WriteReadBodyCore( "MessagePackObject", Nullability.Value, ( typeVar, valueVar, resultVar, isAsync0 ) => this.WriteReadObjectCore( typeVar, valueVar, resultVar, isAsync0 ), isAsync ); -} // WriteReadObject( bool ) - -private void WriteReadObjectCore( string typeVariable, DecodedVariable valueVariable, string resultVariable, bool isAsync ) -{ -#> -case ReadValueResult.Nil: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.SuccessObject( resultVariable, "MessagePackObject.Nil", isAsync, false ); - this.PopIndent(); -#> -} -case ReadValueResult.Boolean: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.SuccessObject( resultVariable, valueVariable.Integral( isAsync ) + " != 0", isAsync, true ); - this.PopIndent(); -#> -} -<#+ - foreach( var entry in TypeCodeMappings ) - { -#> -case ReadValueResult.<#= entry.Code #>: -{ -<#+ - this.PushIndent( 1 ); - this.OnReturnScalar(); - this.SuccessObject( resultVariable, CastIfNecessary( GetSourceType( entry.CodeType ), entry.CodeType, false, valueVariable.Get( entry.CodeType, isAsync ), false, isAsync ), isAsync, true ); - this.PopIndent(); -#> -} -<#+ - } // foreach -- scalar - -// Array/Map -#> -case ReadValueResult.ArrayLength: -{ -<#+ - if( isAsync ) - { -#> - // ReadArrayLengthCore does not perform I/O, so no ReadArrayLengthAsyncCore exists. -<#+ - } -#> - var length = <#= CastIfNecessary( typeof( long ), typeof( uint ), false, "this.ReadArrayLengthCore( " + valueVariable.Integral( isAsync ) + " )", false, isAsync ) #>; - if ( !isDeep ) - { -<#+ - this.PushIndent( 2 ); - this.SuccessObject( resultVariable, "length", isAsync, true ); - this.PopIndent(); -#> - } - - this.CheckLength( length, ReadValueResult.ArrayLength ); - var collection = new List( unchecked( ( int ) length ) ); - for( var i = 0; i < length; i++ ) - { - MessagePackObject item; - if( !this.ReadSubtreeObject( /* isDeep */true, out item ) ) - { -<#+ - this.PushIndent( 3 ); - this.Fail( resultVariable, "MessagePackObject", isAsync ); - this.PopIndent(); -#> - } - - collection.Add( item ); - } - - { -<#+ - this.PushIndent( 2 ); - this.SuccessObject( resultVariable, "new MessagePackObject( collection, /* isImmutable */true )", isAsync, true ); - this.PopIndent(); -#> - } -} -case ReadValueResult.MapLength: -{ -<#+ - if( isAsync ) - { -#> - // ReadMapLengthCore does not perform I/O, so no ReadMapLengthAsyncCore exists. -<#+ - } -#> - var length = <#= CastIfNecessary( typeof( long ), typeof( uint ), false, "this.ReadMapLengthCore( " + valueVariable.Integral( isAsync ) + " )", false, isAsync ) #>; - if ( !isDeep ) - { -<#+ - this.PushIndent( 2 ); - this.SuccessObject( resultVariable, "length", isAsync, true ); - this.PopIndent(); -#> - } - - this.CheckLength( length, ReadValueResult.MapLength ); - var collection = new MessagePackObjectDictionary( unchecked( ( int ) length ) ); - for( var i = 0; i < length; i++ ) - { - MessagePackObject key; - if( !this.ReadSubtreeObject( /* isDeep */true, out key ) ) - { -<#+ - this.PushIndent( 3 ); - this.Fail( resultVariable, "MessagePackObject", isAsync ); - this.PopIndent(); -#> - } - - MessagePackObject value; - if( !this.ReadSubtreeObject( /* isDeep */true, out value ) ) - { -<#+ - this.PushIndent( 3 ); - this.Fail( resultVariable, "MessagePackObject", isAsync ); - this.PopIndent(); -#> - } - - collection.Add( key, value ); - } - - { -<#+ - this.PushIndent( 2 ); - this.SuccessObject( resultVariable, "new MessagePackObject( collection, /* isImmutable */true )", isAsync, true ); - this.PopIndent(); -#> - } -} - -<#+ -// Array/Map - -#> -case ReadValueResult.String: -{ -<#+ - this.PushIndent( 1 ); - this.SuccessObject( - resultVariable, - "new MessagePackObject( new MessagePackString( " + Await( isAsync, "this.ReadBinary" + AsyncSuffix( isAsync ) + "Core( " + valueVariable.Integral( isAsync ) + LastArgument( isAsync ) + " )" ) + ", false ) )", - isAsync, - false - ); - this.PopIndent(); -#> -} -case ReadValueResult.Binary: -{ -<#+ - this.PushIndent( 1 ); - this.SuccessObject( - resultVariable, - "new MessagePackObject( new MessagePackString( " + Await( isAsync, "this.ReadBinary" + AsyncSuffix( isAsync ) + "Core( " + valueVariable.Integral( isAsync ) + LastArgument( isAsync ) + " )" ) + ", true ) )", - isAsync, - false - ); - this.PopIndent(); -#> -} -<#+ - this.WriteReadExtCore( typeVariable, resultVariable, true, isAsync ); -} // WriteReadObjectCore( string typeVariable, DecodedVariable valueVariable, string resultVariable, bool isAsync ) - - -private void WriteReadExt( bool isAsync ) -{ - WriteReadBodyCore( "MessagePackExtendedTypeObject", Nullability.Value, ( typeVar, v, resultVar, isAsync0 ) => this.WriteReadExtCore( typeVar, resultVar, false, isAsync0 ), isAsync ); -} // WriteReadExt( bool isAsync ) - -private void WriteReadExtCore( string typeVariable, string resultVariable, bool isMpo, bool isAsync ) -{ - - foreach( var code in ExtCodes ) - { -#> -case ReadValueResult.<#= code #>: -<#+ - } // foreach -#> -{ -<#+ - var expression = - Await( isAsync, "this.ReadMessagePackExtendedTypeObject" + AsyncSuffix( isAsync ) + "Core( " + typeVariable + LastArgument( isAsync ) + " )" ); - - this.PushIndent( 1 ); - - if( !isMpo ) - { - this.Success( null, resultVariable, expression, isAsync ); - } - else - { - this.SuccessObject( resultVariable, expression, isAsync, true ); - } - - this.PopIndent(); -#> -} -<#+ -} // WriteReadExtCore( string headerVariable, string resultVariable, bool isAsync ) - - -private void OnReturnScalar() -{ -#> -this.InternalCollectionType = CollectionType.None; -<#+ -} // OnReturnScalar() - - -private bool CanConvertTo( Type destination, int size ) -{ - switch( Type.GetTypeCode( destination ) ) - { - case TypeCode.Single: - case TypeCode.Double: - { - return true; - } - default: - { - return System.Runtime.InteropServices.Marshal.SizeOf( destination ) >= size / 8; - } - } -} // CanConvertTo( Type destination, String source ) - -private static string CastIfNecessary( Type sourceType, Type targetType, bool shouldCheckOverflow, string sourceExpression, bool shouldInsertUInt64Cast, bool isAsync ) -{ - if( sourceType == targetType ) - { - return - shouldInsertUInt64Cast - ? String.Format( CultureInfo.InvariantCulture, "unchecked( ( UInt64 ){0} )", sourceExpression ) - : sourceExpression; - } - - if( !isAsync ) - { - if( sourceType == typeof( float ) ) - { - if( targetType == typeof( double ) ) - { - return sourceExpression; - } - } - else if( sourceType != typeof( double ) ) - { - if( targetType == typeof( long ) ) - { - return - shouldInsertUInt64Cast - ? String.Format( CultureInfo.InvariantCulture, "checked( ( Int64 )( UInt64 ){0} )", sourceExpression ) - : sourceExpression; - } - - if ( targetType == typeof( float ) || targetType == typeof( double ) ) - { - return - shouldInsertUInt64Cast - ? String.Format( CultureInfo.InvariantCulture, "unchecked( ( UInt64 ){0} )", sourceExpression ) - : sourceExpression; - } - } - } - - return String.Format( CultureInfo.InvariantCulture, "{0}( ( {1} ){2}{3} )", ( shouldCheckOverflow ? "checked" : "unchecked" ), targetType.Name, ( shouldInsertUInt64Cast ? "( UInt64 )" : String.Empty ), sourceExpression ); -} // CastIfNecessary( Type sourceType, Type targetType, bool shouldCheckOverflow, string sourceExpression ) - -private static Type GetSourceType( Type targetType ) -{ - return - targetType == typeof( float ) - ? typeof( float ) - : targetType == typeof( double ) - ? typeof( double ) - : typeof( long ); -} - -private void Success( string type, string resultVariable, string expression, bool isAsync ) -{ - if( !isAsync ) - { -#> -<#= resultVariable #> = <#= expression #>; -return true; -<#+ - } - else - { - var typeArgument = - type == null ? String.Empty : "<" + type + ">"; -#> -return AsyncReadResult.Success<#= typeArgument #>( <#= expression #> ); -<#+ - } -} // Sucess( string resultVariable, string expression, bool isAsync ) - -private void SuccessWithLengthCheck( string code, string resultVariable, string expression, bool isAsync ) -{ - if( !isAsync ) - { -#> -<#= resultVariable #> = <#= expression #>; -this.CheckLength( <#= resultVariable #>, ReadValueResult.<#= code #> ); -return true; -<#+ - } - else - { -#> -var result = <#= expression #>; -this.CheckLength( result, ReadValueResult.<#= code #> ); -return AsyncReadResult.Success( result ); -<#+ - } - -#> -<#+ -} // SuccessWithLengthCheck( string type, string resultVariable, string expression, bool isAsync ) - -private void SuccessObject( string resultVariable, string expression, bool isAsync, bool withTypeVariable ) -{ - if( !isAsync ) - { -#> -<#= resultVariable #> = <#= expression #>; -this.InternalData = <#= resultVariable #>; -return true; -<#+ - } - else - { - var typeArgument = - withTypeVariable ? "" : String.Empty; -#> -var result = <#= expression #>; -this.InternalData = result; -return AsyncReadResult.Success<#= typeArgument #>( result ); -<#+ - } - -#> -<#+ -} // SuccessObject( string resultVariable, string expression, bool isAsync ) - -private void Fail( string resultVariable, string typeName, bool isAsync ) -{ - if( !isAsync ) - { -#> -<#= resultVariable #> = default( <#= typeName #> ); -return false; -<#+ - } - else - { -#> -return AsyncReadResult.Fail<#= "<" + typeName + ">" #>(); -<#+ - } -} // Fail( string resultVariable, string typeName, bool isAsync ) - -private static string Await( bool isAsync, string expression ) -{ - return ( isAsync ? "await ": String.Empty ) + expression + ( isAsync ? ".ConfigureAwait( false )" : String.Empty ); -} // Await( bool isAsync, string expression ) - -private static string AsyncSuffix( bool isAsync ) -{ - return isAsync ? "Async": String.Empty; -} // AsyncSuffix( bool isAsync ) - -private static string LastArgument( bool isAsync ) -{ - return isAsync ? ", cancellationToken" : String.Empty; -} // LastArgument( bool isAsync ) - -private enum Nullability -{ - Reference, - Value, - Nullable -} - -private class DecodedVariable -{ - private readonly string _integral; - private readonly string _real32; - private readonly string _real64; - private readonly string _asyncResult; - - public DecodedVariable( string integral, string real32, string real64, string asyncResult ) - { - this._integral = integral; - this._real32 = real32; - this._real64 = real64; - this._asyncResult = asyncResult; - } - - public string Get( Type type, bool isAsync ) - { - if( type == typeof( float ) ) - { - return this.Real32( isAsync ); - } - - if( type == typeof( double ) ) - { - return this.Real64( isAsync ); - } - - return this.Integral( isAsync ); - } - - public string Integral( bool isAsync ) - { - return this.GetVariable( this._integral, isAsync ); - } - - public string Real32( bool isAsync ) - { - return this.GetVariable( this._real32, isAsync ); - } - - public string Real64( bool isAsync ) - { - return this.GetVariable( this._real64, isAsync ); - } - - private string GetVariable( string name, bool isAsync ) - { - return isAsync ? this._asyncResult + "." + name : name; - } -} -#> \ No newline at end of file diff --git a/src/MsgPack/ItemsUnpacker.Skipping.cs b/src/MsgPack/ItemsUnpacker.Skipping.cs deleted file mode 100644 index 087f74d5e..000000000 --- a/src/MsgPack/ItemsUnpacker.Skipping.cs +++ /dev/null @@ -1,2567 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -#if !UNITY || MSGPACK_UNITY_FULL -using Int64Stack = System.Collections.Generic.Stack; -#endif // !UNITY || MSGPACK_UNITY_FULL - -namespace MsgPack -{ - // This file was generated from ItemsUnpacker.Skipping.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit ItemsUnpacker.Skipping.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class ItemsUnpacker - { - protected override long? SkipCore() - { - long remainingItems = -1; - long startOffset = this._offset; - Int64Stack remainingCollections = null; - do - { - var header = this.ReadByteFromSource(); - if ( header < 0 ) - { - return null; - } - - switch ( header ) - { - case MessagePackCode.NilValue: - case MessagePackCode.TrueValue: - case MessagePackCode.FalseValue: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - } - - if ( header < 0x80 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - else if ( header >= 0xE0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - - switch ( header & 0xF0 ) - { - case 0x80: - { - var size = header & 0xF; - if( size == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = size * 2; - - #endregion PushContextCollection - } - - continue; - } - case 0x90: - { - var size = header & 0xF; - if( size == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = size; - - #endregion PushContextCollection - } - - continue; - } - case 0xA0: - case 0xB0: - { - var size = header & 0x1F; - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( size, Int32.MaxValue ) ) ); - while( size > bytesRead ) - { - var remaining = ( size - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - } - - switch ( header ) - { - case MessagePackCode.SignedInt8: - case MessagePackCode.UnsignedInt8: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 1, Int32.MaxValue ) ) ); - while( 1 > bytesRead ) - { - var remaining = ( 1 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.SignedInt16: - case MessagePackCode.UnsignedInt16: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 2, Int32.MaxValue ) ) ); - while( 2 > bytesRead ) - { - var remaining = ( 2 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.SignedInt32: - case MessagePackCode.UnsignedInt32: - case MessagePackCode.Real32: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 4, Int32.MaxValue ) ) ); - while( 4 > bytesRead ) - { - var remaining = ( 4 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.SignedInt64: - case MessagePackCode.UnsignedInt64: - case MessagePackCode.Real64: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 8, Int32.MaxValue ) ) ); - while( 8 > bytesRead ) - { - var remaining = ( 8 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.Str8: - case MessagePackCode.Bin8: - { - byte length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - length = this._scalarBuffer[0]; - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Bin16: - case MessagePackCode.Raw16: - { - ushort length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 2 ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Bin32: - case MessagePackCode.Raw32: - { - uint length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 4 ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Array16: - { - ushort length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 2 ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.Array32: - { - uint length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 4 ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.Map16: - { - ushort length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 2 ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length * 2; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.Map32: - { - uint length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 4 ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length * 2; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.FixExt1: - { - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 1, Int32.MaxValue ) ) ); - while( 1 > bytesRead ) - { - var remaining = ( 1 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt2: - { - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 2, Int32.MaxValue ) ) ); - while( 2 > bytesRead ) - { - var remaining = ( 2 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt4: - { - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 4, Int32.MaxValue ) ) ); - while( 4 > bytesRead ) - { - var remaining = ( 4 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt8: - { - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 8, Int32.MaxValue ) ) ); - while( 8 > bytesRead ) - { - var remaining = ( 8 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt16: - { - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 16, Int32.MaxValue ) ) ); - while( 16 > bytesRead ) - { - var remaining = ( 16 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Ext8: - { - byte length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - length = this._scalarBuffer[0]; - } - else - { - return null; - } - this._lastOffset = this._offset; - read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Ext16: - { - ushort length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 2 ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - this._lastOffset = this._offset; - read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Ext32: - { - uint length; - this._lastOffset = this._offset; - var read = this._source.Read( this._scalarBuffer, 0, 4 ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - this._lastOffset = this._offset; - read = this._source.Read( this._scalarBuffer, 0, 1 ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = this._source.Read( dummyBufferForSkipping, 0, reading ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - default: - { - this.ThrowUnassignedMessageTypeException( header ); - return null; // Never reach - } - } - } while ( remainingItems > 0 ); - - return this._offset - startOffset; - } - -#if FEATURE_TAP - protected override async Task SkipAsyncCore( CancellationToken cancellationToken ) - { - long remainingItems = -1; - long startOffset = this._offset; - Int64Stack remainingCollections = null; - do - { - var header = await this.ReadByteFromSourceAsync( cancellationToken ).ConfigureAwait( false ); - if ( header < 0 ) - { - return null; - } - - switch ( header ) - { - case MessagePackCode.NilValue: - case MessagePackCode.TrueValue: - case MessagePackCode.FalseValue: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - } - - if ( header < 0x80 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - else if ( header >= 0xE0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - - switch ( header & 0xF0 ) - { - case 0x80: - { - var size = header & 0xF; - if( size == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = size * 2; - - #endregion PushContextCollection - } - - continue; - } - case 0x90: - { - var size = header & 0xF; - if( size == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = size; - - #endregion PushContextCollection - } - - continue; - } - case 0xA0: - case 0xB0: - { - var size = header & 0x1F; - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( size, Int32.MaxValue ) ) ); - while( size > bytesRead ) - { - var remaining = ( size - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - } - - switch ( header ) - { - case MessagePackCode.SignedInt8: - case MessagePackCode.UnsignedInt8: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 1, Int32.MaxValue ) ) ); - while( 1 > bytesRead ) - { - var remaining = ( 1 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.SignedInt16: - case MessagePackCode.UnsignedInt16: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 2, Int32.MaxValue ) ) ); - while( 2 > bytesRead ) - { - var remaining = ( 2 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.SignedInt32: - case MessagePackCode.UnsignedInt32: - case MessagePackCode.Real32: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 4, Int32.MaxValue ) ) ); - while( 4 > bytesRead ) - { - var remaining = ( 4 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.SignedInt64: - case MessagePackCode.UnsignedInt64: - case MessagePackCode.Real64: - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 8, Int32.MaxValue ) ) ); - while( 8 > bytesRead ) - { - var remaining = ( 8 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - continue; - } - case MessagePackCode.Str8: - case MessagePackCode.Bin8: - { - byte length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - length = this._scalarBuffer[0]; - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Bin16: - case MessagePackCode.Raw16: - { - ushort length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 2, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Bin32: - case MessagePackCode.Raw32: - { - uint length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 4, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Array16: - { - ushort length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 2, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.Array32: - { - uint length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 4, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.Map16: - { - ushort length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 2, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length * 2; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.Map32: - { - uint length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 4, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - if( length == 0 ) - { - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - } - else - { - #region PushContextCollection - - if( remainingItems >= 0 ) - { - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); - } - - remainingItems = length * 2; - - #endregion PushContextCollection - } - - continue; - } - case MessagePackCode.FixExt1: - { - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 1, Int32.MaxValue ) ) ); - while( 1 > bytesRead ) - { - var remaining = ( 1 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt2: - { - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 2, Int32.MaxValue ) ) ); - while( 2 > bytesRead ) - { - var remaining = ( 2 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt4: - { - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 4, Int32.MaxValue ) ) ); - while( 4 > bytesRead ) - { - var remaining = ( 4 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt8: - { - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 8, Int32.MaxValue ) ) ); - while( 8 > bytesRead ) - { - var remaining = ( 8 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.FixExt16: - { - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( 16, Int32.MaxValue ) ) ); - while( 16 > bytesRead ) - { - var remaining = ( 16 - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Ext8: - { - byte length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - length = this._scalarBuffer[0]; - } - else - { - return null; - } - this._lastOffset = this._offset; - read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Ext16: - { - ushort length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 2, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 2 ) - { - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - } - else - { - return null; - } - this._lastOffset = this._offset; - read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - case MessagePackCode.Ext32: - { - uint length; - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._scalarBuffer, 0, 4, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 4 ) - { - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - } - else - { - return null; - } - this._lastOffset = this._offset; - read = await this._source.ReadAsync( this._scalarBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - this._offset += read; - if ( read == 1 ) - { - } - else - { - return null; - } - #region DrainValue - - long bytesRead = 0; - var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( length, Int32.MaxValue ) ) ); - while( length > bytesRead ) - { - var remaining = ( length - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = await this._source.ReadAsync( dummyBufferForSkipping, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } - } - - #endregion DrainValue - #region TryPopContextCollection - - remainingItems--; - - if( remainingCollections != null ) - { - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } - } - - #endregion TryPopContextCollection - continue; - } - default: - { - this.ThrowUnassignedMessageTypeException( header ); - return null; // Never reach - } - } - } while ( remainingItems > 0 ); - - return this._offset - startOffset; - } - -#endif // FEATURE_TAP - } -} diff --git a/src/MsgPack/ItemsUnpacker.Skipping.tt b/src/MsgPack/ItemsUnpacker.Skipping.tt deleted file mode 100644 index b98b0bf2d..000000000 --- a/src/MsgPack/ItemsUnpacker.Skipping.tt +++ /dev/null @@ -1,628 +0,0 @@ -<#@ template debug="true" hostSpecific="true" language="C#" #> -<#@ output extension=".cs" #> -<#@ include file="..\Core.ttinclude" #> -<#@ Assembly Name="System.Core.dll" #> -<#@ import namespace="System" #> -<#@ import namespace="System.Collections" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.Diagnostics" #> -<#@ import namespace="System.Globalization" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Linq" #> -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -#if !UNITY || MSGPACK_UNITY_FULL -using Int64Stack = System.Collections.Generic.Stack; -#endif // !UNITY || MSGPACK_UNITY_FULL - -namespace MsgPack -{ - // This file was generated from ItemsUnpacker.Skipping.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit ItemsUnpacker.Skipping.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class ItemsUnpacker - { -<# -foreach ( var isAsync in new [] { false, true } ) -{ - if ( isAsync ) - { -#> -#if FEATURE_TAP -<# - } -#> - protected override <#= isAsync ? "async Task" : "long?" #> Skip<#= AsyncSuffix( isAsync ) #>Core(<#= Parameter( isAsync ) #>) - { - long remainingItems = -1; - long startOffset = this._offset; - Int64Stack remainingCollections = null; - do - { - var header = <#= !isAsync ? "this.ReadByteFromSource()" : "await this.ReadByteFromSourceAsync( cancellationToken ).ConfigureAwait( false )" #>; - if ( header < 0 ) - { - return null; - } - - switch ( header ) - { - case MessagePackCode.NilValue: - case MessagePackCode.TrueValue: - case MessagePackCode.FalseValue: - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - } - - if ( header < 0x80 ) - { -<# -this.PushIndent( 5 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - else if ( header >= 0xE0 ) - { -<# -this.PushIndent( 5 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - - switch ( header & 0xF0 ) - { - case 0x80: - { - var size = header & 0xF; - if( size == 0 ) - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - } - else - { -<# -this.PushIndent( 6 ); -this.WritePushCollection( "size * 2" ); -this.PopIndent(); -#> - } - - continue; - } - case 0x90: - { - var size = header & 0xF; - if( size == 0 ) - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - } - else - { -<# -this.PushIndent( 6 ); -this.WritePushCollection( "size" ); -this.PopIndent(); -#> - } - - continue; - } - case 0xA0: - case 0xB0: - { - var size = header & 0x1F; -<# -this.PushIndent( 6 ); -this.WriteDrainValue( "size", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - } - - switch ( header ) - { - case MessagePackCode.SignedInt8: - case MessagePackCode.UnsignedInt8: - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.WriteDrainValue( "1", isAsync ); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.SignedInt16: - case MessagePackCode.UnsignedInt16: - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.WriteDrainValue( "2", isAsync ); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.SignedInt32: - case MessagePackCode.UnsignedInt32: - case MessagePackCode.Real32: - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.WriteDrainValue( "4", isAsync ); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.SignedInt64: - case MessagePackCode.UnsignedInt64: - case MessagePackCode.Real64: - { -<# -this.PushIndent( 6 ); -this.WriteTryPopCollection(); -this.WriteDrainValue( "8", isAsync ); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Str8: - case MessagePackCode.Bin8: - { - byte length; -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( "length", isAsync ); -this.WriteDrainValue( "length", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Bin16: - case MessagePackCode.Raw16: - { - ushort length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 2, "length", isAsync ); -this.WriteDrainValue( "length", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Bin32: - case MessagePackCode.Raw32: - { - uint length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 4, "length", isAsync ); -this.WriteDrainValue( "length", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Array16: - { - ushort length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 2, "length", isAsync ); -this.PopIndent(); -#> - if( length == 0 ) - { -<# -this.PushIndent( 7 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - } - else - { -<# -this.PushIndent( 7 ); -this.WritePushCollection( "length" ); -this.PopIndent(); -#> - } - - continue; - } - case MessagePackCode.Array32: - { - uint length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 4, "length", isAsync ); -this.PopIndent(); -#> - if( length == 0 ) - { -<# -this.PushIndent( 7 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - } - else - { -<# -this.PushIndent( 7 ); -this.WritePushCollection( "length" ); -this.PopIndent(); -#> - } - - continue; - } - case MessagePackCode.Map16: - { - ushort length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 2, "length", isAsync ); -this.PopIndent(); -#> - if( length == 0 ) - { -<# -this.PushIndent( 7 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - } - else - { -<# -this.PushIndent( 7 ); -this.WritePushCollection( "length * 2" ); -this.PopIndent(); -#> - } - - continue; - } - case MessagePackCode.Map32: - { - uint length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 4, "length", isAsync ); -this.PopIndent(); -#> - if( length == 0 ) - { -<# -this.PushIndent( 7 ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - } - else - { -<# -this.PushIndent( 7 ); -this.WritePushCollection( "length * 2" ); -this.PopIndent(); -#> - } - - continue; - } - case MessagePackCode.FixExt1: - { -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( null, isAsync ); -this.WriteDrainValue( "1", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.FixExt2: - { -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( null, isAsync ); -this.WriteDrainValue( "2", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.FixExt4: - { -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( null, isAsync ); -this.WriteDrainValue( "4", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.FixExt8: - { -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( null, isAsync ); -this.WriteDrainValue( "8", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.FixExt16: - { -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( null, isAsync ); -this.WriteDrainValue( "16", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Ext8: - { - byte length; -<# -this.PushIndent( 6 ); -this.WriteUnpackByte( "length", isAsync ); -this.WriteUnpackByteSubsequent( null, isAsync ); -this.WriteDrainValue( "length", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Ext16: - { - ushort length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 2, "length", isAsync ); -this.WriteUnpackByteSubsequent( null, isAsync ); -this.WriteDrainValue( "length", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - case MessagePackCode.Ext32: - { - uint length; -<# -this.PushIndent( 6 ); -this.WriteUnpackLength( 4, "length", isAsync ); -this.WriteUnpackByteSubsequent( null, isAsync ); -this.WriteDrainValue( "length", isAsync ); -this.WriteTryPopCollection(); -this.PopIndent(); -#> - continue; - } - default: - { - this.ThrowUnassignedMessageTypeException( header ); - return null; // Never reach - } - } - } while ( remainingItems > 0 ); - - return this._offset - startOffset; - } - -<# - if ( isAsync ) - { -#> -#endif // FEATURE_TAP -<# - } -} -#> - } -} -<#+ -private void WritePushCollection( string sizeVariable ) -{ -#> -#region PushContextCollection - -if( remainingItems >= 0 ) -{ - if( remainingCollections == null ) - { - remainingCollections = new Int64Stack( 4 ); - } - - remainingCollections.Push( remainingItems ); -} - -remainingItems = <#= sizeVariable #>; - -#endregion PushContextCollection -<#+ -} - -private void WriteTryPopCollection() -{ -#> -#region TryPopContextCollection - -remainingItems--; - -if( remainingCollections != null ) -{ - while ( remainingItems == 0 && remainingCollections.Count > 0 ) - { - if( remainingCollections.Count == 0 ) - { - break; - } - - remainingItems = remainingCollections.Pop(); - remainingItems--; - } -} - -#endregion TryPopContextCollection -<#+ -} - -private void WriteDrainValue( string sizeVariable, bool isAsync ) -{ -#> -#region DrainValue - -long bytesRead = 0; -var dummyBufferForSkipping = BufferManager.NewByteBuffer( unchecked( ( int )Math.Min( <#= sizeVariable #>, Int32.MaxValue ) ) ); -while( <#= sizeVariable #> > bytesRead ) -{ - var remaining = ( <#= sizeVariable #> - bytesRead ); - var reading = remaining > dummyBufferForSkipping.Length ? dummyBufferForSkipping.Length : unchecked( ( int )remaining ); - this._lastOffset = this._offset; - var lastRead = <#= Await( isAsync, "this._source.Read" + AsyncSuffix( isAsync ) + "( dummyBufferForSkipping, 0, reading" + LastArgument( isAsync ) + " )" ) #>; - this._offset += lastRead; - bytesRead += lastRead; - if ( lastRead == 0 ) - { - return null; - } -} - -#endregion DrainValue -<#+ -} - -private void WriteUnpackLength( int size, string lengthVariable, bool isAsync ) -{ -#> -this._lastOffset = this._offset; -var read = <#= Await( isAsync, "this._source.Read" + AsyncSuffix( isAsync ) + "( this._scalarBuffer, 0, " + size.ToString( CultureInfo.InvariantCulture ) + LastArgument( isAsync ) + " )" ) #>; -this._offset += read; -if ( read == <#= size.ToString( CultureInfo.InvariantCulture ) #> ) -{ - <#= lengthVariable #> = BigEndianBinary.ToUInt<#= ( size * 8 ).ToString( CultureInfo.InvariantCulture ) #>( this._scalarBuffer, 0 ); -} -else -{ - return null; -} -<#+ -} - -private void WriteUnpackByte( string lengthVariable, bool isAsync ) -{ - this.WriteUnpackByteCore( lengthVariable, true, isAsync ); -} - -private void WriteUnpackByteSubsequent( string lengthVariable, bool isAsync ) -{ - this.WriteUnpackByteCore( lengthVariable, false, isAsync ); -} - -private void WriteUnpackByteCore( string lengthVariable, bool needsDeclaration, bool isAsync ) -{ -#> -this._lastOffset = this._offset; -<#= needsDeclaration ? "var" : String.Empty #> read = <#= Await( isAsync, "this._source.Read" + AsyncSuffix( isAsync ) + "( this._scalarBuffer, 0, 1" + LastArgument( isAsync ) + " )" ) #>; -this._offset += read; -if ( read == 1 ) -{ -<#+ - if ( lengthVariable != null ) - { -#> - <#= lengthVariable #> = this._scalarBuffer[0]; -<#+ - } -#> -} -else -{ - return null; -} -<#+ -} - -private static string Await( bool isAsync, string expression ) -{ - return ( isAsync ? "await ": String.Empty ) + expression + ( isAsync ? ".ConfigureAwait( false )" : String.Empty ); -} - -private static string AsyncSuffix( bool isAsync ) -{ - return isAsync ? "Async": String.Empty; -} - -private static string Parameter( bool isAsync ) -{ - return isAsync ? " CancellationToken cancellationToken " : String.Empty; -} - -private static string LastArgument( bool isAsync ) -{ - return isAsync ? ", cancellationToken" : String.Empty; -} - -private static string Argument( bool isAsync ) -{ - return isAsync ? " cancellationToken " : String.Empty; -} -#> diff --git a/src/MsgPack/ItemsUnpacker.Unpacking.cs b/src/MsgPack/ItemsUnpacker.Unpacking.cs deleted file mode 100644 index 3f8511ca5..000000000 --- a/src/MsgPack/ItemsUnpacker.Unpacking.cs +++ /dev/null @@ -1,888 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -using System.Text; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - // This file was generated from ItemsUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit ItemsUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class ItemsUnpacker - { - private ReadValueResult ReadValue( out byte header, out long integral, out float real32, out double real64 ) - { - var readHeader = this.ReadByteFromSource(); - // This is BAD practice for out, but it reduces IL size very well for this method. - integral = default( long ); - real32 = default( float ); - real64 = default( double ); - - if ( readHeader < 0 ) - { - header = 0; - return ReadValueResult.Eof; - } - - header = unchecked( ( byte )readHeader ); - - switch ( header >> 4 ) - { - case 0x0: - case 0x1: - case 0x2: - case 0x3: - case 0x4: - case 0x5: - case 0x6: - case 0x7: - { - // PositiveFixNum - this.InternalCollectionType = CollectionType.None; - integral = header; - return ReadValueResult.Byte; - } - case 0x8: - { - // FixMap - integral = header & 0xF; - return ReadValueResult.MapLength; - } - case 0x9: - { - // FixArray - integral = header & 0xF; - return ReadValueResult.ArrayLength; - } - case 0xA: - case 0xB: - { - // FixRaw - integral = header & 0x1F; - return ReadValueResult.String; - } - case 0xE: - case 0xF: - { - // NegativeFixNum - this.InternalCollectionType = CollectionType.None; - integral = header | unchecked( ( long )0xFFFFFFFFFFFFFF00 ); - return ReadValueResult.SByte; - } - } - - switch ( header ) - { - case MessagePackCode.NilValue: - { - return ReadValueResult.Nil; - } - case MessagePackCode.TrueValue: - { - integral = 1; - return ReadValueResult.Boolean; - } - case MessagePackCode.FalseValue: - { - integral = 0; - return ReadValueResult.Boolean; - } - case MessagePackCode.SignedInt8: - { - this.ReadStrict( this._scalarBuffer, sizeof( sbyte ) ); - integral = BigEndianBinary.ToSByte( this._scalarBuffer, 0 ); - return ReadValueResult.SByte; - } - case MessagePackCode.SignedInt16: - { - this.ReadStrict( this._scalarBuffer, sizeof( short ) ); - integral = BigEndianBinary.ToInt16( this._scalarBuffer, 0 ); - return ReadValueResult.Int16; - } - case MessagePackCode.SignedInt32: - { - this.ReadStrict( this._scalarBuffer, sizeof( int ) ); - integral = BigEndianBinary.ToInt32( this._scalarBuffer, 0 ); - return ReadValueResult.Int32; - } - case MessagePackCode.SignedInt64: - { - this.ReadStrict( this._scalarBuffer, sizeof( long ) ); - integral = BigEndianBinary.ToInt64( this._scalarBuffer, 0 ); - return ReadValueResult.Int64; - } - case MessagePackCode.UnsignedInt8: - { - this.ReadStrict( this._scalarBuffer, sizeof( byte ) ); - integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - return ReadValueResult.Byte; - } - case MessagePackCode.UnsignedInt16: - { - this.ReadStrict( this._scalarBuffer, sizeof( ushort ) ); - integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - return ReadValueResult.UInt16; - } - case MessagePackCode.UnsignedInt32: - { - this.ReadStrict( this._scalarBuffer, sizeof( uint ) ); - integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - return ReadValueResult.UInt32; - } - case MessagePackCode.UnsignedInt64: - { - this.ReadStrict( this._scalarBuffer, sizeof( ulong ) ); - integral = unchecked( ( long )BigEndianBinary.ToUInt64( this._scalarBuffer, 0 ) ); - return ReadValueResult.UInt64; - } - case MessagePackCode.Real32: - { - this.ReadStrict( this._scalarBuffer, sizeof( float ) ); - real32 = BigEndianBinary.ToSingle( this._scalarBuffer, 0 ); - return ReadValueResult.Single; - } - case MessagePackCode.Real64: - { - this.ReadStrict( this._scalarBuffer, sizeof( double ) ); - real64 = BigEndianBinary.ToDouble( this._scalarBuffer, 0 ); - return ReadValueResult.Double; - } - case MessagePackCode.Bin8: - { - this.ReadStrict( this._scalarBuffer, sizeof( byte ) ); - integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - return ReadValueResult.Binary; - } - case MessagePackCode.Str8: - { - this.ReadStrict( this._scalarBuffer, sizeof( byte ) ); - integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - return ReadValueResult.String; - } - case MessagePackCode.Bin16: - { - this.ReadStrict( this._scalarBuffer, sizeof( ushort ) ); - integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - return ReadValueResult.Binary; - } - case MessagePackCode.Raw16: - { - this.ReadStrict( this._scalarBuffer, sizeof( ushort ) ); - integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - return ReadValueResult.String; - } - case MessagePackCode.Bin32: - { - this.ReadStrict( this._scalarBuffer, sizeof( uint ) ); - integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - return ReadValueResult.Binary; - } - case MessagePackCode.Raw32: - { - this.ReadStrict( this._scalarBuffer, sizeof( uint ) ); - integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - return ReadValueResult.String; - } - case MessagePackCode.Array16: - { - this.ReadStrict( this._scalarBuffer, sizeof( ushort ) ); - integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - return ReadValueResult.ArrayLength; - } - case MessagePackCode.Array32: - { - this.ReadStrict( this._scalarBuffer, sizeof( uint ) ); - integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - return ReadValueResult.ArrayLength; - } - case MessagePackCode.Map16: - { - this.ReadStrict( this._scalarBuffer, sizeof( ushort ) ); - integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - return ReadValueResult.MapLength; - } - case MessagePackCode.Map32: - { - this.ReadStrict( this._scalarBuffer, sizeof( uint ) ); - integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - return ReadValueResult.MapLength; - } - case MessagePackCode.FixExt1: - { - return ReadValueResult.FixExt1; - } - case MessagePackCode.FixExt2: - { - return ReadValueResult.FixExt2; - } - case MessagePackCode.FixExt4: - { - return ReadValueResult.FixExt4; - } - case MessagePackCode.FixExt8: - { - return ReadValueResult.FixExt8; - } - case MessagePackCode.FixExt16: - { - return ReadValueResult.FixExt16; - } - case MessagePackCode.Ext8: - { - return ReadValueResult.Ext8; - } - case MessagePackCode.Ext16: - { - return ReadValueResult.Ext16; - } - case MessagePackCode.Ext32: - { - return ReadValueResult.Ext32; - } - default: - { - this.ThrowUnassignedMessageTypeException( readHeader ); - // Never reach - return ReadValueResult.Eof; - } - } - } - -#if FEATURE_TAP - - private async Task ReadValueAsync( CancellationToken cancellationToken ) - { - var readHeader = await this.ReadByteFromSourceAsync( cancellationToken ).ConfigureAwait( false ); - var result = default( AsyncReadValueResult ); - - if ( readHeader < 0 ) - { - return result; - } - - var header = unchecked( ( byte )readHeader ); - result.header = header; - - switch ( header >> 4 ) - { - case 0x0: - case 0x1: - case 0x2: - case 0x3: - case 0x4: - case 0x5: - case 0x6: - case 0x7: - { - // PositiveFixNum - this.InternalCollectionType = CollectionType.None; - result.integral = header; - result.type = ReadValueResult.Byte; - return result; - } - case 0x8: - { - // FixMap - result.integral = header & 0xF; - result.type = ReadValueResult.MapLength; - return result; - } - case 0x9: - { - // FixArray - result.integral = header & 0xF; - result.type = ReadValueResult.ArrayLength; - return result; - } - case 0xA: - case 0xB: - { - // FixRaw - result.integral = header & 0x1F; - result.type = ReadValueResult.String; - return result; - } - case 0xE: - case 0xF: - { - // NegativeFixNum - this.InternalCollectionType = CollectionType.None; - result.integral = header | unchecked( ( long )0xFFFFFFFFFFFFFF00 ); - result.type = ReadValueResult.SByte; - return result; - } - } - - switch ( header ) - { - case MessagePackCode.NilValue: - { - result.type = ReadValueResult.Nil; - return result; - } - case MessagePackCode.TrueValue: - { - result.integral = 1; - result.type = ReadValueResult.Boolean; - return result; - } - case MessagePackCode.FalseValue: - { - result.integral = 0; - result.type = ReadValueResult.Boolean; - return result; - } - case MessagePackCode.SignedInt8: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( sbyte ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToSByte( this._scalarBuffer, 0 ); - result.type = ReadValueResult.SByte; - return result; - } - case MessagePackCode.SignedInt16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( short ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToInt16( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Int16; - return result; - } - case MessagePackCode.SignedInt32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( int ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToInt32( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Int32; - return result; - } - case MessagePackCode.SignedInt64: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( long ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToInt64( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Int64; - return result; - } - case MessagePackCode.UnsignedInt8: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( byte ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Byte; - return result; - } - case MessagePackCode.UnsignedInt16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ushort ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - result.type = ReadValueResult.UInt16; - return result; - } - case MessagePackCode.UnsignedInt32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( uint ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - result.type = ReadValueResult.UInt32; - return result; - } - case MessagePackCode.UnsignedInt64: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ulong ), cancellationToken ).ConfigureAwait( false ); - result.integral = unchecked( ( long )BigEndianBinary.ToUInt64( this._scalarBuffer, 0 ) ); - result.type = ReadValueResult.UInt64; - return result; - } - case MessagePackCode.Real32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( float ), cancellationToken ).ConfigureAwait( false ); - result.real32 = BigEndianBinary.ToSingle( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Single; - return result; - } - case MessagePackCode.Real64: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( double ), cancellationToken ).ConfigureAwait( false ); - result.real64 = BigEndianBinary.ToDouble( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Double; - return result; - } - case MessagePackCode.Bin8: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( byte ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Binary; - return result; - } - case MessagePackCode.Str8: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( byte ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - result.type = ReadValueResult.String; - return result; - } - case MessagePackCode.Bin16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ushort ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Binary; - return result; - } - case MessagePackCode.Raw16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ushort ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - result.type = ReadValueResult.String; - return result; - } - case MessagePackCode.Bin32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( uint ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - result.type = ReadValueResult.Binary; - return result; - } - case MessagePackCode.Raw32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( uint ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - result.type = ReadValueResult.String; - return result; - } - case MessagePackCode.Array16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ushort ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - result.type = ReadValueResult.ArrayLength; - return result; - } - case MessagePackCode.Array32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( uint ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - result.type = ReadValueResult.ArrayLength; - return result; - } - case MessagePackCode.Map16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ushort ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - result.type = ReadValueResult.MapLength; - return result; - } - case MessagePackCode.Map32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( uint ), cancellationToken ).ConfigureAwait( false ); - result.integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - result.type = ReadValueResult.MapLength; - return result; - } - case MessagePackCode.FixExt1: - { - result.type = ReadValueResult.FixExt1; - return result; - } - case MessagePackCode.FixExt2: - { - result.type = ReadValueResult.FixExt2; - return result; - } - case MessagePackCode.FixExt4: - { - result.type = ReadValueResult.FixExt4; - return result; - } - case MessagePackCode.FixExt8: - { - result.type = ReadValueResult.FixExt8; - return result; - } - case MessagePackCode.FixExt16: - { - result.type = ReadValueResult.FixExt16; - return result; - } - case MessagePackCode.Ext8: - { - result.type = ReadValueResult.Ext8; - return result; - } - case MessagePackCode.Ext16: - { - result.type = ReadValueResult.Ext16; - return result; - } - case MessagePackCode.Ext32: - { - result.type = ReadValueResult.Ext32; - return result; - } - default: - { - this.ThrowUnassignedMessageTypeException( readHeader ); - // Never reach - result.type = ReadValueResult.Eof; - return result; - } - } - } - -#endif // FEATURE_TAP - - private long ReadArrayLengthCore( long length ) - { - this.InternalCollectionType = CollectionType.Array; - this.InternalItemsCount = length; - this.InternalData = unchecked( ( uint )length ); - return length; - } - - private long ReadMapLengthCore( long length ) - { - this.InternalCollectionType = CollectionType.Map; - this.InternalItemsCount = length; - this.InternalData = unchecked( ( uint )length ); - return length; - } - - private byte[] ReadBinaryCore( long length ) - { - if ( length == 0 ) - { - this.InternalCollectionType = CollectionType.None; - return Binary.Empty; - } - - this.CheckLength( length, ReadValueResult.Binary ); - var buffer = new byte[ length ]; - this.ReadStrict( buffer, buffer.Length ); - this.InternalCollectionType = CollectionType.None; - return buffer; - } - -#if FEATURE_TAP - - private async Task ReadBinaryAsyncCore( long length, CancellationToken cancellationToken ) - { - if ( length == 0 ) - { - this.InternalCollectionType = CollectionType.None; - return Binary.Empty; - } - - this.CheckLength( length, ReadValueResult.Binary ); - var buffer = new byte[ length ]; - await this.ReadStrictAsync( buffer, buffer.Length, cancellationToken ).ConfigureAwait( false ); - this.InternalCollectionType = CollectionType.None; - return buffer; - } - -#endif // FEATURE_TAP - - private string ReadStringCore( long length ) - { - if ( length == 0 ) - { - this.InternalCollectionType = CollectionType.None; - return String.Empty; - } - - this.CheckLength( length, ReadValueResult.String ); - - var length32 = unchecked( ( int )length ); - var bytes = BufferManager.NewByteBuffer( length32 ); - - if ( length32 <= bytes.Length ) - { - this.ReadStrict( bytes, length32 ); - var result = Encoding.UTF8.GetString( bytes, 0, length32 ); - this.InternalCollectionType = CollectionType.None; - return result; - } - - var decoder = Encoding.UTF8.GetDecoder(); - var chars = BufferManager.NewCharBuffer( bytes.Length ); - var stringBuffer = new StringBuilder( length32 ); - var remaining = length32; - do - { - var reading = Math.Min( remaining, bytes.Length ); - this._lastOffset = this._offset; - var bytesRead = this._source.Read( bytes, 0, reading ); - this._offset += bytesRead; - if ( bytesRead == 0 ) - { - this.ThrowEofException( reading ); - } - - remaining -= bytesRead; - - var isCompleted = false; - var bytesOffset = 0; - - while ( !isCompleted ) - { - int bytesUsed; - int charsUsed; - decoder.Convert( - bytes, - bytesOffset, - bytesRead - bytesOffset, - chars, - 0, - chars.Length, - ( bytesRead == 0 ), - // flush when last read. - out bytesUsed, - out charsUsed, - out isCompleted - ); - - stringBuffer.Append( chars, 0, charsUsed ); - bytesOffset += bytesUsed; - } - } while ( remaining > 0 ); - - this.InternalCollectionType = CollectionType.None; - return stringBuffer.ToString(); - } - -#if FEATURE_TAP - - private async Task ReadStringAsyncCore( long length, CancellationToken cancellationToken ) - { - if ( length == 0 ) - { - this.InternalCollectionType = CollectionType.None; - return String.Empty; - } - - this.CheckLength( length, ReadValueResult.String ); - - var length32 = unchecked( ( int )length ); - var bytes = BufferManager.NewByteBuffer( length32 ); - - if ( length32 <= bytes.Length ) - { - await this.ReadStrictAsync( bytes, length32, cancellationToken ).ConfigureAwait( false ); - var result = Encoding.UTF8.GetString( bytes, 0, length32 ); - this.InternalCollectionType = CollectionType.None; - return result; - } - - var decoder = Encoding.UTF8.GetDecoder(); - var chars = BufferManager.NewCharBuffer( bytes.Length ); - var stringBuffer = new StringBuilder( length32 ); - var remaining = length32; - do - { - var reading = Math.Min( remaining, bytes.Length ); - this._lastOffset = this._offset; - var bytesRead = await this._source.ReadAsync( bytes, 0, reading, cancellationToken ).ConfigureAwait( false ); - this._offset += bytesRead; - if ( bytesRead == 0 ) - { - this.ThrowEofException( reading ); - } - - remaining -= bytesRead; - - var isCompleted = false; - var bytesOffset = 0; - - while ( !isCompleted ) - { - int bytesUsed; - int charsUsed; - decoder.Convert( - bytes, - bytesOffset, - bytesRead - bytesOffset, - chars, - 0, - chars.Length, - ( bytesRead == 0 ), - // flush when last read. - out bytesUsed, - out charsUsed, - out isCompleted - ); - - stringBuffer.Append( chars, 0, charsUsed ); - bytesOffset += bytesUsed; - } - } while ( remaining > 0 ); - - this.InternalCollectionType = CollectionType.None; - return stringBuffer.ToString(); - } - -#endif // FEATURE_TAP - - private MessagePackExtendedTypeObject ReadMessagePackExtendedTypeObjectCore( ReadValueResult type ) - { - byte typeCode; - uint length; - switch ( type ) - { - case ReadValueResult.FixExt1: - { - typeCode = this.ReadByteStrict(); - length = 1; - break; - } - case ReadValueResult.FixExt2: - { - typeCode = this.ReadByteStrict(); - length = 2; - break; - } - case ReadValueResult.FixExt4: - { - typeCode = this.ReadByteStrict(); - length = 4; - break; - } - case ReadValueResult.FixExt8: - { - typeCode = this.ReadByteStrict(); - length = 8; - break; - } - case ReadValueResult.FixExt16: - { - typeCode = this.ReadByteStrict(); - length = 16; - break; - } - case ReadValueResult.Ext8: - { - this.ReadStrict( this._scalarBuffer, sizeof( byte ) ); - length = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - case ReadValueResult.Ext16: - { - this.ReadStrict( this._scalarBuffer, sizeof( ushort ) ); - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - case ReadValueResult.Ext32: - { - this.ReadStrict( this._scalarBuffer, sizeof( uint ) ); - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - default: - { - this.ThrowUnexpectedExtCodeException( type ); - return default( MessagePackExtendedTypeObject ); // Never reach - } - } - - var data = new byte[ length ]; - this.ReadStrict( data, data.Length ); - this.InternalCollectionType = CollectionType.None; - return new MessagePackExtendedTypeObject( typeCode, data ); - } - -#if FEATURE_TAP - - private async Task ReadMessagePackExtendedTypeObjectAsyncCore( ReadValueResult type, CancellationToken cancellationToken ) - { - byte typeCode; - uint length; - switch ( type ) - { - case ReadValueResult.FixExt1: - { - typeCode = await this.ReadByteStrictAsync( cancellationToken ).ConfigureAwait( false ); - length = 1; - break; - } - case ReadValueResult.FixExt2: - { - typeCode = await this.ReadByteStrictAsync( cancellationToken ).ConfigureAwait( false ); - length = 2; - break; - } - case ReadValueResult.FixExt4: - { - typeCode = await this.ReadByteStrictAsync( cancellationToken ).ConfigureAwait( false ); - length = 4; - break; - } - case ReadValueResult.FixExt8: - { - typeCode = await this.ReadByteStrictAsync( cancellationToken ).ConfigureAwait( false ); - length = 8; - break; - } - case ReadValueResult.FixExt16: - { - typeCode = await this.ReadByteStrictAsync( cancellationToken ).ConfigureAwait( false ); - length = 16; - break; - } - case ReadValueResult.Ext8: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( byte ), cancellationToken ).ConfigureAwait( false ); - length = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - case ReadValueResult.Ext16: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( ushort ), cancellationToken ).ConfigureAwait( false ); - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - case ReadValueResult.Ext32: - { - await this.ReadStrictAsync( this._scalarBuffer, sizeof( uint ), cancellationToken ).ConfigureAwait( false ); - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - default: - { - this.ThrowUnexpectedExtCodeException( type ); - return default( MessagePackExtendedTypeObject ); // Never reach - } - } - - var data = new byte[ length ]; - await this.ReadStrictAsync( data, data.Length, cancellationToken ).ConfigureAwait( false ); - this.InternalCollectionType = CollectionType.None; - return new MessagePackExtendedTypeObject( typeCode, data ); - } - -#endif // FEATURE_TAP - - } -} diff --git a/src/MsgPack/ItemsUnpacker.Unpacking.tt b/src/MsgPack/ItemsUnpacker.Unpacking.tt deleted file mode 100644 index 095c4a619..000000000 --- a/src/MsgPack/ItemsUnpacker.Unpacking.tt +++ /dev/null @@ -1,740 +0,0 @@ -<#@ template debug="true" hostSpecific="true" language="C#" #> -<#@ output extension=".cs" #> -<#@ Assembly Name="System.Core.dll" #> -<#@ include file="..\Core.ttinclude" #> -<#@ import namespace="System" #> -<#@ import namespace="System.Collections" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Diagnostics" #> -<#@ import namespace="System.Globalization" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Runtime.InteropServices" #> -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -using System.Text; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - // This file was generated from ItemsUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit ItemsUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class ItemsUnpacker - { -<# -foreach ( var isAsync in new [] { false, true } ) -{ - var asyncPrefix = isAsync ? "result." : String.Empty; - - if ( !isAsync ) - { -#> - private ReadValueResult ReadValue( out byte header, out long integral, out float real32, out double real64 ) - { - var readHeader = this.ReadByteFromSource(); -<# - } - else - { -#> -#if FEATURE_TAP - - private async Task ReadValueAsync( CancellationToken cancellationToken ) - { - var readHeader = await this.ReadByteFromSourceAsync( cancellationToken ).ConfigureAwait( false ); -<# - } - - if ( !isAsync ) - { -#> - // This is BAD practice for out, but it reduces IL size very well for this method. - integral = default( long ); - real32 = default( float ); - real64 = default( double ); -<# - } - else - { -#> - var result = default( AsyncReadValueResult ); -<# - } -#> - - if ( readHeader < 0 ) - { -<# - if ( !isAsync ) - { -#> - header = 0; - return ReadValueResult.Eof; -<# - } - else - { -#> - return result; -<# - } -#> - } - -<# - if ( !isAsync ) - { -#> - header = unchecked( ( byte )readHeader ); -<# - } - else - { -#> - var header = unchecked( ( byte )readHeader ); - result.header = header; -<# - } -#> - - switch ( header >> 4 ) - { - case 0x0: - case 0x1: - case 0x2: - case 0x3: - case 0x4: - case 0x5: - case 0x6: - case 0x7: - { - // PositiveFixNum - this.InternalCollectionType = CollectionType.None; - <#= asyncPrefix #>integral = header; -<# - ReturnValue( "Byte", isAsync ); -#> - } - case 0x8: - { - // FixMap - <#= asyncPrefix #>integral = header & 0xF; -<# - ReturnValue( "MapLength", isAsync ); -#> - } - case 0x9: - { - // FixArray - <#= asyncPrefix #>integral = header & 0xF; -<# - ReturnValue( "ArrayLength", isAsync ); -#> - } - case 0xA: - case 0xB: - { - // FixRaw - <#= asyncPrefix #>integral = header & 0x1F; -<# - ReturnValue( "String", isAsync ); -#> - } - case 0xE: - case 0xF: - { - // NegativeFixNum - this.InternalCollectionType = CollectionType.None; - <#= asyncPrefix #>integral = header | unchecked( ( long )0xFFFFFFFFFFFFFF00 ); -<# - ReturnValue( "SByte", isAsync ); -#> - } - } - - switch ( header ) - { - case MessagePackCode.NilValue: - { -<# - ReturnValue( "Nil", isAsync ); -#> - } - case MessagePackCode.TrueValue: - { - <#= asyncPrefix #>integral = 1; -<# - ReturnValue( "Boolean", isAsync ); -#> - } - case MessagePackCode.FalseValue: - { - <#= asyncPrefix #>integral = 0; -<# - ReturnValue( "Boolean", isAsync ); -#> - } - case MessagePackCode.SignedInt8: - { - <#= ReadStrict( "sbyte", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToSByte( this._scalarBuffer, 0 ); -<# - ReturnValue( "SByte", isAsync ); -#> - } - case MessagePackCode.SignedInt16: - { - <#= ReadStrict( "short", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToInt16( this._scalarBuffer, 0 ); -<# - ReturnValue( "Int16", isAsync ); -#> - } - case MessagePackCode.SignedInt32: - { - <#= ReadStrict( "int", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToInt32( this._scalarBuffer, 0 ); -<# - ReturnValue( "Int32", isAsync ); -#> - } - case MessagePackCode.SignedInt64: - { - <#= ReadStrict( "long", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToInt64( this._scalarBuffer, 0 ); -<# - ReturnValue( "Int64", isAsync ); -#> - } - case MessagePackCode.UnsignedInt8: - { - <#= ReadStrict( "byte", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); -<# - ReturnValue( "Byte", isAsync ); -#> - } - case MessagePackCode.UnsignedInt16: - { - <#= ReadStrict( "ushort", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); -<# - ReturnValue( "UInt16", isAsync ); -#> - } - case MessagePackCode.UnsignedInt32: - { - <#= ReadStrict( "uint", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); -<# - ReturnValue( "UInt32", isAsync ); -#> - } - case MessagePackCode.UnsignedInt64: - { - <#= ReadStrict( "ulong", isAsync ) #>; - <#= asyncPrefix #>integral = unchecked( ( long )BigEndianBinary.ToUInt64( this._scalarBuffer, 0 ) ); -<# - ReturnValue( "UInt64", isAsync ); -#> - } - case MessagePackCode.Real32: - { - <#= ReadStrict( "float", isAsync ) #>; - <#= asyncPrefix #>real32 = BigEndianBinary.ToSingle( this._scalarBuffer, 0 ); -<# - ReturnValue( "Single", isAsync ); -#> - } - case MessagePackCode.Real64: - { - <#= ReadStrict( "double", isAsync ) #>; - <#= asyncPrefix #>real64 = BigEndianBinary.ToDouble( this._scalarBuffer, 0 ); -<# - ReturnValue( "Double", isAsync ); -#> - } - case MessagePackCode.Bin8: - { - <#= ReadStrict( "byte", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); -<# - ReturnValue( "Binary", isAsync ); -#> - } - case MessagePackCode.Str8: - { - <#= ReadStrict( "byte", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); -<# - ReturnValue( "String", isAsync ); -#> - } - case MessagePackCode.Bin16: - { - <#= ReadStrict( "ushort", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); -<# - ReturnValue( "Binary", isAsync ); -#> - } - case MessagePackCode.Raw16: - { - <#= ReadStrict( "ushort", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); -<# - ReturnValue( "String", isAsync ); -#> - } - case MessagePackCode.Bin32: - { - <#= ReadStrict( "uint", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); -<# - ReturnValue( "Binary", isAsync ); -#> - } - case MessagePackCode.Raw32: - { - <#= ReadStrict( "uint", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); -<# - ReturnValue( "String", isAsync ); -#> - } - case MessagePackCode.Array16: - { - <#= ReadStrict( "ushort", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); -<# - ReturnValue( "ArrayLength", isAsync ); -#> - } - case MessagePackCode.Array32: - { - <#= ReadStrict( "uint", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); -<# - ReturnValue( "ArrayLength", isAsync ); -#> - } - case MessagePackCode.Map16: - { - <#= ReadStrict( "ushort", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); -<# - ReturnValue( "MapLength", isAsync ); -#> - } - case MessagePackCode.Map32: - { - <#= ReadStrict( "uint", isAsync ) #>; - <#= asyncPrefix #>integral = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); -<# - ReturnValue( "MapLength", isAsync ); -#> - } - case MessagePackCode.FixExt1: - { -<# - ReturnValue( "FixExt1", isAsync ); -#> - } - case MessagePackCode.FixExt2: - { -<# - ReturnValue( "FixExt2", isAsync ); -#> - } - case MessagePackCode.FixExt4: - { -<# - ReturnValue( "FixExt4", isAsync ); -#> - } - case MessagePackCode.FixExt8: - { -<# - ReturnValue( "FixExt8", isAsync ); -#> - } - case MessagePackCode.FixExt16: - { -<# - ReturnValue( "FixExt16", isAsync ); -#> - } - case MessagePackCode.Ext8: - { -<# - ReturnValue( "Ext8", isAsync ); -#> - } - case MessagePackCode.Ext16: - { -<# - ReturnValue( "Ext16", isAsync ); -#> - } - case MessagePackCode.Ext32: - { -<# - ReturnValue( "Ext32", isAsync ); -#> - } - default: - { - this.ThrowUnassignedMessageTypeException( readHeader ); - // Never reach -<# - ReturnValue( "Eof", isAsync ); -#> - } - } - } - -<# - if ( isAsync ) - { -#> -#endif // FEATURE_TAP -<# - } -} -#> - - private long ReadArrayLengthCore( long length ) - { - this.InternalCollectionType = CollectionType.Array; - this.InternalItemsCount = length; - this.InternalData = unchecked( ( uint )length ); - return length; - } - - private long ReadMapLengthCore( long length ) - { - this.InternalCollectionType = CollectionType.Map; - this.InternalItemsCount = length; - this.InternalData = unchecked( ( uint )length ); - return length; - } - -<# -foreach ( var isAsync in new [] { false, true } ) -{ - if ( isAsync ) - { -#> -#if FEATURE_TAP - -<# - } -#> - private <#= AsyncReturnValue( "byte[]", isAsync ) #> ReadBinary<#= AsyncSuffix( isAsync ) #>Core( long length<#= Parameter( isAsync ) #> ) - { - if ( length == 0 ) - { - this.InternalCollectionType = CollectionType.None; - return Binary.Empty; - } - - this.CheckLength( length, ReadValueResult.Binary ); - var buffer = new byte[ length ]; - <#= Await( isAsync, "this.ReadStrict" + AsyncSuffix( isAsync ) + "( buffer, buffer.Length" + LastArgument( isAsync ) + " )" ) #>; - this.InternalCollectionType = CollectionType.None; - return buffer; - } - -<# - if ( isAsync ) - { -#> -#endif // FEATURE_TAP -<# - } -} -#> - -<# -foreach ( var isAsync in new [] { false, true } ) -{ - if ( isAsync ) - { -#> -#if FEATURE_TAP - -<# - } -#> - private <#= AsyncReturnValue( "string", isAsync ) #> ReadString<#= AsyncSuffix( isAsync ) #>Core( long length<#= Parameter( isAsync ) #> ) - { - if ( length == 0 ) - { - this.InternalCollectionType = CollectionType.None; - return String.Empty; - } - - this.CheckLength( length, ReadValueResult.String ); - - var length32 = unchecked( ( int )length ); - var bytes = BufferManager.NewByteBuffer( length32 ); - - if ( length32 <= bytes.Length ) - { - <#= Await( isAsync, "this.ReadStrict" + AsyncSuffix( isAsync ) + "( bytes, length32" + LastArgument( isAsync ) + " )" ) #>; - var result = Encoding.UTF8.GetString( bytes, 0, length32 ); - this.InternalCollectionType = CollectionType.None; - return result; - } - - var decoder = Encoding.UTF8.GetDecoder(); - var chars = BufferManager.NewCharBuffer( bytes.Length ); - var stringBuffer = new StringBuilder( length32 ); - var remaining = length32; - do - { - var reading = Math.Min( remaining, bytes.Length ); - this._lastOffset = this._offset; - var bytesRead = <#= Await( isAsync, "this._source.Read" + AsyncSuffix( isAsync ) + "( bytes, 0, reading" + LastArgument( isAsync ) + " )" ) #>; - this._offset += bytesRead; - if ( bytesRead == 0 ) - { - this.ThrowEofException( reading ); - } - - remaining -= bytesRead; - - var isCompleted = false; - var bytesOffset = 0; - - while ( !isCompleted ) - { - int bytesUsed; - int charsUsed; - decoder.Convert( - bytes, - bytesOffset, - bytesRead - bytesOffset, - chars, - 0, - chars.Length, - ( bytesRead == 0 ), - // flush when last read. - out bytesUsed, - out charsUsed, - out isCompleted - ); - - stringBuffer.Append( chars, 0, charsUsed ); - bytesOffset += bytesUsed; - } - } while ( remaining > 0 ); - - this.InternalCollectionType = CollectionType.None; - return stringBuffer.ToString(); - } - -<# - if ( isAsync ) - { -#> -#endif // FEATURE_TAP - -<# - } -} - -foreach ( var isAsync in new [] { false, true } ) -{ - if ( isAsync ) - { -#> -#if FEATURE_TAP - -<# - } -#> - private <#= AsyncReturnValue( "MessagePackExtendedTypeObject", isAsync ) #> ReadMessagePackExtendedTypeObject<#= AsyncSuffix( isAsync ) #>Core( ReadValueResult type<#= Parameter( isAsync ) #> ) - { - byte typeCode; - uint length; - switch ( type ) - { - case ReadValueResult.FixExt1: - { - typeCode = <#= ReadByteStrict( isAsync ) #>; - length = 1; - break; - } - case ReadValueResult.FixExt2: - { - typeCode = <#= ReadByteStrict( isAsync ) #>; - length = 2; - break; - } - case ReadValueResult.FixExt4: - { - typeCode = <#= ReadByteStrict( isAsync ) #>; - length = 4; - break; - } - case ReadValueResult.FixExt8: - { - typeCode = <#= ReadByteStrict( isAsync ) #>; - length = 8; - break; - } - case ReadValueResult.FixExt16: - { - typeCode = <#= ReadByteStrict( isAsync ) #>; - length = 16; - break; - } - case ReadValueResult.Ext8: - { - <#= ReadStrict( "byte", isAsync ) #>; - length = BigEndianBinary.ToByte( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - case ReadValueResult.Ext16: - { - <#= ReadStrict( "ushort", isAsync ) #>; - length = BigEndianBinary.ToUInt16( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - case ReadValueResult.Ext32: - { - <#= ReadStrict( "uint", isAsync ) #>; - length = BigEndianBinary.ToUInt32( this._scalarBuffer, 0 ); - typeCode = this.ReadByteStrict(); - break; - } - default: - { - this.ThrowUnexpectedExtCodeException( type ); - return default( MessagePackExtendedTypeObject ); // Never reach - } - } - - var data = new byte[ length ]; -<# - if ( !isAsync ) - { -#> - this.ReadStrict( data, data.Length ); -<# - } - else - { -#> - await this.ReadStrictAsync( data, data.Length, cancellationToken ).ConfigureAwait( false ); -<# - } -#> - this.InternalCollectionType = CollectionType.None; - return new MessagePackExtendedTypeObject( typeCode, data ); - } - -<# - if ( isAsync ) - { -#> -#endif // FEATURE_TAP - -<# - } -} -#> - } -} -<#+ -private static string ReadStrict( string type, bool isAsync ) -{ - return - ( isAsync ? "await this.ReadStrictAsync" : "this.ReadStrict" ) + - "( this._scalarBuffer, sizeof( " + type + " )" + - ( isAsync ? ", cancellationToken ).ConfigureAwait( false )" : " )" ); -} - -private static string ReadByteStrict( bool isAsync ) -{ - return isAsync ? "await this.ReadByteStrictAsync( cancellationToken ).ConfigureAwait( false )" : "this.ReadByteStrict()"; -} - - -private void ReturnValue( string type, bool isAsync ) -{ - if( !isAsync ) - { -#> - return ReadValueResult.<#= type #>; -<#+ - } - else - { -#> - result.type = ReadValueResult.<#= type #>; - return result; -<#+ - } -} - -private static string Await( bool isAsync, string expression ) -{ - return ( isAsync ? "await ": String.Empty ) + expression + ( isAsync ? ".ConfigureAwait( false )" : String.Empty ); -} - -private static string AsyncSuffix( bool isAsync ) -{ - return isAsync ? "Async": String.Empty; -} - -private static string AsyncReturnValue( string type, bool isAsync ) -{ - return ( isAsync ? "async Task<" : String.Empty ) + type + ( isAsync ? ">" : String.Empty ); -} - -private static string Parameter( bool isAsync ) -{ - return isAsync ? ", CancellationToken cancellationToken" : String.Empty; -} - -private static string LastArgument( bool isAsync ) -{ - return isAsync ? ", cancellationToken" : String.Empty; -} - -private static string Argument( bool isAsync ) -{ - return isAsync ? " cancellationToken " : String.Empty; -} -#> \ No newline at end of file diff --git a/src/MsgPack/ItemsUnpacker.cs b/src/MsgPack/ItemsUnpacker.cs deleted file mode 100644 index efd51a46f..000000000 --- a/src/MsgPack/ItemsUnpacker.cs +++ /dev/null @@ -1,605 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -#if DEBUG -#if CORE_CLR || UNITY -using Contract = MsgPack.MPContract; -#else -using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY -#endif // DEBUG -using System.Globalization; -using System.IO; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - internal sealed partial class ItemsUnpacker : Unpacker - { - private readonly bool _ownsStream; - private readonly bool _useStreamPosition; - private readonly Stream _source; - - private readonly byte[] _oneByteBuffer = new byte[ 1 ]; - private readonly byte[] _scalarBuffer = new byte[ 8 ]; - - internal long InternalItemsCount; - internal CollectionType InternalCollectionType; - internal MessagePackObject InternalData; - - [Obsolete( "Consumer should not use this property. Query LastReadData instead." )] - public override MessagePackObject? Data - { - get { return this.InternalData; } - protected set { this.InternalData = value.GetValueOrDefault(); } - } - - public override MessagePackObject LastReadData - { - get { return this.InternalData; } - protected set { this.InternalData = value; } - } - - public override bool IsArrayHeader - { - get { return this.InternalCollectionType == CollectionType.Array; } - } - - public override bool IsMapHeader - { - get { return this.InternalCollectionType == CollectionType.Map; } - } - - public override bool IsCollectionHeader - { - get { return this.InternalCollectionType != CollectionType.None; } - } - - public override long ItemsCount - { - get { return this.InternalCollectionType != CollectionType.None ? this.InternalItemsCount : 0L; } - } - - protected override Stream UnderlyingStream - { - get { return this._source; } - } - -#if DEBUG - internal override long? UnderlyingStreamPosition - { - get { return this.UnderlyingStream.Position; } - } -#endif - - internal override bool GetPreviousPosition( out long offsetOrPosition ) - { - offsetOrPosition = this._lastOffset; - return this._useStreamPosition; - } - - /// - /// An position of seekable or offset from start of this instance. - /// - private long _offset; - - /// - /// An position of seekable or offset from start of this instance before last operation. - /// - private long _lastOffset; - - public ItemsUnpacker( Stream stream, PackerUnpackerStreamOptions streamOptions ) - { - if ( stream == null ) - { - throw new ArgumentNullException( "stream" ); - } - - var options = streamOptions ?? PackerUnpackerStreamOptions.None; - this._source = options.WrapStream( stream ); - this._ownsStream = options.OwnsStream; - this._useStreamPosition = stream.CanSeek; - this._offset = this._useStreamPosition ? stream.Position : 0L; - } - - protected override void Dispose( bool disposing ) - { - if ( disposing ) - { - if ( this._ownsStream ) - { - this._source.Dispose(); - } - } - - base.Dispose( disposing ); - } - - protected override bool ReadCore() - { - MessagePackObject value; - var success = this.ReadSubtreeObject( /* isDeep */false, out value ); - if ( success ) - { - this.InternalData = value; - return true; - } - else - { - return false; - } - } - -#if FEATURE_TAP - - protected override async Task ReadAsyncCore( CancellationToken cancellationToken ) - { - var result = await this.ReadSubtreeObjectAsync( /* isDeep */false, cancellationToken ).ConfigureAwait( false ); - if ( result.Success ) - { - this.InternalData = result.Value; - return true; - } - else - { - return false; - } - } - -#endif // FEATURE_TAP - - /// - /// Starts unpacking of current subtree. - /// - /// - /// to unpack current subtree. - /// This will not be null. - /// - protected override Unpacker ReadSubtreeCore() - { - return new SubtreeUnpacker( this ); - } - - /// - /// Read subtree item from current stream. - /// - /// - /// true, if position is sucessfully move to next entry; - /// false, if position reaches the tail of the Message Pack stream. - /// - /// - /// This method only be called from . - /// - internal bool ReadSubtreeItem() - { - return this.ReadCore(); - } - -#if FEATURE_TAP - - internal Task ReadSubtreeItemAsync( CancellationToken cancellationToken ) - { - return this.ReadAsyncCore( cancellationToken ); - } - -#endif // FEATURE_TAP - - internal long? SkipSubtreeItem() - { - return this.SkipCore(); - } - -#if FEATURE_TAP - - internal Task SkipSubtreeItemAsync( CancellationToken cancellationToken ) - { - return this.SkipAsyncCore( cancellationToken ); - } - -#endif // FEATURE_TAP - - private void ReadStrict( byte[] buffer, int size ) - { -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - - // Reading 0 byte from stream causes exception in some implementation (issue #60, reported from @odyth). - if ( size == 0 ) - { - return; - } - - this._lastOffset = this._offset; - var remaining = size; - var offset = 0; - int read; - - do - { - read = this._source.Read( buffer, offset, remaining ); - remaining -= read; - offset += read; - } while ( read > 0 && remaining > 0 ); - - this._offset += offset; -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - - if ( offset < size ) - { - this.ThrowEofException( size ); - } - } - -#if FEATURE_TAP - - private async Task ReadStrictAsync( byte[] buffer, int size, CancellationToken cancellationToken ) - { -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - // Reading 0 byte from stream causes exception in some implementation (issue #60, reported from @odyth). - if ( size == 0 ) - { - return; - } - - this._lastOffset = this._offset; - var remaining = size; - var offset = 0; - int read; - - do - { - read = await this._source.ReadAsync( buffer, offset, remaining, cancellationToken ).ConfigureAwait( false ); - remaining -= read; - offset += read; - } while ( read > 0 && remaining > 0 ); - - this._offset += offset; -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - - if ( offset < size ) - { - this.ThrowEofException( size ); - } - } - -#endif // FEATURE_TAP - - private int ReadByteFromSource() - { - this._lastOffset = this._offset; -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - var read = this._source.Read( this._oneByteBuffer, 0, 1 ); - if ( read > 0 ) - { - this._offset++; - } - -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - return read == 0 ? -1 : this._oneByteBuffer[ 0 ]; - } - - private byte ReadByteStrict() - { -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - this._lastOffset = this._offset; - var read = this._source.Read( this._oneByteBuffer, 0, 1 ); - if ( read == 0 ) - { - this.ThrowEofException( 1 ); - } - - this._offset++; -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - return this._oneByteBuffer[ 0 ]; - } - -#if FEATURE_TAP - - private async Task ReadByteFromSourceAsync( CancellationToken cancellationToken ) - { - this._lastOffset = this._offset; -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - var read = await this._source.ReadAsync( this._oneByteBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - if ( read > 0 ) - { - this._offset++; - } - -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - return read == 0 ? -1 : this._oneByteBuffer[ 0 ]; - } - - private async Task ReadByteStrictAsync( CancellationToken cancellationToken ) - { -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - this._lastOffset = this._offset; - var read = await this._source.ReadAsync( this._oneByteBuffer, 0, 1, cancellationToken ).ConfigureAwait( false ); - if ( read == 0 ) - { - this.ThrowEofException( 1 ); - } - - this._offset++; -#if DEBUG - if ( this._source.CanSeek ) - { - Contract.Assert( this._source.Position == this._offset, this._source.Position + "==" + this._offset ); - } -#endif // DEBUG - return this._oneByteBuffer[ 0 ]; - } - -#endif // FEATURE_TAP - - internal override void ThrowEofException() - { - long offsetOrPosition; - var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); - throw new InvalidMessagePackStreamException( - String.Format( - CultureInfo.CurrentCulture, - isRealOffset - ? "Stream unexpectedly ends. Cannot read object from stream. Current position is {0:#,0}." - : "Stream unexpectedly ends. Cannot read object from stream. Current offset is {0:#,0}.", - offsetOrPosition - ) - ); - } - - private void ThrowEofException( long reading ) - { - long offsetOrPosition; - var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); - throw new InvalidMessagePackStreamException( - String.Format( - CultureInfo.CurrentCulture, - isRealOffset - ? "Stream unexpectedly ends. Cannot read {0:#,0} bytes from stream at position {1:#,0}." - : "Stream unexpectedly ends. Cannot read {0:#,0} bytes from stream at offset {1:#,0}.", - reading, - offsetOrPosition - ) - ); - } - - private void ThrowUnassignedMessageTypeException( int header ) - { -#if DEBUG - Contract.Assert( header == 0xC1, "Unhandled header:" + header.ToString( "X2" ) ); -#endif // DEBUG - long offsetOrPosition; - var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); - throw new UnassignedMessageTypeException( - String.Format( - CultureInfo.CurrentCulture, - isRealOffset - ? "Unknown header value 0x{0:X} at position {1:#,0}" - : "Unknown header value 0x{0:X} at offset {1:#,0}", - header, - offsetOrPosition - ) - ); - } - - private void ThrowUnexpectedExtCodeException( ReadValueResult type ) - { -#if DEBUG - Contract.Assert( false, "Unexpected ext-code type:" + type ); -#endif // DEBUG - // ReSharper disable HeuristicUnreachableCode - long offsetOrPosition; - var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); - - throw new NotSupportedException( - String.Format( - CultureInfo.CurrentCulture, - isRealOffset - ? "Unexpeded ext-code type {0} at position {1:#,0}" - : "Unexpeded ext-code type {0} at offset {1:#,0}", - type, - offsetOrPosition - ) - ); - // ReSharper restore HeuristicUnreachableCode - } - - private void CheckLength( long length, ReadValueResult type ) - { - if ( length > Int32.MaxValue ) - { - this.ThrowTooLongLengthException( length, type ); - } - } - - private void ThrowTooLongLengthException( long length, ReadValueResult type ) - { - string message; - long offsetOrPosition; - var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); - - switch ( type ) - { - case ReadValueResult.ArrayLength: - { - message = - isRealOffset - ? "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at position {1:#,0}" - : "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at offset {1:#,0}"; - break; - } - case ReadValueResult.MapLength: - { - message = - isRealOffset - ? "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at position {1:#,0}" - : "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at offset {1:#,0}"; - break; - } - default: - { - message = - isRealOffset - ? "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" - : "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; - break; - } - } - - throw new MessageNotSupportedException( - String.Format( - CultureInfo.CurrentCulture, - message, - length, - offsetOrPosition - ) - ); - } - - private void ThrowTypeException( Type type, byte header ) - { - long offsetOrPosition; - var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); - throw new MessageTypeException( - String.Format( - CultureInfo.CurrentCulture, - isRealOffset - ? "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in position {3:#,0}." - : "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in offset {3:#,0}.", - type, - header, - MessagePackCode.ToString( header ), - offsetOrPosition - ) - ); - } - - private enum ReadValueResult - { - Eof = 0, - Nil, - Boolean, - SByte, - Byte, - Int16, - UInt16, - Int32, - UInt32, - Int64, - UInt64, - Single, - Double, - ArrayLength, - MapLength, - String, - Binary, - FixExt1, - FixExt2, - FixExt4, - FixExt8, - FixExt16, - Ext8, - Ext16, - Ext32, - } - -#if FEATURE_TAP - - private struct AsyncReadValueResult - { - public ReadValueResult type; - public byte header; - public long integral; - public float real32; - public double real64; - } - -#endif // FEATURE_TAP - - internal enum CollectionType - { - // Value must be items count of collection element. - None = 0, - Array = 1, - Map = 2 - } - } -} diff --git a/src/MsgPack/KnownExtTypeCode.cs b/src/MsgPack/KnownExtTypeCode.cs index 8757d7028..3724f8182 100644 --- a/src/MsgPack/KnownExtTypeCode.cs +++ b/src/MsgPack/KnownExtTypeCode.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,15 +31,26 @@ namespace MsgPack /// public static class KnownExtTypeCode { + /// + /// Gets the ext type code which represents MsgPack timestamp. + /// + /// + /// 0xFF(-1). + /// + public static byte Timestamp + { + get { return 0xFF; } + } + /// /// Gets the ext type code which represents multidimensional array. /// /// - /// 0x1. + /// 0x71. /// public static byte MultidimensionalArray { get { return 0x71; } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/KnownExtTypeName.cs b/src/MsgPack/KnownExtTypeName.cs index a14833950..629fef805 100644 --- a/src/MsgPack/KnownExtTypeName.cs +++ b/src/MsgPack/KnownExtTypeName.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,6 +31,17 @@ namespace MsgPack /// public static class KnownExtTypeName { + /// + /// Gets the ext type name which represents MsgPack timestamp. + /// + /// + /// "Timestamp". + /// + public static string Timestamp + { + get { return "Timestamp"; } + } + /// /// Gets the ext type name which represents multidimensional array. /// diff --git a/src/netstandard/MPContract.cs b/src/MsgPack/MPContract.cs similarity index 100% rename from src/netstandard/MPContract.cs rename to src/MsgPack/MPContract.cs diff --git a/src/MsgPack/MessagePackByteArrayPacker.Pack.cs b/src/MsgPack/MessagePackByteArrayPacker.Pack.cs new file mode 100644 index 000000000..83ce2a451 --- /dev/null +++ b/src/MsgPack/MessagePackByteArrayPacker.Pack.cs @@ -0,0 +1,1191 @@ + +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + // This file was generated from MessagePackByteArrayPacker.Pack.tt and MessagePackPackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackByteArrayPacker.Pack.tt and MessagePackPackerCommon.ttinclude instead. + + partial class MessagePackByteArrayPacker + { + protected override void PackCore( Boolean value ) + { + this.WriteByte( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue ); + } + + protected override void PackCore( Byte value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )value ) ); + } + + protected override void PackCore( SByte value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ) ); + } + + protected override void PackCore( Int16 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ) ); + return; + } + + if ( value <= SByte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ) ); + } + + protected override void PackCore( UInt16 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Byte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )value ) ); + } + + protected override void PackCore( Int32 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value >= Int16.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ) ); + return; + } + + if ( value <= SByte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Int16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ) ); + } + + protected override void PackCore( UInt32 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Byte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )value ) ); + } + + protected override void PackCore( Int64 value ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & unchecked( ( long )0xFFFFFFFFFFFFFFE0 ) ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value >= Int16.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + if ( value >= Int32.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ) ); + return; + } + + if ( value <= SByte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Int16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + if ( value <= Int32.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ) ); + } + + protected override void PackCore( UInt64 value ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Byte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + if ( value <= UInt32.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt64, unchecked( ( UInt64 )value ) ); + } + + protected override void PackCore( Single value ) + { + this.WriteBytes( ( byte )MessagePackCode.Real32, unchecked( ( Single )value ) ); + } + + protected override void PackCore( Double value ) + { + this.WriteBytes( ( byte )MessagePackCode.Real64, unchecked( ( Double )value ) ); + } + + protected override void PackArrayHeaderCore( int length ) + { + if ( length < 0x10 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedArray | length ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Array16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Array32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackMapHeaderCore( int length ) + { + if ( length < 0x10 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedMap | length ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Map16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Map32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackStringHeaderCore( int length ) + { + if ( length < 0x20 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ) ); + return; + } + + if ( length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str8, unchecked( ( byte )( length & 0xFF ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Str32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackBinaryHeaderCore( int length ) + { + if ( length < 0x100 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( length & 0xFF ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Bin32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackRawCore( string value ) + { + this.WriteBytes( value, ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ); + } + + protected override void PackRawCore( byte[] value ) + { + if ( value.Length < 0x20 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + if ( value.Length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str8, unchecked( ( byte )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + if ( value.Length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Str32, unchecked( ( uint )value.Length ) ); + this.WriteBytes( value ); + return; + } + + protected override void PackBinaryCore( byte[] value ) + { + if ( value.Length < 0x100 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + if ( value.Length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Bin32, unchecked( ( uint )value.Length ) ); + this.WriteBytes( value ); + return; + } + + protected override void PackExtendedTypeValueCore( byte typeCode, byte[] body ) + { + unchecked + { + switch ( body.Length ) + { + case 1: + { + this.WriteByte( ( byte )MessagePackCode.FixExt1 ); + break; + } + case 2: + { + this.WriteByte( ( byte )MessagePackCode.FixExt2 ); + break; + } + case 4: + { + this.WriteByte( ( byte )MessagePackCode.FixExt4 ); + break; + } + case 8: + { + this.WriteByte( ( byte )MessagePackCode.FixExt8 ); + break; + } + case 16: + { + this.WriteByte( ( byte )MessagePackCode.FixExt16 ); + break; + } + default: + { + if ( body.Length < 0x100 ) + { + this.WriteBytes( ( byte )MessagePackCode.Ext8, ( byte )body.Length ); + } + else if ( body.Length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Ext16, ( ushort )body.Length ); + } + else + { + this.WriteBytes( ( byte )MessagePackCode.Ext32, ( uint )body.Length ); + } + + break; + } + } // switch + } // unchecked + + this.WriteByte( typeCode ); + this.WriteBytes( body ); + } + +#if FEATURE_TAP + + protected override async Task PackAsyncCore( Boolean value, CancellationToken cancellationToken ) + { + await this.WriteByteAsync( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue, cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Byte value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( SByte value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Int16 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= SByte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( UInt16 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Byte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Int32 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value >= Int16.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= SByte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Int16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( UInt32 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Byte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Int64 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & unchecked( ( long )0xFFFFFFFFFFFFFFE0 ) ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value >= Int16.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value >= Int32.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= SByte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Int16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Int32.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( UInt64 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Byte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= UInt32.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt64, unchecked( ( UInt64 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Single value, CancellationToken cancellationToken ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Real32, unchecked( ( Single )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Double value, CancellationToken cancellationToken ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Real64, unchecked( ( Double )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackArrayHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x10 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedArray | length ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Array16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Array32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackMapHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x10 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedMap | length ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Map16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Map32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackStringHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x20 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str8, unchecked( ( byte )( length & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Str32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackBinaryHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x100 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( length & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackRawAsyncCore( string value, CancellationToken cancellationToken ) + { + await this.WriteBytesAsync( value, ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0, cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackRawAsyncCore( byte[] value, CancellationToken cancellationToken ) + { + if ( value.Length < 0x20 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value.Length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str8, unchecked( ( byte )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value.Length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Str32, unchecked( ( uint )value.Length ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackBinaryAsyncCore( byte[] value, CancellationToken cancellationToken ) + { + if ( value.Length < 0x100 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value.Length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin32, unchecked( ( uint )value.Length ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackExtendedTypeValueAsyncCore( byte typeCode, byte[] body, CancellationToken cancellationToken ) + { + unchecked + { + switch ( body.Length ) + { + case 1: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt1, cancellationToken ).ConfigureAwait( false ); + break; + } + case 2: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt2, cancellationToken ).ConfigureAwait( false ); + break; + } + case 4: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt4, cancellationToken ).ConfigureAwait( false ); + break; + } + case 8: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt8, cancellationToken ).ConfigureAwait( false ); + break; + } + case 16: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt16, cancellationToken ).ConfigureAwait( false ); + break; + } + default: + { + if ( body.Length < 0x100 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Ext8, ( byte )body.Length, cancellationToken ).ConfigureAwait( false ); + } + else if ( body.Length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Ext16, ( ushort )body.Length, cancellationToken ).ConfigureAwait( false ); + } + else + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Ext32, ( uint )body.Length, cancellationToken ).ConfigureAwait( false ); + } + + break; + } + } // switch + } // unchecked + + await this.WriteByteAsync( typeCode, cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( body, cancellationToken ).ConfigureAwait( false ); + } + +#endif // FEATURE_TAP + + private void WriteStringHeader( int bytesLength, bool allowStr8 ) + { + if( bytesLength < 0x20 ) + { + this.WriteByte( ( byte )( bytesLength | MessagePackCode.MinimumFixedRaw ) ); + return; + } + + if ( bytesLength < 0x100 && allowStr8 ) + { + this.WriteBytes( MessagePackCode.Str8, ( byte )bytesLength ); + return; + } + + if ( bytesLength < 0x10000 ) + { + this.WriteBytes( MessagePackCode.Str16, ( ushort )bytesLength ); + return; + } + + this.WriteBytes( MessagePackCode.Str32, unchecked( ( uint )bytesLength ) ); + } + + private void WriteBytes( byte header, byte value ) + { + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( byte ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + + buffer[ offset ] = unchecked( ( byte )( value >> ( ( sizeof( byte ) - 1 ) * 8 ) & 0xFF ) ); + + this._buffer = buffer; + this._offset = offset + sizeof( byte ); + } + + private void WriteBytes( byte header, ushort value ) + { + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( ushort ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + + buffer[ offset ] = unchecked( ( byte )( value >> ( ( sizeof( ushort ) - 1 ) * 8 ) & 0xFF ) ); + buffer[ offset + 1 ] = unchecked( ( byte )( value >> ( ( sizeof( ushort ) - 2 ) * 8 ) & 0xFF ) ); + + this._buffer = buffer; + this._offset = offset + sizeof( ushort ); + } + + private void WriteBytes( byte header, uint value ) + { + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( uint ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + + buffer[ offset ] = unchecked( ( byte )( value >> ( ( sizeof( uint ) - 1 ) * 8 ) & 0xFF ) ); + buffer[ offset + 1 ] = unchecked( ( byte )( value >> ( ( sizeof( uint ) - 2 ) * 8 ) & 0xFF ) ); + buffer[ offset + 2 ] = unchecked( ( byte )( value >> ( ( sizeof( uint ) - 3 ) * 8 ) & 0xFF ) ); + buffer[ offset + 3 ] = unchecked( ( byte )( value >> ( ( sizeof( uint ) - 4 ) * 8 ) & 0xFF ) ); + + this._buffer = buffer; + this._offset = offset + sizeof( uint ); + } + + private void WriteBytes( byte header, ulong value ) + { + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( ulong ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + + buffer[ offset ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 1 ) * 8 ) & 0xFF ) ); + buffer[ offset + 1 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 2 ) * 8 ) & 0xFF ) ); + buffer[ offset + 2 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 3 ) * 8 ) & 0xFF ) ); + buffer[ offset + 3 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 4 ) * 8 ) & 0xFF ) ); + buffer[ offset + 4 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 5 ) * 8 ) & 0xFF ) ); + buffer[ offset + 5 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 6 ) * 8 ) & 0xFF ) ); + buffer[ offset + 6 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 7 ) * 8 ) & 0xFF ) ); + buffer[ offset + 7 ] = unchecked( ( byte )( value >> ( ( sizeof( ulong ) - 8 ) * 8 ) & 0xFF ) ); + + this._buffer = buffer; + this._offset = offset + sizeof( ulong ); + } + + private void WriteBytes( byte header, float value ) + { + var bits = Binary.ToBits( value ); + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( float ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + + buffer[ offset ] = unchecked( ( byte )( bits >> ( ( sizeof( float ) - 1 ) * 8 ) & 0xFF ) ); + buffer[ offset + 1 ] = unchecked( ( byte )( bits >> ( ( sizeof( float ) - 2 ) * 8 ) & 0xFF ) ); + buffer[ offset + 2 ] = unchecked( ( byte )( bits >> ( ( sizeof( float ) - 3 ) * 8 ) & 0xFF ) ); + buffer[ offset + 3 ] = unchecked( ( byte )( bits >> ( ( sizeof( float ) - 4 ) * 8 ) & 0xFF ) ); + + this._buffer = buffer; + this._offset = offset + sizeof( float ); + } + + private void WriteBytes( byte header, double value ) + { + var bits = Binary.ToBits( value ); + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( double ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + + buffer[ offset ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 1 ) * 8 ) & 0xFF ) ); + buffer[ offset + 1 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 2 ) * 8 ) & 0xFF ) ); + buffer[ offset + 2 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 3 ) * 8 ) & 0xFF ) ); + buffer[ offset + 3 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 4 ) * 8 ) & 0xFF ) ); + buffer[ offset + 4 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 5 ) * 8 ) & 0xFF ) ); + buffer[ offset + 5 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 6 ) * 8 ) & 0xFF ) ); + buffer[ offset + 6 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 7 ) * 8 ) & 0xFF ) ); + buffer[ offset + 7 ] = unchecked( ( byte )( bits >> ( ( sizeof( double ) - 8 ) * 8 ) & 0xFF ) ); + + this._buffer = buffer; + this._offset = offset + sizeof( double ); + } + + private void WriteBytes( string value, bool allowStr8 ) + { + var encodedLength = Encoding.UTF8.GetByteCount( value ); + this.WriteStringHeader( encodedLength, allowStr8 ); + if ( encodedLength == 0 ) + { + return; + } + + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + + if ( remains < encodedLength && !this._allocator.TryAllocate( buffer, encodedLength, out buffer ) ) + { + this.ThrowEofException( encodedLength ); + } + + Encoding.UTF8.GetBytes( value, 0, value.Length, buffer, offset ); + this._buffer = buffer; + this._offset += encodedLength; + } + +#if FEATURE_TAP + + private Task WriteBytesAsync( byte header, byte value, CancellationToken cancellationToken ) + { + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( byte header, ushort value, CancellationToken cancellationToken ) + { + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( byte header, uint value, CancellationToken cancellationToken ) + { + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( byte header, ulong value, CancellationToken cancellationToken ) + { + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( byte header, float value, CancellationToken cancellationToken ) + { + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( byte header, double value, CancellationToken cancellationToken ) + { + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( string value, bool allowStr8, CancellationToken cancellationToken ) + { + this.WriteBytes( value, allowStr8 ); + return TaskAugument.CompletedTask; + } + +#endif // FEATURE_TAP + } +} diff --git a/src/MsgPack/MessagePackByteArrayPacker.Pack.tt b/src/MsgPack/MessagePackByteArrayPacker.Pack.tt new file mode 100644 index 000000000..4b02bc458 --- /dev/null +++ b/src/MsgPack/MessagePackByteArrayPacker.Pack.tt @@ -0,0 +1,157 @@ +<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ Assembly Name="System.Core.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Runtime.InteropServices" #> +<#@ import namespace="System.Text" #> +<#@ include file="MessagePackPackerCommon.ttinclude" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + // This file was generated from MessagePackByteArrayPacker.Pack.tt and MessagePackPackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackByteArrayPacker.Pack.tt and MessagePackPackerCommon.ttinclude instead. + + partial class MessagePackByteArrayPacker + { +<# + this.WriteOverrides(); + + foreach ( var isAsync in new [] { false, true } ) + { + if ( isAsync ) + { +#> +#if FEATURE_TAP + +<# + } + + foreach ( var type in scalarTypes ) + { +#> + <#= NonAsyncMethod( isAsync, "void", "WriteBytes", "byte header, " + type + " value", false ) #> + { +<# + if ( isAsync ) + { +#> + this.WriteBytes( header, value ); + return TaskAugument.CompletedTask; +<# + } + else + { + string bits; + this.WriteToBits( type, "value", out bits ); +#> + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + const int requiredSize = sizeof( <#= type #> ) + 1; + if ( remains < requiredSize && !this._allocator.TryAllocate( buffer, requiredSize, out buffer ) ) + { + this.ThrowEofException( requiredSize ); + } + + buffer[ offset ] = header; + offset++; + +<# + var bytesLength = lengthes[ type ]; + for ( var i = 0; i < bytesLength; i++ ) + { +#> + buffer[ offset<#= i == 0 ? String.Empty : ( " + " + i.ToString( CultureInfo.InvariantCulture ) ) #> ] = unchecked( ( byte )( <#= bits #> >> ( ( sizeof( <#= type #> ) - <#= ( i + 1 ).ToString( CultureInfo.InvariantCulture ) #> ) * 8 ) & 0xFF ) ); +<# + } +#> + + this._buffer = buffer; + this._offset = offset + sizeof( <#= type #> ); +<# + } // if isAsync +#> + } + +<# + } // foreach type +#> + <#= NonAsyncMethod( isAsync, "void", "WriteBytes", "string value, bool allowStr8", false ) #> + { +<# + if ( isAsync ) + { +#> + this.WriteBytes( value, allowStr8 ); + return TaskAugument.CompletedTask; +<# + } + else + { +#> + var encodedLength = Encoding.UTF8.GetByteCount( value ); + this.WriteStringHeader( encodedLength, allowStr8 ); + if ( encodedLength == 0 ) + { + return; + } + + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + + if ( remains < encodedLength && !this._allocator.TryAllocate( buffer, encodedLength, out buffer ) ) + { + this.ThrowEofException( encodedLength ); + } + + Encoding.UTF8.GetBytes( value, 0, value.Length, buffer, offset ); + this._buffer = buffer; + this._offset += encodedLength; +<# + } // if isAsync +#> + } + +<# + + if ( isAsync ) + { +#> +#endif // FEATURE_TAP +<# + } + } // foreach isAsync +#> + } +} diff --git a/src/MsgPack/MessagePackByteArrayPacker.cs b/src/MsgPack/MessagePackByteArrayPacker.cs new file mode 100644 index 000000000..b560cd838 --- /dev/null +++ b/src/MsgPack/MessagePackByteArrayPacker.cs @@ -0,0 +1,191 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + /// + /// Implementation for byte array based MessagePack packer. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + sealed partial class MessagePackByteArrayPacker : ByteArrayPacker + { + private const int MaximumUtf8Length = 4; + + private byte[] _buffer; + private int _offset; + + private readonly int _initialOffset; + private readonly ByteBufferAllocator _allocator; + + public override int BytesUsed + { + get { return this._offset - this._initialOffset; } + } + + public override int InitialBufferOffset + { + get { return this._initialOffset; } + } + + public MessagePackByteArrayPacker( byte[] buffer, ByteBufferAllocator allocator, PackerCompatibilityOptions compatibilityOptions ) + : this( buffer, 0, allocator, compatibilityOptions ) { } + + public MessagePackByteArrayPacker( byte[] buffer, int startOffset, ByteBufferAllocator allocator, PackerCompatibilityOptions compatibilityOptions ) + : base( compatibilityOptions ) + { + this._buffer = buffer ?? Binary.Empty; + if ( startOffset < 0 ) + { + throw new ArgumentOutOfRangeException( "startOffset" ); + } + + if ( startOffset > this._buffer.Length ) + { + throw new ArgumentException( "The startOffset is too large or the length of buffer is too small." ); + } + + this._initialOffset = startOffset; + this._offset = startOffset; + this._allocator = allocator; + } + + public override byte[] GetFinalBuffer() + { + return this._buffer; + } + + protected override void WriteBytes( ICollection value ) + { + this.WriteBytes( value as byte[] ?? value.ToArray() ); + } + + protected override void WriteBytes( byte[] value, bool isImmutable ) + { + this.WriteBytes( value ); + } + +#if FEATURE_TAP + + protected override Task WriteBytesAsync( ICollection value, CancellationToken cancellationToken ) + { + return this.WriteBytesAsync( value as byte[] ?? value.ToArray(), cancellationToken ); + } + + protected override Task WriteBytesAsync( byte[] value, bool isImmutable, CancellationToken cancellationToken ) + { + return this.WriteBytesAsync( value, cancellationToken ); + } + +#endif // FEATURE_TAP + + protected override void WriteByte( byte value ) + { + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + if ( remains < 1 && !this._allocator.TryAllocate( buffer, 1, out buffer ) ) + { + this.ThrowEofException( 1 ); + } + + buffer[ offset ] = value; + this._buffer = buffer; + this._offset = offset + 1; + } + + private void WriteBytes( byte[] value, int startIndex, int count ) + { + var buffer = this._buffer; + var offset = this._offset; + var remains = buffer.Length - offset; + if ( remains < count && !this._allocator.TryAllocate( buffer, count, out buffer ) ) + { + this.ThrowEofException( count ); + } + + Buffer.BlockCopy( value, startIndex, buffer, offset, count ); + + this._buffer = buffer; + this._offset += count; + } + + private void WriteBytes( byte[] value ) + { + this.WriteBytes( value, 0, value.Length ); + } + +#if FEATURE_TAP + + protected override Task WriteByteAsync( byte value, CancellationToken cancellationToken ) + { + this.WriteByte( value ); + return TaskAugument.CompletedTask; + } + + private Task WriteBytesAsync( byte[] value, CancellationToken cancellationToken ) + { + this.WriteBytes( value ); + return TaskAugument.CompletedTask; + } + +#endif // FEATURE_TAP + + private void ThrowEofException( int requiredSize ) + { + throw new InvalidOperationException( + String.Format( + CultureInfo.CurrentCulture, + "Data buffer unexpectedly ends. Cannot write {0:#,0} bytes at offset {1:#,0}.", + requiredSize, + this._offset + ) + ); + } + + private void ThrowEofExceptionForString( int requiredCharCount ) + { + throw new InvalidOperationException( + String.Format( + CultureInfo.CurrentCulture, + "Data buffer unexpectedly ends. Cannot write {0:#,0} UTF-16 chars in UTF-8 encoding at offset {1:#,0}.", + requiredCharCount, + this._offset + ) + ); + } + } +} diff --git a/src/MsgPack/MessagePackByteArrayUnpacker.Unpack.cs b/src/MsgPack/MessagePackByteArrayUnpacker.Unpack.cs new file mode 100644 index 000000000..221b9bb71 --- /dev/null +++ b/src/MsgPack/MessagePackByteArrayUnpacker.Unpack.cs @@ -0,0 +1,3335 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; +using System.IO; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +#if !UNITY || MSGPACK_UNITY_FULL +using Int64Stack = System.Collections.Generic.Stack; +#endif // !UNITY || MSGPACK_UNITY_FULL + +namespace MsgPack +{ + // This file was generated from MessagePackByteArrayUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackByteArrayUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude instead. + + partial class MessagePackByteArrayUnpacker + { + public sealed override bool ReadByte( out Byte result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Byte ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Byte )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadByteSlow( header, source, ref offset, out result ) ) + { + result = default( Byte ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadByteSlow( ReadValueResult header, byte[] source, ref Int32 offset, out Byte result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Byte ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( Byte ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Byte )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( Byte )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( Byte )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( Byte )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( Byte )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Byte )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( Byte )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( Byte )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( Byte )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( Byte )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( Byte ), header ); + // Never + result = default( Byte ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableByte( out Byte? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Byte? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Byte? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableByteSlow( header, source, ref offset, out result ) ) + { + result = default( Byte? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableByteSlow( ReadValueResult header, byte[] source, ref Int32 offset, out Byte? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Byte? ); + offset++; + return true; + } + + Byte value; + if( !this.ReadByteSlow( header, source, ref offset, out value ) ) + { + result = default( Byte? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadByteAsync( CancellationToken cancellationToken ) + { + Byte result; + return Task.FromResult( this.ReadByte( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableByteAsync( CancellationToken cancellationToken ) + { + Byte? result; + return Task.FromResult( this.ReadNullableByte( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadSByte( out SByte result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( SByte ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( SByte )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadSByteSlow( header, source, ref offset, out result ) ) + { + result = default( SByte ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadSByteSlow( ReadValueResult header, byte[] source, ref Int32 offset, out SByte result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( SByte ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( SByte ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( SByte )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( SByte )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( SByte )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( SByte )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( SByte )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( SByte )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( SByte )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( SByte )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( SByte )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( SByte )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( SByte ), header ); + // Never + result = default( SByte ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableSByte( out SByte? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( SByte? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( SByte? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableSByteSlow( header, source, ref offset, out result ) ) + { + result = default( SByte? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableSByteSlow( ReadValueResult header, byte[] source, ref Int32 offset, out SByte? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( SByte? ); + offset++; + return true; + } + + SByte value; + if( !this.ReadSByteSlow( header, source, ref offset, out value ) ) + { + result = default( SByte? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadSByteAsync( CancellationToken cancellationToken ) + { + SByte result; + return Task.FromResult( this.ReadSByte( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableSByteAsync( CancellationToken cancellationToken ) + { + SByte? result; + return Task.FromResult( this.ReadNullableSByte( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadInt16( out Int16 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int16 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int16 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadInt16Slow( header, source, ref offset, out result ) ) + { + result = default( Int16 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadInt16Slow( ReadValueResult header, byte[] source, ref Int32 offset, out Int16 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int16 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( Int16 ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int16 )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int16 )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( Int16 )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( Int16 )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( Int16 )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int16 )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( Int16 )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( Int16 )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( Int16 )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( Int16 )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int16 ), header ); + // Never + result = default( Int16 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableInt16( out Int16? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int16? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int16? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableInt16Slow( header, source, ref offset, out result ) ) + { + result = default( Int16? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableInt16Slow( ReadValueResult header, byte[] source, ref Int32 offset, out Int16? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Int16? ); + offset++; + return true; + } + + Int16 value; + if( !this.ReadInt16Slow( header, source, ref offset, out value ) ) + { + result = default( Int16? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadInt16Async( CancellationToken cancellationToken ) + { + Int16 result; + return Task.FromResult( this.ReadInt16( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableInt16Async( CancellationToken cancellationToken ) + { + Int16? result; + return Task.FromResult( this.ReadNullableInt16( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadUInt16( out UInt16 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( UInt16 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt16 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadUInt16Slow( header, source, ref offset, out result ) ) + { + result = default( UInt16 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadUInt16Slow( ReadValueResult header, byte[] source, ref Int32 offset, out UInt16 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt16 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( UInt16 ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt16 )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt16 )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt16 )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt16 )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( UInt16 )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt16 )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt16 )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt16 )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( UInt16 )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( UInt16 )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt16 ), header ); + // Never + result = default( UInt16 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableUInt16( out UInt16? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( UInt16? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt16? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableUInt16Slow( header, source, ref offset, out result ) ) + { + result = default( UInt16? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableUInt16Slow( ReadValueResult header, byte[] source, ref Int32 offset, out UInt16? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( UInt16? ); + offset++; + return true; + } + + UInt16 value; + if( !this.ReadUInt16Slow( header, source, ref offset, out value ) ) + { + result = default( UInt16? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadUInt16Async( CancellationToken cancellationToken ) + { + UInt16 result; + return Task.FromResult( this.ReadUInt16( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableUInt16Async( CancellationToken cancellationToken ) + { + UInt16? result; + return Task.FromResult( this.ReadNullableUInt16( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadInt32( out Int32 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int32 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int32 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadInt32Slow( header, source, ref offset, out result ) ) + { + result = default( Int32 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadInt32Slow( ReadValueResult header, byte[] source, ref Int32 offset, out Int32 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int32 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( Int32 ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int32 )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int32 )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( Int32 )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( Int32 )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( Int32 )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int32 )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( Int32 )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( Int32 )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( Int32 )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( Int32 )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int32 ), header ); + // Never + result = default( Int32 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableInt32( out Int32? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int32? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int32? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableInt32Slow( header, source, ref offset, out result ) ) + { + result = default( Int32? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableInt32Slow( ReadValueResult header, byte[] source, ref Int32 offset, out Int32? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Int32? ); + offset++; + return true; + } + + Int32 value; + if( !this.ReadInt32Slow( header, source, ref offset, out value ) ) + { + result = default( Int32? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadInt32Async( CancellationToken cancellationToken ) + { + Int32 result; + return Task.FromResult( this.ReadInt32( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableInt32Async( CancellationToken cancellationToken ) + { + Int32? result; + return Task.FromResult( this.ReadNullableInt32( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadUInt32( out UInt32 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( UInt32 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt32 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadUInt32Slow( header, source, ref offset, out result ) ) + { + result = default( UInt32 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadUInt32Slow( ReadValueResult header, byte[] source, ref Int32 offset, out UInt32 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt32 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( UInt32 ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt32 )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt32 )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt32 )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt32 )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( UInt32 )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt32 )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt32 )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt32 )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( UInt32 )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( UInt32 )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt32 ), header ); + // Never + result = default( UInt32 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableUInt32( out UInt32? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( UInt32? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt32? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableUInt32Slow( header, source, ref offset, out result ) ) + { + result = default( UInt32? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableUInt32Slow( ReadValueResult header, byte[] source, ref Int32 offset, out UInt32? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( UInt32? ); + offset++; + return true; + } + + UInt32 value; + if( !this.ReadUInt32Slow( header, source, ref offset, out value ) ) + { + result = default( UInt32? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadUInt32Async( CancellationToken cancellationToken ) + { + UInt32 result; + return Task.FromResult( this.ReadUInt32( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableUInt32Async( CancellationToken cancellationToken ) + { + UInt32? result; + return Task.FromResult( this.ReadNullableUInt32( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadInt64( out Int64 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int64 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadInt64Slow( header, source, ref offset, out result ) ) + { + result = default( Int64 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadInt64Slow( ReadValueResult header, byte[] source, ref Int32 offset, out Int64 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int64 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( Int64 ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int64 )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int64 )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( Int64 )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( Int64 )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( Int64 )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int64 )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( Int64 )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( Int64 )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( Int64 )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( Int64 )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int64 ), header ); + // Never + result = default( Int64 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableInt64( out Int64? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int64? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int64? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableInt64Slow( header, source, ref offset, out result ) ) + { + result = default( Int64? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableInt64Slow( ReadValueResult header, byte[] source, ref Int32 offset, out Int64? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Int64? ); + offset++; + return true; + } + + Int64 value; + if( !this.ReadInt64Slow( header, source, ref offset, out value ) ) + { + result = default( Int64? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadInt64Async( CancellationToken cancellationToken ) + { + Int64 result; + return Task.FromResult( this.ReadInt64( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableInt64Async( CancellationToken cancellationToken ) + { + Int64? result; + return Task.FromResult( this.ReadNullableInt64( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadUInt64( out UInt64 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( UInt64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt64 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadUInt64Slow( header, source, ref offset, out result ) ) + { + result = default( UInt64 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadUInt64Slow( ReadValueResult header, byte[] source, ref Int32 offset, out UInt64 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt64 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( UInt64 ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt64 )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt64 )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt64 )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt64 )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( UInt64 )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt64 )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt64 )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt64 )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( UInt64 )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( UInt64 )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt64 ), header ); + // Never + result = default( UInt64 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableUInt64( out UInt64? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( UInt64? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt64? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableUInt64Slow( header, source, ref offset, out result ) ) + { + result = default( UInt64? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableUInt64Slow( ReadValueResult header, byte[] source, ref Int32 offset, out UInt64? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( UInt64? ); + offset++; + return true; + } + + UInt64 value; + if( !this.ReadUInt64Slow( header, source, ref offset, out value ) ) + { + result = default( UInt64? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadUInt64Async( CancellationToken cancellationToken ) + { + UInt64 result; + return Task.FromResult( this.ReadUInt64( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableUInt64Async( CancellationToken cancellationToken ) + { + UInt64? result; + return Task.FromResult( this.ReadNullableUInt64( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadSingle( out Single result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Single ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Single )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadSingleSlow( header, source, ref offset, out result ) ) + { + result = default( Single ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadSingleSlow( ReadValueResult header, byte[] source, ref Int32 offset, out Single result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Single ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( Single ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Single )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( Single )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( Single )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( Single )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( Single )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Single )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( Single )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( Single )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( Single )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( Single )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( Single ), header ); + // Never + result = default( Single ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableSingle( out Single? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Single? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Single? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableSingleSlow( header, source, ref offset, out result ) ) + { + result = default( Single? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableSingleSlow( ReadValueResult header, byte[] source, ref Int32 offset, out Single? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Single? ); + offset++; + return true; + } + + Single value; + if( !this.ReadSingleSlow( header, source, ref offset, out value ) ) + { + result = default( Single? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadSingleAsync( CancellationToken cancellationToken ) + { + Single result; + return Task.FromResult( this.ReadSingle( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableSingleAsync( CancellationToken cancellationToken ) + { + Single? result; + return Task.FromResult( this.ReadNullableSingle( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadDouble( out Double result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Double ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Double )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadDoubleSlow( header, source, ref offset, out result ) ) + { + result = default( Double ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadDoubleSlow( ReadValueResult header, byte[] source, ref Int32 offset, out Double result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Double ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + if ( source.Length - offset < length ) + { + result = default( Double ); + return false; + } + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Double )source[ offset ]; + break; + } + case 0x200: // UInt16 + { + result = ( Double )BigEndianBinary.ToUInt16( source, offset ); + break; + } + case 0x400: // UInt32 + { + result = ( Double )BigEndianBinary.ToUInt32( source, offset ); + break; + } + case 0x800: // UInt64 + { + result = ( Double )BigEndianBinary.ToUInt64( source, offset ); + break; + } + case 0x1100: // SByte + { + result = ( Double )( unchecked( ( SByte )source[ offset ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Double )BigEndianBinary.ToInt16( source, offset ); + break; + } + case 0x1400: // Int32 + { + result = ( Double )BigEndianBinary.ToInt32( source, offset ); + break; + } + case 0x1800: // Int64 + { + result = ( Double )BigEndianBinary.ToInt64( source, offset ); + break; + } + case 0x2400: // Single + { + result = ( Double )BigEndianBinary.ToSingle( source, offset ); + break; + } + case 0x2800: // Double + { + result = ( Double )BigEndianBinary.ToDouble( source, offset ); + break; + } + default: + { + this.ThrowTypeException( typeof( Double ), header ); + // Never + result = default( Double ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableDouble( out Double? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Double? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Double? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableDoubleSlow( header, source, ref offset, out result ) ) + { + result = default( Double? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableDoubleSlow( ReadValueResult header, byte[] source, ref Int32 offset, out Double? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Double? ); + offset++; + return true; + } + + Double value; + if( !this.ReadDoubleSlow( header, source, ref offset, out value ) ) + { + result = default( Double? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadDoubleAsync( CancellationToken cancellationToken ) + { + Double result; + return Task.FromResult( this.ReadDouble( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableDoubleAsync( CancellationToken cancellationToken ) + { + Double? result; + return Task.FromResult( this.ReadNullableDouble( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadBoolean( out Boolean result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Boolean ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + switch ( header ) + { + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( Boolean ), header ); + // never + result = false; + break; + } + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } // if ( isAsync && isPseudoAsync ) + + public sealed override bool ReadNullableBoolean( out Boolean? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Boolean? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + switch ( header ) + { + case ReadValueResult.Nil: + { + result = default( bool? ); + break; + } + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( Boolean? ), header ); + // never + result = false; + break; + } + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } // if ( isAsync && isPseudoAsync ) + +#if FEATURE_TAP + + public sealed override Task> ReadBooleanAsync( CancellationToken cancellationToken ) + { + Boolean result; + return Task.FromResult( this.ReadBoolean( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } // if ( isAsync && isPseudoAsync ) + + public sealed override Task> ReadNullableBooleanAsync( CancellationToken cancellationToken ) + { + Boolean? result; + return Task.FromResult( this.ReadNullableBoolean( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } // if ( isAsync && isPseudoAsync ) + +#endif // FEATURE_TAP + + public sealed override bool ReadBinary( out Byte[] result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Byte[] ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + // Byte[] can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + // Check type + if ( ( header & ReadValueResult.RawTypeMask ) != ReadValueResult.RawTypeMask ) + { + this.ThrowTypeException( "raw", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Raw8 + { + if ( source.Length - offset < 1 ) + { + result = default( Byte[] ); + return false; + } + + length = BigEndianBinary.ToByte( source, offset ); + + break; + } + case 2: // Raw16 + { + if ( source.Length - offset < 2 ) + { + result = default( Byte[] ); + return false; + } + + length = BigEndianBinary.ToUInt16( source, offset ); + + break; + } + default: // Raw32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + if ( source.Length - offset < 4 ) + { + result = default( Byte[] ); + return false; + } + + length = BigEndianBinary.ToUInt32( source, offset ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out result ) ) + { + result = default( Byte[] ); + return false; + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadBinaryAsync( CancellationToken cancellationToken ) + { + Byte[] result; + return Task.FromResult( this.ReadBinary( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadString( out String result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( String ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + // String can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + // Check type + if ( ( header & ReadValueResult.RawTypeMask ) != ReadValueResult.RawTypeMask ) + { + this.ThrowTypeException( "raw", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Raw8 + { + if ( source.Length - offset < 1 ) + { + result = default( String ); + return false; + } + + length = BigEndianBinary.ToByte( source, offset ); + + break; + } + case 2: // Raw16 + { + if ( source.Length - offset < 2 ) + { + result = default( String ); + return false; + } + + length = BigEndianBinary.ToUInt16( source, offset ); + + break; + } + default: // Raw32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + if ( source.Length - offset < 4 ) + { + result = default( String ); + return false; + } + + length = BigEndianBinary.ToUInt32( source, offset ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + if( !this.ReadStringCore( unchecked( ( int )length ), ref offset, out result ) ) + { + result = default( String ); + return false; + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadStringAsync( CancellationToken cancellationToken ) + { + String result; + return Task.FromResult( this.ReadString( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + private bool ReadObject( bool isDeep, out MessagePackObject result ) + { + var source = this._source; + var offset = this._offset; + if ( !this.ReadObjectCore( isDeep, source, ref offset, out result ) ) + { + result = default( MessagePackObject ); + return false; + } + this._offset = offset; + return true; + } + + private bool ReadObjectCore( bool isDeep, byte[] source, ref Int32 offset, out MessagePackObject result ) + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackObject ); + return false; + } + + var byteHeader = source[ offset ]; + offset++; + var collectionType = ReadValueResults.CollectionType[ byteHeader ]; + + if ( ReadValueResults.HasConstantObject[ byteHeader ] ) + { + result = ReadValueResults.ContantObject[ byteHeader ]; + } + else + { + var header = ReadValueResults.EncodedTypes[ byteHeader ]; + + if ( ( header & ReadValueResult.RawTypeMask ) == ReadValueResult.RawTypeMask && ( header & ReadValueResult.LengthOfLengthMask ) == 0 ) + { + // fixed raw + int length = ( int )( header & ReadValueResult.ValueOrLengthMask ); + + byte[] binary; + if ( !this.ReadBinaryCore( length, ref offset, out binary ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = binary; + } + else + { + if ( !this.ReadObjectSlow( header, source, ref offset, out result ) ) + { + result = default( MessagePackObject ); + return false; + } + } + } + + if ( isDeep && collectionType != CollectionType.None ) + { + if ( !this.ReadItems( result.AsInt32(), collectionType == CollectionType.Map, source, ref offset, out result ) ) + { + result = default( MessagePackObject ); + return false; + } + } + + this._data = result; + this._collectionType = collectionType; + return true; + } + + private bool ReadObjectSlow( ReadValueResult header, byte[] source, ref Int32 offset, out MessagePackObject result ) + { + switch ( header & ReadValueResult.TypeCodeMask ) + { + case ReadValueResult.Array16Type: + case ReadValueResult.Map16Type: + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToUInt16( source, offset ); + offset += 2; + break; + } + case ReadValueResult.Array32Type: + case ReadValueResult.Map32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToUInt32( source, offset ); + offset += 4; + break; + } + case ReadValueResult.Str8Type: + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = source[ offset ]; + this.CheckLength( length, header ); + offset += 1; + MessagePackString stringValue; + if( !this.ReadRawStringCore( unchecked( ( int )length ), ref offset, out stringValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Str16Type: + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = BigEndianBinary.ToUInt16( source, offset ); + this.CheckLength( length, header ); + offset += 2; + MessagePackString stringValue; + if( !this.ReadRawStringCore( unchecked( ( int )length ), ref offset, out stringValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Str32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = BigEndianBinary.ToUInt32( source, offset ); + this.CheckLength( length, header ); + offset += 4; + MessagePackString stringValue; + if( !this.ReadRawStringCore( unchecked( ( int )length ), ref offset, out stringValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Bin8Type: + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = source[ offset ]; + this.CheckLength( length, header ); + offset += 1; + byte[] binaryValue; + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out binaryValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.Bin16Type: + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = BigEndianBinary.ToUInt16( source, offset ); + this.CheckLength( length, header ); + offset += 2; + byte[] binaryValue; + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out binaryValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.Bin32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = BigEndianBinary.ToUInt32( source, offset ); + this.CheckLength( length, header ); + offset += 4; + byte[] binaryValue; + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out binaryValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.FixExtType: + { + var length = ( header & ReadValueResult.ValueOrLengthMask ); + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), source, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Ext8Type: + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackObject ); + return false; + } + var length = source[ offset ]; + offset += 1; + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), source, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Ext16Type: + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackObject ); + return false; + } + var length = BigEndianBinary.ToUInt16( source, offset ); + offset += 2; + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), source, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Ext32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + var length = BigEndianBinary.ToUInt32( source, offset ); + offset += 4; + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), source, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Int8Type: + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackObject ); + return false; + } + result = unchecked( ( sbyte )source[ offset ] ); + offset += 1; + break; + } + case ReadValueResult.Int16Type: + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToInt16( source, offset ); + offset += 2; + break; + } + case ReadValueResult.Int32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToInt32( source, offset ); + offset += 4; + break; + } + case ReadValueResult.Int64Type: + { + if ( source.Length - offset < 8 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToInt64( source, offset ); + offset += 8; + break; + } + case ReadValueResult.UInt8Type: + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackObject ); + return false; + } + result = source[ offset ]; + offset += 1; + break; + } + case ReadValueResult.UInt16Type: + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToUInt16( source, offset ); + offset += 2; + break; + } + case ReadValueResult.UInt32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToUInt32( source, offset ); + offset += 4; + break; + } + case ReadValueResult.UInt64Type: + { + if ( source.Length - offset < 8 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToUInt64( source, offset ); + offset += 8; + break; + } + case ReadValueResult.Real32Type: + { + if ( source.Length - offset < 4 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToSingle( source, offset ); + offset += 4; + break; + } + case ReadValueResult.Real64Type: + { + if ( source.Length - offset < 8 ) + { + result = default( MessagePackObject ); + return false; + } + result = BigEndianBinary.ToDouble( source, offset ); + offset += 8; + break; + } + default: + { +#if DEBUG + Contract.Assert( header == ReadValueResult.InvalidCode, header.ToString( "X" ) + " == ReadValueResult.InvalidCode" ); +#endif // DEBUG + this.ThrowUnassignedMessageTypeException( 0xC1 ); + // never + result = default( MessagePackObject ); + break; + } + } + + return true; + } + + private bool ReadItems( int count, bool isMap, byte[] source, ref Int32 offset, out MessagePackObject result ) + { + MessagePackObject container; + if ( !isMap ) + { + var array = new MessagePackObject[ count ]; + for ( var i = 0; i < count; i++ ) + { + MessagePackObject item; + if ( !this.ReadObjectCore( true, source, ref offset, out item ) ) + { + result = default( MessagePackObject ); + return false; + } + array[ i ] = item; + } + + container = new MessagePackObject( array, true ); + } + else + { + var map = new MessagePackObjectDictionary( count ); + + for ( var i = 0; i < count; i++ ) + { + MessagePackObject key; + if ( !this.ReadObjectCore( true, source, ref offset, out key ) ) + { + result = default( MessagePackObject ); + return false; + } + MessagePackObject value; + if ( !this.ReadObjectCore( true, source, ref offset, out value ) ) + { + result = default( MessagePackObject ); + return false; + } + map.Add( key, value ); + } + + container = new MessagePackObject( map, true ); + } + result = container; + return true; + } + +#if FEATURE_TAP + + private Task> ReadObjectAsync( bool isDeep, CancellationToken cancellationToken ) + { + MessagePackObject result; + return Task.FromResult( this.ReadObject( isDeep, out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadArrayLength( out Int64 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.ArrayTypeMask ) != ReadValueResult.ArrayTypeMask ) + { + this.ThrowTypeException( "array", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Array8 + { + if ( source.Length - offset < 1 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToByte( source, offset ); + + break; + } + case 2: // Array16 + { + if ( source.Length - offset < 2 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToUInt16( source, offset ); + + break; + } + default: // Array32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + if ( source.Length - offset < 4 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToUInt32( source, offset ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + result = length; + this._data = length; + this._offset = offset; + this._collectionType = CollectionType.Array; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadArrayLengthAsync( CancellationToken cancellationToken ) + { + Int64 result; + return Task.FromResult( this.ReadArrayLength( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadMapLength( out Int64 result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( Int64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.MapTypeMask ) != ReadValueResult.MapTypeMask ) + { + this.ThrowTypeException( "map", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Map8 + { + if ( source.Length - offset < 1 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToByte( source, offset ); + + break; + } + case 2: // Map16 + { + if ( source.Length - offset < 2 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToUInt16( source, offset ); + + break; + } + default: // Map32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + if ( source.Length - offset < 4 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToUInt32( source, offset ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + result = length; + this._data = length; + this._offset = offset; + this._collectionType = CollectionType.Map; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadMapLengthAsync( CancellationToken cancellationToken ) + { + Int64 result; + return Task.FromResult( this.ReadMapLength( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.ExtTypeMask ) != ReadValueResult.ExtTypeMask ) + { + this.ThrowTypeException( "ext", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Ext8 + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + length = BigEndianBinary.ToByte( source, offset ); + + break; + } + case 2: // Ext16 + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + length = BigEndianBinary.ToUInt16( source, offset ); + + break; + } + default: // Ext32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + if ( source.Length - offset < 4 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + length = BigEndianBinary.ToUInt32( source, offset ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), source, ref offset, out result ) ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadMessagePackExtendedTypeObjectCore( int length, byte[] source, ref Int32 offset, out MessagePackExtendedTypeObject result ) + { + // Read type code + if ( source.Length - offset < 1 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + var typeCode = source[ offset ]; + offset++; + + // Read body + byte[] body; + if ( !this.ReadBinaryCore( length, ref offset, out body ) ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + result = MessagePackExtendedTypeObject.Unpack( typeCode, body ); + return true; + } + + public sealed override bool ReadNullableMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject? result ) + { + var source = this._source; + var offset = this._offset; + if ( source.Length - offset < 1 ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ source[ offset ] ]; + if ( header == ReadValueResult.Nil ) + { + result = default( MessagePackExtendedTypeObject? ); + return true; + } + offset++; + + // Check type + if ( ( header & ReadValueResult.ExtTypeMask ) != ReadValueResult.ExtTypeMask ) + { + this.ThrowTypeException( "ext", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Ext8 + { + if ( source.Length - offset < 1 ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + length = BigEndianBinary.ToByte( source, offset ); + + break; + } + case 2: // Ext16 + { + if ( source.Length - offset < 2 ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + length = BigEndianBinary.ToUInt16( source, offset ); + + break; + } + default: // Ext32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + if ( source.Length - offset < 4 ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + length = BigEndianBinary.ToUInt32( source, offset ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + MessagePackExtendedTypeObject value; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), source, ref offset, out value ) ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + result = value; + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + +#if FEATURE_TAP + + public sealed override Task> ReadMessagePackExtendedTypeObjectAsync( CancellationToken cancellationToken ) + { + MessagePackExtendedTypeObject result; + return Task.FromResult( this.ReadMessagePackExtendedTypeObject( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + + public sealed override Task> ReadNullableMessagePackExtendedTypeObjectAsync( CancellationToken cancellationToken ) + { + MessagePackExtendedTypeObject? result; + return Task.FromResult( this.ReadNullableMessagePackExtendedTypeObject( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail() ); + } + +#endif // FEATURE_TAP + + protected sealed override long? SkipCore() + { + var startOffset = this._offset; + MessagePackObject notUsed; + if ( !this.ReadObject( /* isDeep */true, out notUsed ) ) + { + return null; + } + + return this._offset - startOffset; + } + +#if FEATURE_TAP + protected sealed override async Task SkipAsyncCore( CancellationToken cancellationToken ) + { + var startOffset = this._offset; + var asyncReadResult = await this.ReadObjectAsync( /* isDeep */true, cancellationToken ).ConfigureAwait( false ); + if ( !asyncReadResult.Success ) + { + return null; + } + + return this._offset - startOffset; + } + +#endif // FEATURE_TAP + public sealed override bool ReadObject( out MessagePackObject result ) + { + return this.ReadObject( /* isDeep*/true, out result ); + } + +#if FEATURE_TAP + + public sealed override Task> ReadObjectAsync( CancellationToken cancellationToken ) + { + return this.ReadObjectAsync( /* isDeep*/true, cancellationToken ); + } + +#endif // FEATURE_TAP + + protected sealed override bool ReadCore() + { + MessagePackObject value; + var success = this.ReadObject( /* isDeep */false, out value ); + if ( success ) + { + this._data = value; + return true; + } + else + { + return false; + } + } + +#if FEATURE_TAP + + protected sealed override async Task ReadAsyncCore( CancellationToken cancellationToken ) + { + var result = await this.ReadObjectAsync( /* isDeep */false, cancellationToken ).ConfigureAwait( false ); + if ( result.Success ) + { + this._data = result.Value; + return true; + } + else + { + return false; + } + } + +#endif // FEATURE_TAP + + private void ThrowUnassignedMessageTypeException( int header ) + { +#if DEBUG + Contract.Assert( header == 0xC1, "Unhandled header:" + header.ToString( "X2" ) ); +#endif // DEBUG + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + throw new UnassignedMessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Unknown header value 0x{0:X} at position {1:#,0}" + : "Unknown header value 0x{0:X} at offset {1:#,0}", + header, + offsetOrPosition + ) + ); + } + + private void CheckLength( uint length, ReadValueResult type ) + { + if ( length > Int32.MaxValue ) + { + this.ThrowTooLongLengthException( length, type ); + } + } + + private void ThrowTooLongLengthException( uint length, ReadValueResult type ) + { + string message; + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + + if ( ( type & ReadValueResult.ArrayTypeMask ) == ReadValueResult.ArrayTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at position {1:#,0}" + : "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at offset {1:#,0}"; + } + else if ( ( type & ReadValueResult.MapTypeMask ) == ReadValueResult.MapTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at position {1:#,0}" + : "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at offset {1:#,0}"; + } + else if ( ( type & ReadValueResult.ExtTypeMask ) == ReadValueResult.ExtTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large ext type (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" + : "MessagePack for CLI cannot handle large ext type (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; + } + else + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" + : "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; + } + + throw new MessageNotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + message, + length, + offsetOrPosition + ) + ); + } + + private void ThrowTypeException( string type, ReadValueResult header ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + var byteHeader = header.ToByte(); + throw new MessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Cannot convert '{0}' header from type '{2}'(0x{1:X}) in position {3:#,0}." + : "Cannot convert '{0}' header from type '{2}'(0x{1:X}) in offset {3:#,0}.", + type, + byteHeader, + MessagePackCode.ToString( byteHeader ), + offsetOrPosition + ) + ); + } + + private void ThrowTypeException( Type type, ReadValueResult header ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + var byteHeader = header.ToByte(); + throw new MessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in position {3:#,0}." + : "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in offset {3:#,0}.", + type, + byteHeader, + MessagePackCode.ToString( byteHeader ), + offsetOrPosition + ) + ); + } + } +} diff --git a/src/MsgPack/MessagePackByteArrayUnpacker.Unpack.tt b/src/MsgPack/MessagePackByteArrayUnpacker.Unpack.tt new file mode 100644 index 000000000..367af00f7 --- /dev/null +++ b/src/MsgPack/MessagePackByteArrayUnpacker.Unpack.tt @@ -0,0 +1,108 @@ +<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ include file=".\MessagePackUnpackerCommon.ttinclude" #> +<#@ Assembly Name="System.Core.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; +using System.IO; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +#if !UNITY || MSGPACK_UNITY_FULL +using Int64Stack = System.Collections.Generic.Stack; +#endif // !UNITY || MSGPACK_UNITY_FULL + +namespace MsgPack +{ + // This file was generated from MessagePackByteArrayUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackByteArrayUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude instead. + + partial class MessagePackByteArrayUnpacker + { +<# +this.WriteCommon( + "_offset", + new ReadMethodContext( "source", "offset", "Int32", useOffsetForBuffer: true ), + context => this.WritePrologue( context ), + ( context, collectionType ) => this.WriteEpilogue( context, collectionType ), + ( context, indentLevel, lengthExpression, onFail, isAsync ) => this.WriteReadBytes( context, indentLevel, lengthExpression, onFail, isAsync ), + isPseudoAsync: true +); +#> + } +} +<#+ +private void WritePrologue( ReadMethodContext context ) +{ +#> + var <#= context.BufferExpression #> = this._source; + var <#= context.OffsetExpression #> = this._offset; +<#+ +} // WritePrologue + +private void WriteEpilogue( ReadMethodContext context, string collectionType ) +{ +#> + this._offset = <#= context.OffsetExpression #>; +<#+ + if ( collectionType != null ) + { +#> + this._collectionType = <#= collectionType #>; +<#+ + } +} // WriteEpilogue + +private void WriteReadBytes( ReadMethodContext context, int indentLevel, string lengthExpression, Action onFail, bool isAsync ) +{ + this.PushIndent( indentLevel ); +#> +if ( <#= context.BufferExpression #>.Length - <#= context.OffsetExpression #> < <#= lengthExpression #> ) +{ +<#+ + onFail( 1 ); +#> +} +<#+ + this.PopIndent(); +}// WriteReadBytes( context, indentLevel, lengthExpression, onFail, isAsync ) +#> diff --git a/src/MsgPack/MessagePackByteArrayUnpacker.cs b/src/MsgPack/MessagePackByteArrayUnpacker.cs new file mode 100644 index 000000000..b01b2d4cf --- /dev/null +++ b/src/MsgPack/MessagePackByteArrayUnpacker.cs @@ -0,0 +1,328 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Globalization; +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + /// + /// Implements common features for byte array based MessagePack unpacker. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + abstract partial class MessagePackByteArrayUnpacker : ByteArrayUnpacker, IRootUnpacker + { + private byte[] _source; + private int _offset; + private readonly byte[] _scalarBuffer = new byte[ 8 ]; + private CollectionType _collectionType; + private MessagePackObject _data; + + public sealed override int Offset + { + get { return this._offset; } + } + +#pragma warning disable CS0672 + public sealed override MessagePackObject? Data + { + get { return this._data; } + protected set { this._data = value.GetValueOrDefault(); } + } +#pragma warning restore CS0672 + + public sealed override MessagePackObject LastReadData + { + get { return this._data; } + protected set { this._data = value; } + } + + public sealed override bool IsArrayHeader + { + get { return this._collectionType == CollectionType.Array; } + } + + public sealed override bool IsMapHeader + { + get { return this._collectionType == CollectionType.Map; } + } + + public sealed override bool IsCollectionHeader + { + get { return this._collectionType != CollectionType.None; } + } + + public sealed override long ItemsCount + { + get { return this._collectionType == CollectionType.None ? 0 : this._data.AsInt64(); } + } + + CollectionType IRootUnpacker.CollectionType + { + get { return this._collectionType; } + } + + MessagePackObject? IRootUnpacker.Data + { +#pragma warning disable CS0618 + get { return this.Data; } + set { this.Data = value; } +#pragma warning restore CS0618 + } + + MessagePackObject IRootUnpacker.LastReadData + { + get { return this._data; } + set { this._data = value; } + } + +#if DEBUG + +#if UNITY && DEBUG + public +#else + internal +#endif + byte[] DebugSource + { + get { return this._source; } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + long DebugOffset + { + get { return this._offset; } + } + + internal override long? UnderlyingStreamPosition + { + get { return this._offset; } + } + + long? IRootUnpacker.UnderlyingStreamPosition + { + get { return this.UnderlyingStreamPosition; } + } + +#endif // DEBUG + + internal override bool GetPreviousPosition( out long offsetOrPosition ) + { + offsetOrPosition = this._offset; + return false; + } + + public MessagePackByteArrayUnpacker( byte[] source, int startOffset ) + { + if ( source == null ) + { + throw new ArgumentNullException( "source" ); + } + + if ( source.Length == 0 ) + { + throw new ArgumentException( "The source is empty.", "source" ); + } + + if ( startOffset < 0 ) + { + throw new ArgumentOutOfRangeException( "The value cannot be negative.", "startOffset" ); + } + + if ( startOffset >= source.Length ) + { + throw new ArgumentException( "The startOffset is too large or the length of source is too small." ); + } + + this._source = source; + this._offset = startOffset; + } + +#if FEATURE_MEMCOPY + [System.Security.SecuritySafeCritical] +#endif // FEATURE_MEMCOPY + private bool ReadBinaryCore( int length, ref int offset, out byte[] result ) + { + if ( length == 0 ) + { + result = Binary.Empty; + return true; + } + + var source = this._source; + if ( source.Length - offset < length ) + { + result = default( byte[] ); + return false; + } + + result = new byte[ length ]; +#if FEATURE_MEMCOPY + unsafe + { + fixed ( byte* pSource = source ) + { + fixed ( byte* pResult = result ) + { + Buffer.MemoryCopy( pSource + offset, pResult, length, length ); + } + } + } +#else + Buffer.BlockCopy( source, offset, result, 0, length ); +#endif // FEATURE_MEMCOPY + offset += length; + return true; + } + +#if FEATURE_TAP + + private Task>> ReadBinaryCoreAsync( int length, int offset, CancellationToken cancellationToken ) + { + byte[] result; + if ( !this.ReadBinaryCore( length, ref offset, out result ) ) + { + return Task.FromResult( AsyncReadResult.Fail>() ); + } + + return Task.FromResult( AsyncReadResult.Success( result, offset ) ); + } + +#endif // FEATURE_TAP + + private bool ReadStringCore( int length, ref int offset, out string result ) + { + if ( length == 0 ) + { + result = String.Empty; + return true; + } + + var source = this._source; + if ( source.Length - offset < length ) + { + result = default( string ); + return false; + } + + result = MessagePackConvert.Utf8NonBomStrict.GetString( source, offset, length ); + offset += length; + return true; + } + +#if FEATURE_TAP + + private Task>> ReadStringCoreAsync( int length, int offset, CancellationToken cancellationToken ) + { + string result; + if ( !this.ReadStringCore( length, ref offset, out result ) ) + { + return Task.FromResult( AsyncReadResult.Fail>() ); + } + + return Task.FromResult( AsyncReadResult.Success( result, offset ) ); + } + +#endif // FEATURE_TAP + + private bool ReadRawStringCore( int length, ref int offset, out MessagePackString result ) + { + byte[] asBinary; + if ( !this.ReadBinaryCore( length, ref offset, out asBinary ) ) + { + result = default( MessagePackString ); + return false; + } + + try + { + result = new MessagePackString( MessagePackConvert.Utf8NonBomStrict.GetString( asBinary, 0, asBinary.Length ) ); + } + catch(DecoderFallbackException) + { + result = new MessagePackString( asBinary, true ); + } + + return true; + } + +#if FEATURE_TAP + + private Task>> ReadRawStringCoreAsync( int length, int offset, CancellationToken cancellationToken ) + { + MessagePackString result; + if ( !this.ReadRawStringCore( length, ref offset, out result ) ) + { + return Task.FromResult( AsyncReadResult.Fail>() ); + } + + return Task.FromResult( AsyncReadResult.Success( result, offset ) ); + } + +#endif // FEATURE_TAP + + private bool Drain( uint size ) + { + if ( this._source.Length - this._offset < size ) + { + return false; + } + + if ( this._offset + size > Int32.MaxValue ) + { + return false; + } + + this._offset += unchecked(( int )size); + return true; + } + +#if FEATURE_TAP + + private Task DrainAsync( uint size, CancellationToken cancellationToken ) + { + return Task.FromResult( this.Drain( size ) ); + } + +#endif // FEATURE_TAP + + bool IRootUnpacker.ReadObject(bool isDeep, out MessagePackObject result) + { + return this.ReadObject( isDeep, out result ); + } + } +} diff --git a/src/MsgPack/MessagePackCode.cs b/src/MsgPack/MessagePackCode.cs index 4a2aa4f89..0ca7a0ab9 100644 --- a/src/MsgPack/MessagePackCode.cs +++ b/src/MsgPack/MessagePackCode.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,11 +18,20 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; namespace MsgPack { - internal static class MessagePackCode +#if UNITY && DEBUG + public +#else + internal +#endif + static class MessagePackCode { public const int NilValue = 0xc0; public const int TrueValue = 0xc3; diff --git a/src/MsgPack/MessagePackConvert.cs b/src/MsgPack/MessagePackConvert.cs index 04f406c80..0f8d546ca 100644 --- a/src/MsgPack/MessagePackConvert.cs +++ b/src/MsgPack/MessagePackConvert.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Text; namespace MsgPack diff --git a/src/MsgPack/MessagePackExtendedTypeObject.cs b/src/MsgPack/MessagePackExtendedTypeObject.cs index 2d3ae95d0..dc96efbcf 100644 --- a/src/MsgPack/MessagePackExtendedTypeObject.cs +++ b/src/MsgPack/MessagePackExtendedTypeObject.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Text; @@ -55,7 +59,12 @@ public byte TypeCode /// /// A binary value portion of this object. This value will not be null. /// - internal byte[] Body +#if UNITY && DEBUG + public +#else + internal +#endif + byte[] Body { get { return this._body ?? Binary.Empty; } } @@ -155,7 +164,12 @@ public override string ToString() return buffer.ToString(); } - internal void ToString( StringBuilder buffer, bool isJson ) +#if UNITY && DEBUG + public +#else + internal +#endif + void ToString( StringBuilder buffer, bool isJson ) { if ( isJson ) { diff --git a/src/MsgPack/MessagePackObject.Utilities.cs b/src/MsgPack/MessagePackObject.Utilities.cs index cc180c737..545fe5486 100644 --- a/src/MsgPack/MessagePackObject.Utilities.cs +++ b/src/MsgPack/MessagePackObject.Utilities.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,11 +25,11 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || !UNITY +#endif // CORE_CLR || !UNITY || NETSTANDARD1_1 using System.Globalization; using System.Linq; #if NETFX_CORE @@ -44,9 +44,9 @@ namespace MsgPack { -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 [Serializable] -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 partial struct MessagePackObject : IPackable #if FEATURE_TAP , IAsyncPackable @@ -196,7 +196,12 @@ public MessagePackObject( MessagePackObjectDictionary value, bool isImmutable ) /// Initializes a new instance wraps . /// /// which represents byte array or UTF-8 encoded string. - internal MessagePackObject( MessagePackString messagePackString ) +#if UNITY && DEBUG + public +#else + internal +#endif + MessagePackObject( MessagePackString messagePackString ) { // trick: Avoid long boilerplate initialization. See "CLR via C#". this = new MessagePackObject(); @@ -922,7 +927,7 @@ private static void ToStringBinary( StringBuilder buffer, bool isJson, MessagePa } // Lifting support. -#if ( NETSTANDARD1_1 || NETSTANDARD1_3 ) && !XAMARIN +#if ( NETSTANDARD1_1 || NETSTANDARD1_3 ) switch ( NetStandardCompatibility.GetTypeCode( type ) ) #else switch ( Type.GetTypeCode( type ) ) @@ -1037,6 +1042,14 @@ public Type UnderlyingType { return asMps.GetUnderlyingType(); } + else if ( this._handleOrTypeCode is byte[] ) + { + // It should be MPETO +#if DEBUG + Contract.Assert( ( this._value & 0xFFFFFFFFFFFFFF00 ) == 0, "( " + this._value.ToString( "X16" ) + " & 0xFFFFFFFFFFFFFF00 ) != 0" ); +#endif // DEBUG + return typeof( MessagePackExtendedTypeObject ); + } else { return this._handleOrTypeCode.GetType(); @@ -1355,7 +1368,7 @@ public string AsString( Encoding encoding ) return null; } - VerifyUnderlyingType( this, null ); + VerifyUnderlyingRawType( this, null ); try { @@ -1395,7 +1408,7 @@ public string AsStringUtf8() /// public string AsStringUtf16() { - VerifyUnderlyingType( this, null ); + VerifyUnderlyingRawType( this, null ); Contract.EndContractBlock(); if ( this.IsNil ) @@ -1509,6 +1522,10 @@ public MessagePackObjectDictionary AsDictionary() private static void VerifyUnderlyingType( MessagePackObject instance, string parameterName ) { +#if DEBUG + Contract.Assert( typeof( T ) != typeof( MessagePackString ), "Should use VerifyUnderlyingRawType()" ); +#endif // DEBUG + if ( instance.IsNil ) { if ( !typeof( T ).GetIsValueType() || Nullable.GetUnderlyingType( typeof( T ) ) != null ) @@ -1540,6 +1557,24 @@ private static void VerifyUnderlyingType( MessagePackObject instance, string } } + private static void VerifyUnderlyingRawType( MessagePackObject instance, string parameterName ) + { + if ( instance._handleOrTypeCode == null || instance._handleOrTypeCode is MessagePackString ) + { + // nil or MPS (eventually string or byte[]) + return; + } + + if ( parameterName != null ) + { + throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Do not convert {0} MessagePackObject to {1}.", instance.UnderlyingType, typeof( T ) ), parameterName ); + } + else + { + ThrowInvalidTypeAs( instance ); + } + } + private static void ThrowCannotBeNilAs() { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "Do not convert nil MessagePackObject to {0}.", typeof( T ) ) ); @@ -1785,6 +1820,23 @@ public object ToObject() } } + /// + /// Gets a this object as a value. + /// + /// A value. + /// This object does not represent value. + public Timestamp AsTimestamp() + { + try + { + return Timestamp.Decode( this.AsMessagePackExtendedTypeObject() ); + } + catch(ArgumentException ex) + { + throw new InvalidOperationException( ex.Message, ex ); + } + } + #region -- Structure Operator Overloads -- /// @@ -1831,7 +1883,12 @@ public static implicit operator MessagePackObject( MessagePackObject[] value ) #endregion -- Conversion Operator Overloads -- #if DEBUG - internal string DebugDump() +#if UNITY && DEBUG + public +#else + internal +#endif + string DebugDump() { var typeCode = this._handleOrTypeCode as ValueTypeCode; if ( typeCode != null ) @@ -1850,7 +1907,7 @@ internal string DebugDump() #endif // DEBUG #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 - [Serializable] + [ Serializable ] #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 private enum MessagePackValueTypeCode { diff --git a/src/MsgPack/MessagePackObject.cs b/src/MsgPack/MessagePackObject.cs index 54502d377..293b71231 100644 --- a/src/MsgPack/MessagePackObject.cs +++ b/src/MsgPack/MessagePackObject.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Runtime.InteropServices; namespace MsgPack @@ -774,7 +774,7 @@ public Double AsDouble() /// instance corresponds to this instance. public String AsString() { - VerifyUnderlyingType( this, null ); + VerifyUnderlyingRawType( this, null ); if( this._handleOrTypeCode == null ) { @@ -793,7 +793,7 @@ public String AsString() /// [] instance corresponds to this instance. public Byte[] AsBinary() { - VerifyUnderlyingType( this, null ); + VerifyUnderlyingRawType( this, null ); if( this._handleOrTypeCode == null ) { @@ -1603,7 +1603,7 @@ public static explicit operator Double( MessagePackObject value ) /// instance corresponds to . public static explicit operator String( MessagePackObject value ) { - VerifyUnderlyingType( value, "value" ); + VerifyUnderlyingRawType( value, "value" ); if( value._handleOrTypeCode == null ) { @@ -1623,7 +1623,7 @@ public static explicit operator String( MessagePackObject value ) /// [] instance corresponds to . public static explicit operator Byte[]( MessagePackObject value ) { - VerifyUnderlyingType( value, "value" ); + VerifyUnderlyingRawType( value, "value" ); if( value._handleOrTypeCode == null ) { diff --git a/src/MsgPack/MessagePackObject.tt b/src/MsgPack/MessagePackObject.tt index c9cb8d140..b63659ea2 100644 --- a/src/MsgPack/MessagePackObject.tt +++ b/src/MsgPack/MessagePackObject.tt @@ -1,4 +1,4 @@ -<# +<# // // MessagePack for CLI // @@ -79,11 +79,11 @@ Func IsNotCLSCompliant = #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Runtime.InteropServices; namespace MsgPack @@ -408,7 +408,7 @@ private void GenerateAsT( string val, Object typeOrTypeName, bool passParameterN else if ( t == typeof( byte[] ) ) { #> - VerifyUnderlyingType( <#= val #>, <#= passParameterName ? "\"" + val + "\"" : "null" #> ); + VerifyUnderlyingRawType( <#= val #>, <#= passParameterName ? "\"" + val + "\"" : "null" #> ); if( <#= val #>._handleOrTypeCode == null ) { @@ -424,7 +424,7 @@ private void GenerateAsT( string val, Object typeOrTypeName, bool passParameterN else if ( t == typeof( string ) ) { #> - VerifyUnderlyingType( <#= val #>, <#= passParameterName ? "\"" + val + "\"" : "null" #> ); + VerifyUnderlyingRawType( <#= val #>, <#= passParameterName ? "\"" + val + "\"" : "null" #> ); if( <#= val #>._handleOrTypeCode == null ) { @@ -646,4 +646,4 @@ private static string GetTypeName( object typeOrTypeName ) { return ( typeOrTypeName as string ) ?? ( typeOrTypeName as Type ).Name; } -#> \ No newline at end of file +#> diff --git a/src/MsgPack/MessagePackObjectDictionary.Enumerator.cs b/src/MsgPack/MessagePackObjectDictionary.Enumerator.cs index 8bb56b925..92cf34824 100644 --- a/src/MsgPack/MessagePackObjectDictionary.Enumerator.cs +++ b/src/MsgPack/MessagePackObjectDictionary.Enumerator.cs @@ -25,11 +25,11 @@ using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack { diff --git a/src/MsgPack/MessagePackObjectDictionary.KeySet.Enumerator.cs b/src/MsgPack/MessagePackObjectDictionary.KeySet.Enumerator.cs index 71b92b5b3..0c7a6d8e6 100644 --- a/src/MsgPack/MessagePackObjectDictionary.KeySet.Enumerator.cs +++ b/src/MsgPack/MessagePackObjectDictionary.KeySet.Enumerator.cs @@ -25,11 +25,11 @@ using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack { @@ -127,4 +127,4 @@ void IEnumerator.Reset() } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/MessagePackObjectDictionary.KeySet.cs b/src/MsgPack/MessagePackObjectDictionary.KeySet.cs index 91d67cc13..a285eed4b 100644 --- a/src/MsgPack/MessagePackObjectDictionary.KeySet.cs +++ b/src/MsgPack/MessagePackObjectDictionary.KeySet.cs @@ -27,11 +27,11 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack { @@ -48,9 +48,9 @@ partial class MessagePackObjectDictionary [SuppressMessage( "Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "ICollection implementing dictionary should return ICollection implementing values." )] #if !UNITY public sealed partial class KeySet : -#if !NETFX_35 +#if !NET35 ISet, -#endif // !NETFX_35 +#endif // !NET35 #else public sealed partial class KeyCollection : #endif // !UNITY @@ -219,7 +219,7 @@ bool ICollection.Remove( MessagePackObject item ) } #if !UNITY -#if !NETFX_35 +#if !NET35 bool ISet.Add( MessagePackObject item ) { throw new NotSupportedException(); @@ -234,7 +234,7 @@ void ISet.IntersectWith( IEnumerable other { throw new NotSupportedException(); } -#endif // !NETFX_35 +#endif // !NET35 /// /// Determines whether this set is proper subset of the specified collection. @@ -338,7 +338,7 @@ public bool SetEquals( IEnumerable other ) return SetOperation.SetEquals( this, other ); } -#if !NETFX_35 +#if !NET35 void ISet.SymmetricExceptWith( IEnumerable other ) { throw new NotSupportedException(); @@ -348,7 +348,7 @@ void ISet.UnionWith( IEnumerable other ) { throw new NotSupportedException(); } -#endif // !NETFX_35 +#endif // !NET35 #endif // !UNITY /// @@ -373,4 +373,4 @@ IEnumerator IEnumerable.GetEnumerator() } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/MessagePackObjectDictionary.ValueCollection.Enumerator.cs b/src/MsgPack/MessagePackObjectDictionary.ValueCollection.Enumerator.cs index 00d919f77..47f9dd0ff 100644 --- a/src/MsgPack/MessagePackObjectDictionary.ValueCollection.Enumerator.cs +++ b/src/MsgPack/MessagePackObjectDictionary.ValueCollection.Enumerator.cs @@ -25,11 +25,11 @@ using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack { diff --git a/src/MsgPack/MessagePackObjectDictionary.ValueCollection.cs b/src/MsgPack/MessagePackObjectDictionary.ValueCollection.cs index b9cd8e723..a2db23d50 100644 --- a/src/MsgPack/MessagePackObjectDictionary.ValueCollection.cs +++ b/src/MsgPack/MessagePackObjectDictionary.ValueCollection.cs @@ -27,11 +27,11 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack { diff --git a/src/MsgPack/MessagePackObjectDictionary.cs b/src/MsgPack/MessagePackObjectDictionary.cs index 6b82bdec4..9a244f73d 100644 --- a/src/MsgPack/MessagePackObjectDictionary.cs +++ b/src/MsgPack/MessagePackObjectDictionary.cs @@ -27,11 +27,11 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; @@ -481,7 +481,7 @@ private static MessagePackObject ValidateObjectArgument( object obj, string para return new MessagePackObject( asMessagePackString ); } -#if ( NETSTANDARD1_1 || NETSTANDARD1_3 ) && !XAMARIN +#if ( NETSTANDARD1_1 || NETSTANDARD1_3 ) switch ( NetStandardCompatibility.GetTypeCode( value.GetType() ) ) #else switch ( Type.GetTypeCode( value.GetType() ) ) diff --git a/src/MsgPack/MessagePackObjectEqualityComparer.cs b/src/MsgPack/MessagePackObjectEqualityComparer.cs index 29dcc4993..2f7551510 100644 --- a/src/MsgPack/MessagePackObjectEqualityComparer.cs +++ b/src/MsgPack/MessagePackObjectEqualityComparer.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Collections.Generic; @@ -29,11 +33,21 @@ namespace MsgPack #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 [Serializable] #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 - public sealed class MessagePackObjectEqualityComparer : IEqualityComparer +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class MessagePackObjectEqualityComparer : IEqualityComparer { private static readonly MessagePackObjectEqualityComparer _instance = new MessagePackObjectEqualityComparer(); - internal static MessagePackObjectEqualityComparer Instance +#if UNITY && DEBUG + public +#else + internal +#endif + static MessagePackObjectEqualityComparer Instance { get { return _instance; } } diff --git a/src/MsgPack/MessagePackPackerCommon.ttinclude b/src/MsgPack/MessagePackPackerCommon.ttinclude new file mode 100644 index 000000000..bc0a66ffb --- /dev/null +++ b/src/MsgPack/MessagePackPackerCommon.ttinclude @@ -0,0 +1,614 @@ +<#@ include file="..\Core.ttinclude" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Runtime.InteropServices" #> +<#@ import namespace="System.Text" #> +<#+ +// +// MessagePack for CLI +// +// Copyright (C) 2010-2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +private void WriteOverrides() +{ + var ints = + new HashSet + { + typeof( byte ), typeof( sbyte ), + typeof( short ), typeof( ushort ), + typeof( int ), typeof( uint ), + typeof( long ), typeof( ulong ), + }; + + var signedInts = + new HashSet + { + typeof( sbyte ), + typeof( short ), + typeof( int ), + typeof( long ), + }; + + foreach ( var isAsync in new [] { false, true } ) + { + if ( isAsync ) + { +#> +#if FEATURE_TAP + +<#+ + } + + foreach ( var type in + new [] + { + typeof( bool ), + typeof( byte ), typeof( sbyte ), + typeof( short ), typeof( ushort ), + typeof( int ), typeof( uint ), + typeof( long ), typeof( ulong ), + typeof( float ), typeof( double ), + } + ) + { +#> + <#= AsyncPack( type, isAsync ) #> + { +<#+ + if ( ints.Contains( type ) ) + { + if ( type.Name.EndsWith( "64" ) ) + { +#> + if ( ( value & 0x000000000000007FL ) == value ) +<#+ + } + else + { +#> + if ( ( value & 0x0000007F ) == value ) +<#+ + } +#> + { + // Positive fix num + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( unchecked( ( byte )( value & 0xFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // if ints + + if ( signedInts.Contains( type ) ) + { + if ( type.Name.EndsWith( "64" ) ) + { +#> + if ( ( ~value & unchecked( ( long )0xFFFFFFFFFFFFFFE0 ) ) == 0 ) +<#+ + } + else + { +#> + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) +<#+ + } +#> + { + // Negative fix num + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( unchecked( ( byte )( value & 0xFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // if signedInts + + if ( type == typeof( bool ) ) + { +#> + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; +<#+ + } + else + { + if ( ints.Contains( type ) ) + { + // Use compact expression as possible + + var size = Marshal.SizeOf( type ); + var isSigned = signedInts.Contains( type ); + + if ( isSigned ) + { +#> + if ( value < 0 ) + { +<#+ + for ( var bytes = 1; bytes < size; bytes *= 2 ) + { + var mask = new String( Enumerable.Repeat( 'F', bytes * 2 ).ToArray() ); +#> + if ( value >= <#= ToTypeName( true, bytes ) #>.MinValue ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= ToCodeName( isSigned, bytes ) #>, unchecked( ( <#= ToTypeName( false, bytes ) #> )( value & 0x<#= mask #> ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // for +#> + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= ToCodeName( type.Name ) #>, unchecked( ( <#= ToUnsigned( type ) #> )value )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // isSigned + + for ( var bytes = 1; bytes < size; bytes *= 2 ) + { + var mask = new String( Enumerable.Repeat( 'F', bytes * 2 ).ToArray() ); +#> + if ( value <= <#= ToTypeName( isSigned, bytes ) #>.MaxValue ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= ToCodeName( isSigned, bytes ) #>, unchecked( ( <#= ToTypeName( false, bytes ) #> )( value & 0x<#= mask #> ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // for + } // if ints +#> + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= ToCodeName( type.Name ) #>, unchecked( ( <#= ToUnsigned( type ) #> )value )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; +<#+ + } // if type == typeof( bool ) +#> + } + +<#+ + } // foreach type (scalar) + + foreach ( var prefix in new [] { "Array", "Map" } ) + { +#> + <#= AsyncMethod( isAsync, "void", "Pack" + prefix + "Header", "int length", true ) #> + { + if ( length < 0x10 ) + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( unchecked( ( byte )( MessagePackCode.MinimumFixed<#= prefix #> | length ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + if ( length < 0x10000 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= prefix #>16, unchecked( ( ushort )( length & 0xFFFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= prefix #>32, unchecked( ( uint )length )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // foreach prefix + +#> + <#= AsyncMethod( isAsync, "void", "PackStringHeader", "int length", true ) #> + { + if ( length < 0x20 ) + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + if ( length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Str8, unchecked( ( byte )( length & 0xFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + if ( length < 0x10000 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( length & 0xFFFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Str32, unchecked( ( uint )length )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + <#= AsyncMethod( isAsync, "void", "PackBinaryHeader", "int length", true ) #> + { + if ( length < 0x100 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( length & 0xFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + if ( length < 0x10000 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( length & 0xFFFF ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Bin32, unchecked( ( uint )length )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + + // TODO: ReadOnlySpan, ReadOnlySpan + +#> + <#= AsyncMethod( isAsync, "void", "PackRaw", "string value", true ) #> + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( value, ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + } + +<#+ + + foreach ( var isRaw in new [] { true, false } ) + { + var suffix = isRaw ? "Raw" : "Binary"; + var code = isRaw ? "Str" : "Bin"; +#> + <#= AsyncMethod( isAsync, "void", "Pack" + suffix, "byte[] value", true ) #> + { +<#+ + if ( isRaw ) + { +#> + if ( value.Length < 0x20 ) + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | value.Length ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( value<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // if spec.IsRaw +#> + if ( value.Length < 0x100<#= isRaw ? " && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0" : String.Empty #> ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= code #>8, unchecked( ( byte )( value.Length ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( value<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + if ( value.Length < 0x10000 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= code #>16, unchecked( ( ushort )( value.Length ) )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( value<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.<#= code #>32, unchecked( ( uint )value.Length )<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( value<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + return; + } + +<#+ + } // foreach spec + + // TODO: ReadOnlySpan +#> + <#= AsyncMethod( isAsync, "void", "PackExtendedTypeValue", "byte typeCode, byte[] body", true ) #> + { + unchecked + { + switch ( body.Length ) + { + case 1: + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.FixExt1<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + break; + } + case 2: + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.FixExt2<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + break; + } + case 4: + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.FixExt4<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + break; + } + case 8: + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.FixExt8<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + break; + } + case 16: + { + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.FixExt16<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + break; + } + default: + { + if ( body.Length < 0x100 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Ext8, ( byte )body.Length<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + } + else if ( body.Length < 0x10000 ) + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Ext16, ( ushort )body.Length<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + } + else + { + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( ( byte )MessagePackCode.Ext32, ( uint )body.Length<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + } + + break; + } + } // switch + } // unchecked + + <#= Await( isAsync ) #>this.WriteByte<#= Suffix( isAsync ) #>( typeCode<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>this.WriteBytes<#= Suffix( isAsync ) #>( body<#= Argument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + } + +<#+ + + if ( isAsync ) + { +#> +#endif // FEATURE_TAP +<#+ + } + + } // foreach isAsync +#> + + private void WriteStringHeader( int bytesLength, bool allowStr8 ) + { + if( bytesLength < 0x20 ) + { + this.WriteByte( ( byte )( bytesLength | MessagePackCode.MinimumFixedRaw ) ); + return; + } + + if ( bytesLength < 0x100 && allowStr8 ) + { + this.WriteBytes( MessagePackCode.Str8, ( byte )bytesLength ); + return; + } + + if ( bytesLength < 0x10000 ) + { + this.WriteBytes( MessagePackCode.Str16, ( ushort )bytesLength ); + return; + } + + this.WriteBytes( MessagePackCode.Str32, unchecked( ( uint )bytesLength ) ); + } + +<#+ +} + +private static string AsyncPack( Type type, bool isAsync ) +{ + return + AsyncMethod( + isAsync, + "void", + "Pack", + String.Format( + CultureInfo.InvariantCulture, + "{0} value", + type.Name + ), + true + ); +} + +private static string AsyncMethod( bool isAsync, string returnType, string name, string parameterList, bool isOverride ) +{ + var realReturnType = returnType; + if ( isAsync ) + { + realReturnType = "Task" + ( returnType == "void" ? String.Empty : ( "<" + returnType + ">" ) ); + } + + return + String.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}{3}{4}( {5}{6} )", + isOverride ? "protected override" : "private", + ( isAsync ? "async " : String.Empty ) + realReturnType, + name, + isAsync ? "Async" : String.Empty, + isOverride ? "Core" : String.Empty, + parameterList, + isAsync ? ", CancellationToken cancellationToken" : String.Empty + ); +} + +private static string NonAsyncMethod( bool isAsync, string returnType, string name, string parameterList, bool isOverride ) +{ + var realReturnType = returnType; + if ( isAsync ) + { + realReturnType = "Task" + ( returnType == "void" ? String.Empty : ( "<" + returnType + ">" ) ); + } + + return + String.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}{3}{4}( {5}{6} )", + isOverride ? "protected override" : "private", + realReturnType, + name, + isAsync ? "Async" : String.Empty, + isOverride ? "Core" : String.Empty, + parameterList, + isAsync ? ", CancellationToken cancellationToken" : String.Empty + ); +} + +private static string Await( bool isAsync ) +{ + return isAsync ? "await " : String.Empty; +} + +private static string Suffix( bool isAsync ) +{ + return isAsync ? "Async" : String.Empty; +} + +private static string Argument( bool isAsync ) +{ + return isAsync ? ", cancellationToken" : String.Empty; +} + +private static string ConfigureAwait( bool isAsync ) +{ + return isAsync ? ".ConfigureAwait( false )" : String.Empty; +} + +private static string ToTypeName( bool isSigned, int bytes ) +{ + switch ( bytes ) + { + case 1: + { + return isSigned ? "SByte" : "Byte"; + } + default: + { + return ( isSigned ? "Int" : "UInt" ) + ( bytes * 8 ).ToString( CultureInfo.InvariantCulture ); + } + } +} + +private static string ToCodeName( bool isSigned, int bytes ) +{ + return ( isSigned ? "Signed" : "Unsigned" ) + "Int" + ( bytes * 8 ).ToString( CultureInfo.InvariantCulture ); +} + +private static string ToCodeName( string typeName ) +{ + switch ( typeName ) + { + case "Byte": + { + return "UnsignedInt8"; + } + case "SByte": + { + return "SignedInt8"; + } + case "Single": + { + return "Real32"; + } + case "Double": + { + return "Real64"; + } + default: + { + return typeName.Replace( "Int", "SignedInt" ).Replace( "USigned", "Unsigned" ); + } + } +} + +private static string ToUnsigned( Type type ) +{ + switch ( type.Name ) + { + case "Byte": + case "UInt16": + case "UInt32": + case "UInt64": + case "Single": + case "Double": + { + return type.Name; + } + case "SByte": + { + return "Byte"; + } + case "Int16": + case "Int32": + case "Int64": + { + return "U" + type.Name; + } + default: + { + throw new Exception( "unexpected type " + type ); + } + } +} + +private static readonly string[] scalarTypes = + new [] + { + "byte", + "ushort", + "uint", + "ulong", + "float", + "double" + }; + +private static readonly HashSet nonBulletables = + new HashSet + { + "float", + "double" + }; + +private static readonly Dictionary lengthes = + new Dictionary + { + { "byte", 1 }, + { "ushort", 2 }, + { "uint", 4 }, + { "ulong", 8 }, + { "float", 4 }, + { "double", 8 } + }; + +private void WriteToBits( string type, string variable, out string bitsVariableName ) +{ + if ( nonBulletables.Contains( type ) ) + { +#> + var bits = Binary.ToBits( <#= variable #> ); +<#+ + bitsVariableName = "bits"; + } + else + { + bitsVariableName = variable; + } +} + +private void WriteShiftCore( int index, int bytesLengthOfType, string variable, string buffer, Func offsetGenerator ) +{ + var shiftSize = ( bytesLengthOfType - index - 1 ) * 8; + var shift = shiftSize == 0 ? String.Empty : ( " >> " + shiftSize.ToString( CultureInfo.InvariantCulture ) ); +#> + <#= buffer #>[ <#= offsetGenerator( index ) #> ] = unchecked( ( byte )( <#= variable #><#= shift #> & 0xFF ) ); +<#+ +} +#> diff --git a/src/MsgPack/MessagePackStreamPacker.Pack.cs b/src/MsgPack/MessagePackStreamPacker.Pack.cs new file mode 100644 index 000000000..4e420d7ed --- /dev/null +++ b/src/MsgPack/MessagePackStreamPacker.Pack.cs @@ -0,0 +1,1292 @@ + +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + // This file was generated from MessagePackStreamPacker.Pack.tt and MessagePackPackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackStreamPacker.Pack.tt and MessagePackPackerCommon.ttinclude instead. + + partial class MessagePackStreamPacker + { + protected override void PackCore( Boolean value ) + { + this.WriteByte( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue ); + } + + protected override void PackCore( Byte value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )value ) ); + } + + protected override void PackCore( SByte value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ) ); + } + + protected override void PackCore( Int16 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ) ); + return; + } + + if ( value <= SByte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ) ); + } + + protected override void PackCore( UInt16 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Byte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )value ) ); + } + + protected override void PackCore( Int32 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value >= Int16.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ) ); + return; + } + + if ( value <= SByte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Int16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ) ); + } + + protected override void PackCore( UInt32 value ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Byte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )value ) ); + } + + protected override void PackCore( Int64 value ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( ( ~value & unchecked( ( long )0xFFFFFFFFFFFFFFE0 ) ) == 0 ) + { + // Negative fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value >= Int16.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + if ( value >= Int32.MinValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ) ); + return; + } + + if ( value <= SByte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Int16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + if ( value <= Int32.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ) ); + } + + protected override void PackCore( UInt64 value ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + this.WriteByte( unchecked( ( byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= Byte.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ) ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ) ); + return; + } + + if ( value <= UInt32.MaxValue ) + { + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.UnsignedInt64, unchecked( ( UInt64 )value ) ); + } + + protected override void PackCore( Single value ) + { + this.WriteBytes( ( byte )MessagePackCode.Real32, unchecked( ( Single )value ) ); + } + + protected override void PackCore( Double value ) + { + this.WriteBytes( ( byte )MessagePackCode.Real64, unchecked( ( Double )value ) ); + } + + protected override void PackArrayHeaderCore( int length ) + { + if ( length < 0x10 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedArray | length ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Array16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Array32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackMapHeaderCore( int length ) + { + if ( length < 0x10 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedMap | length ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Map16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Map32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackStringHeaderCore( int length ) + { + if ( length < 0x20 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ) ); + return; + } + + if ( length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str8, unchecked( ( byte )( length & 0xFF ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Str32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackBinaryHeaderCore( int length ) + { + if ( length < 0x100 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( length & 0xFF ) ) ); + return; + } + + if ( length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( length & 0xFFFF ) ) ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Bin32, unchecked( ( uint )length ) ); + return; + } + + protected override void PackRawCore( string value ) + { + this.WriteBytes( value, ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ); + } + + protected override void PackRawCore( byte[] value ) + { + if ( value.Length < 0x20 ) + { + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + if ( value.Length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str8, unchecked( ( byte )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + if ( value.Length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Str32, unchecked( ( uint )value.Length ) ); + this.WriteBytes( value ); + return; + } + + protected override void PackBinaryCore( byte[] value ) + { + if ( value.Length < 0x100 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + if ( value.Length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( value.Length ) ) ); + this.WriteBytes( value ); + return; + } + + this.WriteBytes( ( byte )MessagePackCode.Bin32, unchecked( ( uint )value.Length ) ); + this.WriteBytes( value ); + return; + } + + protected override void PackExtendedTypeValueCore( byte typeCode, byte[] body ) + { + unchecked + { + switch ( body.Length ) + { + case 1: + { + this.WriteByte( ( byte )MessagePackCode.FixExt1 ); + break; + } + case 2: + { + this.WriteByte( ( byte )MessagePackCode.FixExt2 ); + break; + } + case 4: + { + this.WriteByte( ( byte )MessagePackCode.FixExt4 ); + break; + } + case 8: + { + this.WriteByte( ( byte )MessagePackCode.FixExt8 ); + break; + } + case 16: + { + this.WriteByte( ( byte )MessagePackCode.FixExt16 ); + break; + } + default: + { + if ( body.Length < 0x100 ) + { + this.WriteBytes( ( byte )MessagePackCode.Ext8, ( byte )body.Length ); + } + else if ( body.Length < 0x10000 ) + { + this.WriteBytes( ( byte )MessagePackCode.Ext16, ( ushort )body.Length ); + } + else + { + this.WriteBytes( ( byte )MessagePackCode.Ext32, ( uint )body.Length ); + } + + break; + } + } // switch + } // unchecked + + this.WriteByte( typeCode ); + this.WriteBytes( body ); + } + +#if FEATURE_TAP + + protected override async Task PackAsyncCore( Boolean value, CancellationToken cancellationToken ) + { + await this.WriteByteAsync( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue, cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Byte value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( SByte value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Int16 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= SByte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( UInt16 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Byte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Int32 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & 0xFFFFFFE0 ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value >= Int16.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= SByte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Int16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( UInt32 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x0000007F ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Byte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Int64 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( ( ~value & unchecked( ( long )0xFFFFFFFFFFFFFFE0 ) ) == 0 ) + { + // Negative fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value < 0 ) + { + if ( value >= SByte.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value >= Int16.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value >= Int32.MinValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= SByte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Int16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Int32.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.SignedInt64, unchecked( ( UInt64 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( UInt64 value, CancellationToken cancellationToken ) + { + if ( ( value & 0x000000000000007FL ) == value ) + { + // Positive fix num + await this.WriteByteAsync( unchecked( ( byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= Byte.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt8, unchecked( ( Byte )( value & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= UInt16.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt16, unchecked( ( UInt16 )( value & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value <= UInt32.MaxValue ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt32, unchecked( ( UInt32 )( value & 0xFFFFFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.UnsignedInt64, unchecked( ( UInt64 )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Single value, CancellationToken cancellationToken ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Real32, unchecked( ( Single )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackAsyncCore( Double value, CancellationToken cancellationToken ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Real64, unchecked( ( Double )value ), cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackArrayHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x10 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedArray | length ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Array16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Array32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackMapHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x10 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedMap | length ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Map16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Map32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackStringHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x20 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str8, unchecked( ( byte )( length & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Str32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackBinaryHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { + if ( length < 0x100 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( length & 0xFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( length & 0xFFFF ) ), cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin32, unchecked( ( uint )length ), cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackRawAsyncCore( string value, CancellationToken cancellationToken ) + { + await this.WriteBytesAsync( value, ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0, cancellationToken ).ConfigureAwait( false ); + } + + protected override async Task PackRawAsyncCore( byte[] value, CancellationToken cancellationToken ) + { + if ( value.Length < 0x20 ) + { + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value.Length < 0x100 && ( this.CompatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str8, unchecked( ( byte )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value.Length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Str16, unchecked( ( ushort )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Str32, unchecked( ( uint )value.Length ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackBinaryAsyncCore( byte[] value, CancellationToken cancellationToken ) + { + if ( value.Length < 0x100 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin8, unchecked( ( byte )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( value.Length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin16, unchecked( ( ushort )( value.Length ) ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( ( byte )MessagePackCode.Bin32, unchecked( ( uint )value.Length ), cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return; + } + + protected override async Task PackExtendedTypeValueAsyncCore( byte typeCode, byte[] body, CancellationToken cancellationToken ) + { + unchecked + { + switch ( body.Length ) + { + case 1: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt1, cancellationToken ).ConfigureAwait( false ); + break; + } + case 2: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt2, cancellationToken ).ConfigureAwait( false ); + break; + } + case 4: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt4, cancellationToken ).ConfigureAwait( false ); + break; + } + case 8: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt8, cancellationToken ).ConfigureAwait( false ); + break; + } + case 16: + { + await this.WriteByteAsync( ( byte )MessagePackCode.FixExt16, cancellationToken ).ConfigureAwait( false ); + break; + } + default: + { + if ( body.Length < 0x100 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Ext8, ( byte )body.Length, cancellationToken ).ConfigureAwait( false ); + } + else if ( body.Length < 0x10000 ) + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Ext16, ( ushort )body.Length, cancellationToken ).ConfigureAwait( false ); + } + else + { + await this.WriteBytesAsync( ( byte )MessagePackCode.Ext32, ( uint )body.Length, cancellationToken ).ConfigureAwait( false ); + } + + break; + } + } // switch + } // unchecked + + await this.WriteByteAsync( typeCode, cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( body, cancellationToken ).ConfigureAwait( false ); + } + +#endif // FEATURE_TAP + + private void WriteStringHeader( int bytesLength, bool allowStr8 ) + { + if( bytesLength < 0x20 ) + { + this.WriteByte( ( byte )( bytesLength | MessagePackCode.MinimumFixedRaw ) ); + return; + } + + if ( bytesLength < 0x100 && allowStr8 ) + { + this.WriteBytes( MessagePackCode.Str8, ( byte )bytesLength ); + return; + } + + if ( bytesLength < 0x10000 ) + { + this.WriteBytes( MessagePackCode.Str16, ( ushort )bytesLength ); + return; + } + + this.WriteBytes( MessagePackCode.Str32, unchecked( ( uint )bytesLength ) ); + } + +#if FEATURE_TAP + + private async Task WriteStringHeaderAsync( int bytesLength, bool allowStr8, CancellationToken cancellationToken ) + { + if( bytesLength < 0x20 ) + { + await this.WriteByteAsync( ( byte )( bytesLength | MessagePackCode.MinimumFixedRaw ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( bytesLength < 0x100 && allowStr8 ) + { + await this.WriteBytesAsync( MessagePackCode.Str8, ( byte )bytesLength, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( bytesLength < 0x10000 ) + { + await this.WriteBytesAsync( MessagePackCode.Str16, ( ushort )bytesLength, cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( MessagePackCode.Str32, unchecked(( uint )bytesLength), cancellationToken ).ConfigureAwait( false ); + } + +#endif // FEATURE_TAP + + private void WriteBytes( byte header, byte value ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value & 0xFF ) ); + this.WriteBytes( this._scalarBuffer, 0, sizeof( byte ) + 1 ); + } + + private void WriteBytes( byte header, ushort value ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value >> 8 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( value & 0xFF ) ); + this.WriteBytes( this._scalarBuffer, 0, sizeof( ushort ) + 1 ); + } + + private void WriteBytes( byte header, uint value ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value >> 24 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( value >> 16 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( value >> 8 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( value & 0xFF ) ); + this.WriteBytes( this._scalarBuffer, 0, sizeof( uint ) + 1 ); + } + + private void WriteBytes( byte header, ulong value ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value >> 56 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( value >> 48 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( value >> 40 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( value >> 32 & 0xFF ) ); + this._scalarBuffer[ 5 ] = unchecked( ( byte )( value >> 24 & 0xFF ) ); + this._scalarBuffer[ 6 ] = unchecked( ( byte )( value >> 16 & 0xFF ) ); + this._scalarBuffer[ 7 ] = unchecked( ( byte )( value >> 8 & 0xFF ) ); + this._scalarBuffer[ 8 ] = unchecked( ( byte )( value & 0xFF ) ); + this.WriteBytes( this._scalarBuffer, 0, sizeof( ulong ) + 1 ); + } + + private void WriteBytes( byte header, float value ) + { + var bits = Binary.ToBits( value ); + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( bits >> 24 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( bits >> 16 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( bits >> 8 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( bits & 0xFF ) ); + this.WriteBytes( this._scalarBuffer, 0, sizeof( float ) + 1 ); + } + + private void WriteBytes( byte header, double value ) + { + var bits = Binary.ToBits( value ); + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( bits >> 56 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( bits >> 48 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( bits >> 40 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( bits >> 32 & 0xFF ) ); + this._scalarBuffer[ 5 ] = unchecked( ( byte )( bits >> 24 & 0xFF ) ); + this._scalarBuffer[ 6 ] = unchecked( ( byte )( bits >> 16 & 0xFF ) ); + this._scalarBuffer[ 7 ] = unchecked( ( byte )( bits >> 8 & 0xFF ) ); + this._scalarBuffer[ 8 ] = unchecked( ( byte )( bits & 0xFF ) ); + this.WriteBytes( this._scalarBuffer, 0, sizeof( double ) + 1 ); + } + + private void WriteBytes( string value, bool allowStr8 ) + { + var encodedLength = Encoding.UTF8.GetByteCount( value ); + this.WriteStringHeader( encodedLength, allowStr8 ); + if ( encodedLength == 0 ) + { + return; + } + + this.WriteStringBody( value ); + } + +#if !FEATURE_POINTER_CONVERSION + + private void WriteStringBody( string value ) + { + var chars = BufferManager.NewCharBuffer( value.Length ); + int offset = 0; + + while ( offset < value.Length ) + { + int copying = Math.Min( value.Length - offset, chars.Length ); + value.CopyTo( offset, chars, 0, copying ); + this.WriteStringBody( chars, copying ); + offset += copying; + } + } + + private void WriteStringBody( char[] value, int remainingCharsLength ) + { + +#else + + private void WriteStringBody( string value ) + { + var remainingCharsLength = value.Length; + +#endif // !FEATURE_POINTER_CONVERSION + + var buffer = BufferManager.NewByteBuffer( value.Length * 4 ); + var encoder = Encoding.UTF8.GetEncoder(); + var valueOffset = 0; + + bool isCompleted = false; + do + { + int charsUsed, bytesUsed; + isCompleted = EncodeString( encoder, value, valueOffset, remainingCharsLength, buffer, out charsUsed, out bytesUsed ); + + valueOffset += charsUsed; + remainingCharsLength -= charsUsed; + this._destination.Write( buffer, 0, bytesUsed ); + } while ( remainingCharsLength > 0 ); + +#if DEBUG + Contract.Assert( isCompleted, "Encoding is not completed!" ); +#endif // DEBUG + } + + +#if FEATURE_TAP + + private async Task WriteBytesAsync( byte header, byte value, CancellationToken cancellationToken ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value & 0xFF ) ); + await this.WriteBytesAsync( this._scalarBuffer, 0, sizeof( byte ) + 1, cancellationToken ).ConfigureAwait( false ); + } + + private async Task WriteBytesAsync( byte header, ushort value, CancellationToken cancellationToken ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value >> 8 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( value & 0xFF ) ); + await this.WriteBytesAsync( this._scalarBuffer, 0, sizeof( ushort ) + 1, cancellationToken ).ConfigureAwait( false ); + } + + private async Task WriteBytesAsync( byte header, uint value, CancellationToken cancellationToken ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value >> 24 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( value >> 16 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( value >> 8 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( value & 0xFF ) ); + await this.WriteBytesAsync( this._scalarBuffer, 0, sizeof( uint ) + 1, cancellationToken ).ConfigureAwait( false ); + } + + private async Task WriteBytesAsync( byte header, ulong value, CancellationToken cancellationToken ) + { + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( value >> 56 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( value >> 48 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( value >> 40 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( value >> 32 & 0xFF ) ); + this._scalarBuffer[ 5 ] = unchecked( ( byte )( value >> 24 & 0xFF ) ); + this._scalarBuffer[ 6 ] = unchecked( ( byte )( value >> 16 & 0xFF ) ); + this._scalarBuffer[ 7 ] = unchecked( ( byte )( value >> 8 & 0xFF ) ); + this._scalarBuffer[ 8 ] = unchecked( ( byte )( value & 0xFF ) ); + await this.WriteBytesAsync( this._scalarBuffer, 0, sizeof( ulong ) + 1, cancellationToken ).ConfigureAwait( false ); + } + + private async Task WriteBytesAsync( byte header, float value, CancellationToken cancellationToken ) + { + var bits = Binary.ToBits( value ); + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( bits >> 24 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( bits >> 16 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( bits >> 8 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( bits & 0xFF ) ); + await this.WriteBytesAsync( this._scalarBuffer, 0, sizeof( float ) + 1, cancellationToken ).ConfigureAwait( false ); + } + + private async Task WriteBytesAsync( byte header, double value, CancellationToken cancellationToken ) + { + var bits = Binary.ToBits( value ); + this._scalarBuffer[ 0 ] = header; + this._scalarBuffer[ 1 ] = unchecked( ( byte )( bits >> 56 & 0xFF ) ); + this._scalarBuffer[ 2 ] = unchecked( ( byte )( bits >> 48 & 0xFF ) ); + this._scalarBuffer[ 3 ] = unchecked( ( byte )( bits >> 40 & 0xFF ) ); + this._scalarBuffer[ 4 ] = unchecked( ( byte )( bits >> 32 & 0xFF ) ); + this._scalarBuffer[ 5 ] = unchecked( ( byte )( bits >> 24 & 0xFF ) ); + this._scalarBuffer[ 6 ] = unchecked( ( byte )( bits >> 16 & 0xFF ) ); + this._scalarBuffer[ 7 ] = unchecked( ( byte )( bits >> 8 & 0xFF ) ); + this._scalarBuffer[ 8 ] = unchecked( ( byte )( bits & 0xFF ) ); + await this.WriteBytesAsync( this._scalarBuffer, 0, sizeof( double ) + 1, cancellationToken ).ConfigureAwait( false ); + } + + private async Task WriteBytesAsync( string value, bool allowStr8, CancellationToken cancellationToken ) + { + var encodedLength = Encoding.UTF8.GetByteCount( value ); + await this.WriteStringHeaderAsync( encodedLength, allowStr8, cancellationToken ).ConfigureAwait( false ); + if ( encodedLength == 0 ) + { + return; + } + + await this.WriteStringBodyAsync( value, cancellationToken ).ConfigureAwait( false ); + } + +#if !FEATURE_POINTER_CONVERSION + + private async Task WriteStringBodyAsync( string value, CancellationToken cancellationToken ) + { + var chars = BufferManager.NewCharBuffer( value.Length ); + int offset = 0; + + while ( offset < value.Length ) + { + int copying = Math.Min( value.Length - offset, chars.Length ); + value.CopyTo( offset, chars, 0, copying ); + await this.WriteStringBodyAsync( chars, copying, cancellationToken ).ConfigureAwait( false ); + offset += copying; + } + } + + private async Task WriteStringBodyAsync( char[] value, int remainingCharsLength, CancellationToken cancellationToken ) + { + +#else + + private async Task WriteStringBodyAsync( string value, CancellationToken cancellationToken ) + { + var remainingCharsLength = value.Length; + +#endif // !FEATURE_POINTER_CONVERSION + + var buffer = BufferManager.NewByteBuffer( value.Length * 4 ); + var encoder = Encoding.UTF8.GetEncoder(); + var valueOffset = 0; + + bool isCompleted = false; + do + { + int charsUsed, bytesUsed; + isCompleted = EncodeString( encoder, value, valueOffset, remainingCharsLength, buffer, out charsUsed, out bytesUsed ); + + valueOffset += charsUsed; + remainingCharsLength -= charsUsed; + await this._destination.WriteAsync( buffer, 0, bytesUsed, cancellationToken ).ConfigureAwait( false ); + } while ( remainingCharsLength > 0 ); + +#if DEBUG + Contract.Assert( isCompleted, "Encoding is not completed!" ); +#endif // DEBUG + } + +#endif // FEATURE_TAP + +#if FEATURE_POINTER_CONVERSION + + private static unsafe bool EncodeString( Encoder encoder, string value, int startOffset, int count, byte[] buffer, out int charsUsed, out int bytesUsed ) + { + fixed ( char* pValue = value ) + { + var pChars = pValue + startOffset; + + fixed ( byte* pBuffer = buffer ) + { + return encoder.EncodeString( pChars, count, pBuffer, buffer.Length, out charsUsed, out bytesUsed ); + } + } + } + +#else + + private static bool EncodeString( Encoder encoder, char[] value, int startOffset, int count, byte[] buffer, out int charsUsed, out int bytesUsed ) + { + return encoder.EncodeString( value, startOffset, count, buffer, 0, buffer.Length, out charsUsed, out bytesUsed ); + } + +#endif // FEATURE_POINTER_CONVERSION + } +} diff --git a/src/MsgPack/MessagePackStreamPacker.Pack.tt b/src/MsgPack/MessagePackStreamPacker.Pack.tt new file mode 100644 index 000000000..ac7298188 --- /dev/null +++ b/src/MsgPack/MessagePackStreamPacker.Pack.tt @@ -0,0 +1,221 @@ +<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ Assembly Name="System.Core.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Runtime.InteropServices" #> +<#@ import namespace="System.Text" #> +<#@ include file="MessagePackPackerCommon.ttinclude" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + // This file was generated from MessagePackStreamPacker.Pack.tt and MessagePackPackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackStreamPacker.Pack.tt and MessagePackPackerCommon.ttinclude instead. + + partial class MessagePackStreamPacker + { +<# + this.WriteOverrides(); +#> +#if FEATURE_TAP + + private async Task WriteStringHeaderAsync( int bytesLength, bool allowStr8, CancellationToken cancellationToken ) + { + if( bytesLength < 0x20 ) + { + await this.WriteByteAsync( ( byte )( bytesLength | MessagePackCode.MinimumFixedRaw ), cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( bytesLength < 0x100 && allowStr8 ) + { + await this.WriteBytesAsync( MessagePackCode.Str8, ( byte )bytesLength, cancellationToken ).ConfigureAwait( false ); + return; + } + + if ( bytesLength < 0x10000 ) + { + await this.WriteBytesAsync( MessagePackCode.Str16, ( ushort )bytesLength, cancellationToken ).ConfigureAwait( false ); + return; + } + + await this.WriteBytesAsync( MessagePackCode.Str32, unchecked(( uint )bytesLength), cancellationToken ).ConfigureAwait( false ); + } + +#endif // FEATURE_TAP + +<# + + foreach ( var isAsync in new [] { false, true } ) + { + if ( isAsync ) + { +#> + +#if FEATURE_TAP + +<# + } + + foreach ( var type in scalarTypes ) + { +#> + <#= AsyncMethod( isAsync, "void", "WriteBytes", "byte header, " + type + " value", false ) #> + { +<# + string bits; + this.WriteToBits( type, "value", out bits ); +#> + this._scalarBuffer[ 0 ] = header; +<# + this.WriteShift( type, bits, "this._scalarBuffer", i => ( i + 1 ).ToString( CultureInfo.InvariantCulture ) ); +#> + <#= isAsync ? "await " : String.Empty #>this.WriteBytes<#= isAsync ? "Async" : String.Empty #>( this._scalarBuffer, 0, sizeof( <#= type #> ) + 1<#= isAsync ? ", cancellationToken" : String.Empty #> )<#= isAsync ? ".ConfigureAwait( false )" : String.Empty #>; + } + +<# + } // foreach type +#> + <#= AsyncMethod( isAsync, "void", "WriteBytes", "string value, bool allowStr8", false ) #> + { + var encodedLength = Encoding.UTF8.GetByteCount( value ); + <#= isAsync ? "await " : String.Empty #>this.WriteStringHeader<#= isAsync ? "Async" : String.Empty #>( encodedLength, allowStr8<#= isAsync ? ", cancellationToken" : String.Empty #> )<#= isAsync ? ".ConfigureAwait( false )" : String.Empty #>; + if ( encodedLength == 0 ) + { + return; + } + + <#= isAsync ? "await " : String.Empty #>this.WriteStringBody<#= isAsync ? "Async" : String.Empty #>( value<#= isAsync ? ", cancellationToken" : String.Empty #> )<#= isAsync ? ".ConfigureAwait( false )" : String.Empty #>; + } + +#if !FEATURE_POINTER_CONVERSION + + <#= AsyncMethod( isAsync, "void", "WriteStringBody", "string value", false ) #> + { + var chars = BufferManager.NewCharBuffer( value.Length ); + int offset = 0; + + while ( offset < value.Length ) + { + int copying = Math.Min( value.Length - offset, chars.Length ); + value.CopyTo( offset, chars, 0, copying ); + <#= isAsync ? "await " : String.Empty #>this.WriteStringBody<#= isAsync ? "Async" : String.Empty #>( chars, copying<#= isAsync ? ", cancellationToken" : String.Empty #> )<#= isAsync ? ".ConfigureAwait( false )" : String.Empty #>; + offset += copying; + } + } + + <#= AsyncMethod( isAsync, "void", "WriteStringBody", "char[] value, int remainingCharsLength", false ) #> + { + +#else + + <#= AsyncMethod( isAsync, "void", "WriteStringBody", "string value", false ) #> + { + var remainingCharsLength = value.Length; + +#endif // !FEATURE_POINTER_CONVERSION + + var buffer = BufferManager.NewByteBuffer( value.Length * 4 ); + var encoder = Encoding.UTF8.GetEncoder(); + var valueOffset = 0; + + bool isCompleted = false; + do + { + int charsUsed, bytesUsed; + isCompleted = EncodeString( encoder, value, valueOffset, remainingCharsLength, buffer, out charsUsed, out bytesUsed ); + + valueOffset += charsUsed; + remainingCharsLength -= charsUsed; + <#= isAsync ? "await " : String.Empty #>this._destination.Write<#= isAsync ? "Async" : String.Empty #>( buffer, 0, bytesUsed<#= isAsync ? ", cancellationToken" : String.Empty #> )<#= isAsync ? ".ConfigureAwait( false )" : String.Empty #>; + } while ( remainingCharsLength > 0 ); + +#if DEBUG + Contract.Assert( isCompleted, "Encoding is not completed!" ); +#endif // DEBUG + } + +<# + + if ( isAsync ) + { +#> +#endif // FEATURE_TAP +<# + } + } // foreach isAsync +#> + +#if FEATURE_POINTER_CONVERSION + + private static unsafe bool EncodeString( Encoder encoder, string value, int startOffset, int count, byte[] buffer, out int charsUsed, out int bytesUsed ) + { + fixed ( char* pValue = value ) + { + var pChars = pValue + startOffset; + + fixed ( byte* pBuffer = buffer ) + { + return encoder.EncodeString( pChars, count, pBuffer, buffer.Length, out charsUsed, out bytesUsed ); + } + } + } + +#else + + private static bool EncodeString( Encoder encoder, char[] value, int startOffset, int count, byte[] buffer, out int charsUsed, out int bytesUsed ) + { + return encoder.EncodeString( value, startOffset, count, buffer, 0, buffer.Length, out charsUsed, out bytesUsed ); + } + +#endif // FEATURE_POINTER_CONVERSION + } +} +<#+ +private void WriteShift( string type, string variable, string buffer, Func offsetGenerator ) +{ + var bytesLength = lengthes[ type ]; + for ( var i = 0; i < bytesLength; i++ ) + { + this.WriteShiftCore( i, bytesLength, variable, buffer, offsetGenerator ); + } +} +#> diff --git a/src/MsgPack/MessagePackStreamPacker.cs b/src/MsgPack/MessagePackStreamPacker.cs new file mode 100644 index 000000000..18ee96fc3 --- /dev/null +++ b/src/MsgPack/MessagePackStreamPacker.cs @@ -0,0 +1,148 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + /// + /// Implementation for stream based MessagePack packer. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + sealed partial class MessagePackStreamPacker : Packer + { + private readonly Stream _destination; + private readonly byte[] _scalarBuffer; + private readonly bool _ownsStream; + +#if DEBUG +#if UNITY && DEBUG + public +#else + internal +#endif + Stream Destination { get { return this._destination; } } +#endif // DEBUG + + public MessagePackStreamPacker( Stream stream, PackerUnpackerStreamOptions streamOptions, PackerCompatibilityOptions compatibilityOptions ) + : base( compatibilityOptions ) + { + if ( stream == null ) + { + throw new ArgumentNullException( "stream" ); + } + + var options = streamOptions ?? PackerUnpackerStreamOptions.None; + this._destination = options.WrapStream( stream ); + this._ownsStream = options.OwnsStream; + this._scalarBuffer = new byte[ sizeof( ulong ) + 1 ]; + } + + protected override void Dispose( bool disposing ) + { + if ( disposing && this._ownsStream ) + { + this._destination.Dispose(); + } + + base.Dispose( disposing ); + } + + public override void Flush() + { + this._destination.Flush(); + } + + protected override void WriteByte( byte value ) + { + this._destination.WriteByte( value ); + } + + protected override void WriteBytes( byte[] value, bool isImmutable ) + { + this.WriteBytes( value ); + } + + protected override void WriteBytes( ICollection value ) + { + this.WriteBytes( value as byte[] ?? value.ToArray() ); + } + + private void WriteBytes( byte[] value ) + { + this.WriteBytes( value, 0, value.Length ); + } + + private void WriteBytes( byte[] value, int startIndex, int count ) + { + this._destination.Write( value, startIndex, count ); + } + +#if FEATURE_TAP + + public override Task FlushAsync( CancellationToken cancellationToken ) + { + return this._destination.FlushAsync( cancellationToken ); + } + + protected override Task WriteByteAsync( byte value, CancellationToken cancellationToken ) + { + this._scalarBuffer[ 0 ] = value; + return this._destination.WriteAsync( this._scalarBuffer, 0, sizeof( byte ), cancellationToken ); + } + + protected override Task WriteBytesAsync( byte[] value, bool isImmutable, CancellationToken cancellationToken ) + { + return this.WriteBytesAsync( value, cancellationToken ); + } + + protected override Task WriteBytesAsync( ICollection value, CancellationToken cancellationToken ) + { + return this.WriteBytesAsync( value as byte[] ?? value.ToArray(), cancellationToken ); + } + + private Task WriteBytesAsync( byte[] value, CancellationToken cancellationToken ) + { + return this.WriteBytesAsync( value, 0, value.Length, cancellationToken ); + } + + private Task WriteBytesAsync( byte[] value, int startIndex, int count, CancellationToken cancellationToken ) + { + return this._destination.WriteAsync( value, startIndex, count ); + } + +#endif // FEATURE_TAP + } +} diff --git a/src/MsgPack/MessagePackStreamUnpacker.Unpack.cs b/src/MsgPack/MessagePackStreamUnpacker.Unpack.cs new file mode 100644 index 000000000..a6d699b4c --- /dev/null +++ b/src/MsgPack/MessagePackStreamUnpacker.Unpack.cs @@ -0,0 +1,8774 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; +using System.IO; +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +#if !UNITY || MSGPACK_UNITY_FULL +using Int64Stack = System.Collections.Generic.Stack; +#endif // !UNITY || MSGPACK_UNITY_FULL + +namespace MsgPack +{ + // This file was generated from MessagePackStreamUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackStreamUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude instead. + + partial class MessagePackStreamUnpacker + { + public sealed override bool ReadByte( out Byte result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Byte ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Byte )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadByteSlow( header, buffer, ref offset, out result ) ) + { + result = default( Byte ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadByteSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Byte result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Byte ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Byte ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Byte )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Byte )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Byte )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Byte )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Byte )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Byte )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Byte )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Byte )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Byte )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Byte )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Byte ), header ); + // Never + result = default( Byte ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableByte( out Byte? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Byte? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Byte? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableByteSlow( header, buffer, ref offset, out result ) ) + { + result = default( Byte? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableByteSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Byte? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Byte? ); + offset++; + return true; + } + + Byte value; + if( !this.ReadByteSlow( header, buffer, ref offset, out value ) ) + { + result = default( Byte? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadByteAsync( CancellationToken cancellationToken ) + { + Byte result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Byte )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadByteSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadByteSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + Byte result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Byte ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Byte )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Byte )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Byte )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Byte )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Byte )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Byte )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Byte )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Byte )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Byte )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Byte )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Byte ), header ); + // Never + result = default( Byte ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableByteAsync( CancellationToken cancellationToken ) + { + Byte? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Byte? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableByteSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableByteSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( Byte? ), offset + 1 ); + } + + Byte value; + var asyncReadResult = await this.ReadByteSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( Byte? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadSByte( out SByte result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( SByte ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( SByte )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadSByteSlow( header, buffer, ref offset, out result ) ) + { + result = default( SByte ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadSByteSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out SByte result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( SByte ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( SByte ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( SByte )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( SByte )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( SByte )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( SByte )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( SByte )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( SByte )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( SByte )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( SByte )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( SByte )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( SByte )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( SByte ), header ); + // Never + result = default( SByte ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableSByte( out SByte? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( SByte? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( SByte? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableSByteSlow( header, buffer, ref offset, out result ) ) + { + result = default( SByte? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableSByteSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out SByte? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( SByte? ); + offset++; + return true; + } + + SByte value; + if( !this.ReadSByteSlow( header, buffer, ref offset, out value ) ) + { + result = default( SByte? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadSByteAsync( CancellationToken cancellationToken ) + { + SByte result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( SByte )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadSByteSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadSByteSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + SByte result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( SByte ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( SByte )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( SByte )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( SByte )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( SByte )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( SByte )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( SByte )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( SByte )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( SByte )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( SByte )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( SByte )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( SByte ), header ); + // Never + result = default( SByte ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableSByteAsync( CancellationToken cancellationToken ) + { + SByte? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( SByte? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableSByteSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableSByteSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( SByte? ), offset + 1 ); + } + + SByte value; + var asyncReadResult = await this.ReadSByteSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( SByte? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadInt16( out Int16 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int16 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int16 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadInt16Slow( header, buffer, ref offset, out result ) ) + { + result = default( Int16 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadInt16Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Int16 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int16 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int16 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int16 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int16 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Int16 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Int16 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Int16 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int16 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Int16 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Int16 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Int16 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Int16 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int16 ), header ); + // Never + result = default( Int16 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableInt16( out Int16? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int16? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int16? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableInt16Slow( header, buffer, ref offset, out result ) ) + { + result = default( Int16? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableInt16Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Int16? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Int16? ); + offset++; + return true; + } + + Int16 value; + if( !this.ReadInt16Slow( header, buffer, ref offset, out value ) ) + { + result = default( Int16? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadInt16Async( CancellationToken cancellationToken ) + { + Int16 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int16 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadInt16SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadInt16SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + Int16 result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int16 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int16 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int16 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Int16 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Int16 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Int16 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int16 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Int16 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Int16 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Int16 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Int16 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int16 ), header ); + // Never + result = default( Int16 ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableInt16Async( CancellationToken cancellationToken ) + { + Int16? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int16? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableInt16SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableInt16SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( Int16? ), offset + 1 ); + } + + Int16 value; + var asyncReadResult = await this.ReadInt16SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( Int16? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadUInt16( out UInt16 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( UInt16 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt16 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadUInt16Slow( header, buffer, ref offset, out result ) ) + { + result = default( UInt16 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadUInt16Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out UInt16 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt16 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( UInt16 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt16 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt16 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt16 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt16 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( UInt16 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt16 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt16 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt16 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( UInt16 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( UInt16 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt16 ), header ); + // Never + result = default( UInt16 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableUInt16( out UInt16? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( UInt16? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt16? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableUInt16Slow( header, buffer, ref offset, out result ) ) + { + result = default( UInt16? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableUInt16Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out UInt16? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( UInt16? ); + offset++; + return true; + } + + UInt16 value; + if( !this.ReadUInt16Slow( header, buffer, ref offset, out value ) ) + { + result = default( UInt16? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadUInt16Async( CancellationToken cancellationToken ) + { + UInt16 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt16 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadUInt16SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadUInt16SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + UInt16 result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt16 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt16 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt16 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt16 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt16 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( UInt16 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt16 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt16 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt16 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( UInt16 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( UInt16 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt16 ), header ); + // Never + result = default( UInt16 ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableUInt16Async( CancellationToken cancellationToken ) + { + UInt16? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt16? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableUInt16SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableUInt16SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( UInt16? ), offset + 1 ); + } + + UInt16 value; + var asyncReadResult = await this.ReadUInt16SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( UInt16? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadInt32( out Int32 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int32 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int32 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadInt32Slow( header, buffer, ref offset, out result ) ) + { + result = default( Int32 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadInt32Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Int32 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int32 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int32 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int32 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int32 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Int32 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Int32 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Int32 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int32 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Int32 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Int32 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Int32 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Int32 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int32 ), header ); + // Never + result = default( Int32 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableInt32( out Int32? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int32? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int32? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableInt32Slow( header, buffer, ref offset, out result ) ) + { + result = default( Int32? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableInt32Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Int32? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Int32? ); + offset++; + return true; + } + + Int32 value; + if( !this.ReadInt32Slow( header, buffer, ref offset, out value ) ) + { + result = default( Int32? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadInt32Async( CancellationToken cancellationToken ) + { + Int32 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int32 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadInt32SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadInt32SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + Int32 result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int32 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int32 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int32 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Int32 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Int32 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Int32 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int32 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Int32 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Int32 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Int32 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Int32 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int32 ), header ); + // Never + result = default( Int32 ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableInt32Async( CancellationToken cancellationToken ) + { + Int32? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int32? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableInt32SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableInt32SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( Int32? ), offset + 1 ); + } + + Int32 value; + var asyncReadResult = await this.ReadInt32SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( Int32? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadUInt32( out UInt32 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( UInt32 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt32 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadUInt32Slow( header, buffer, ref offset, out result ) ) + { + result = default( UInt32 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadUInt32Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out UInt32 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt32 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( UInt32 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt32 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt32 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt32 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt32 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( UInt32 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt32 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt32 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt32 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( UInt32 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( UInt32 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt32 ), header ); + // Never + result = default( UInt32 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableUInt32( out UInt32? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( UInt32? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt32? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableUInt32Slow( header, buffer, ref offset, out result ) ) + { + result = default( UInt32? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableUInt32Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out UInt32? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( UInt32? ); + offset++; + return true; + } + + UInt32 value; + if( !this.ReadUInt32Slow( header, buffer, ref offset, out value ) ) + { + result = default( UInt32? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadUInt32Async( CancellationToken cancellationToken ) + { + UInt32 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt32 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadUInt32SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadUInt32SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + UInt32 result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt32 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt32 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt32 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt32 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt32 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( UInt32 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt32 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt32 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt32 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( UInt32 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( UInt32 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt32 ), header ); + // Never + result = default( UInt32 ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableUInt32Async( CancellationToken cancellationToken ) + { + UInt32? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt32? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableUInt32SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableUInt32SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( UInt32? ), offset + 1 ); + } + + UInt32 value; + var asyncReadResult = await this.ReadUInt32SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( UInt32? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadInt64( out Int64 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int64 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadInt64Slow( header, buffer, ref offset, out result ) ) + { + result = default( Int64 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadInt64Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Int64 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int64 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int64 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int64 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int64 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Int64 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Int64 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Int64 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int64 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Int64 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Int64 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Int64 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Int64 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int64 ), header ); + // Never + result = default( Int64 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableInt64( out Int64? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int64? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int64? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableInt64Slow( header, buffer, ref offset, out result ) ) + { + result = default( Int64? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableInt64Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Int64? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Int64? ); + offset++; + return true; + } + + Int64 value; + if( !this.ReadInt64Slow( header, buffer, ref offset, out value ) ) + { + result = default( Int64? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadInt64Async( CancellationToken cancellationToken ) + { + Int64 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int64 )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadInt64SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadInt64SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + Int64 result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Int64 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Int64 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Int64 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Int64 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Int64 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Int64 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Int64 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Int64 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Int64 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Int64 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Int64 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Int64 ), header ); + // Never + result = default( Int64 ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableInt64Async( CancellationToken cancellationToken ) + { + Int64? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + result = ( Int64? )immediateValue; + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableInt64SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableInt64SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( Int64? ), offset + 1 ); + } + + Int64 value; + var asyncReadResult = await this.ReadInt64SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( Int64? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadUInt64( out UInt64 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( UInt64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt64 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadUInt64Slow( header, buffer, ref offset, out result ) ) + { + result = default( UInt64 ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadUInt64Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out UInt64 result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt64 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( UInt64 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt64 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt64 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt64 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt64 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( UInt64 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt64 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt64 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt64 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( UInt64 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( UInt64 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt64 ), header ); + // Never + result = default( UInt64 ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableUInt64( out UInt64? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( UInt64? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt64? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableUInt64Slow( header, buffer, ref offset, out result ) ) + { + result = default( UInt64? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableUInt64Slow( ReadValueResult header, byte[] buffer, ref Int64 offset, out UInt64? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( UInt64? ); + offset++; + return true; + } + + UInt64 value; + if( !this.ReadUInt64Slow( header, buffer, ref offset, out value ) ) + { + result = default( UInt64? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadUInt64Async( CancellationToken cancellationToken ) + { + UInt64 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt64 )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadUInt64SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadUInt64SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + UInt64 result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( UInt64 ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( UInt64 )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( UInt64 )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( UInt64 )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( UInt64 )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( UInt64 )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( UInt64 )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( UInt64 )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( UInt64 )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( UInt64 )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( UInt64 )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( UInt64 ), header ); + // Never + result = default( UInt64 ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableUInt64Async( CancellationToken cancellationToken ) + { + UInt64? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( UInt64? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableUInt64SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableUInt64SlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( UInt64? ), offset + 1 ); + } + + UInt64 value; + var asyncReadResult = await this.ReadUInt64SlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( UInt64? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadSingle( out Single result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Single ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Single )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadSingleSlow( header, buffer, ref offset, out result ) ) + { + result = default( Single ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadSingleSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Single result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Single ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Single ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Single )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Single )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Single )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Single )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Single )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Single )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Single )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Single )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Single )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Single )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Single ), header ); + // Never + result = default( Single ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableSingle( out Single? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Single? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Single? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableSingleSlow( header, buffer, ref offset, out result ) ) + { + result = default( Single? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableSingleSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Single? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Single? ); + offset++; + return true; + } + + Single value; + if( !this.ReadSingleSlow( header, buffer, ref offset, out value ) ) + { + result = default( Single? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadSingleAsync( CancellationToken cancellationToken ) + { + Single result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Single )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadSingleSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadSingleSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + Single result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Single ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Single )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Single )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Single )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Single )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Single )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Single )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Single )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Single )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Single )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Single )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Single ), header ); + // Never + result = default( Single ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableSingleAsync( CancellationToken cancellationToken ) + { + Single? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Single? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableSingleSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableSingleSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( Single? ), offset + 1 ); + } + + Single value; + var asyncReadResult = await this.ReadSingleSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( Single? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadDouble( out Double result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Double ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Double )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadDoubleSlow( header, buffer, ref offset, out result ) ) + { + result = default( Double ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadDoubleSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Double result ) + { + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Double ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Double ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Double )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Double )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Double )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Double )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Double )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Double )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Double )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Double )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Double )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Double )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Double ), header ); + // Never + result = default( Double ); + break; + } + } // switch + } // checked + + offset += length; + return true; + } + + public sealed override bool ReadNullableDouble( out Double? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Double? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Double? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + if ( !this.ReadNullableDoubleSlow( header, buffer, ref offset, out result ) ) + { + result = default( Double? ); + return false; + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadNullableDoubleSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out Double? result ) + { + if ( header == ReadValueResult.Nil ) + { + result = default( Double? ); + offset++; + return true; + } + + Double value; + if( !this.ReadDoubleSlow( header, buffer, ref offset, out value ) ) + { + result = default( Double? ); + return false; + } + + result = value; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadDoubleAsync( CancellationToken cancellationToken ) + { + Double result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Double )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadDoubleSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadDoubleSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + Double result; + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( Double ), header ); + } + + offset++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + // scope for local + { + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( Double )buffer[ 0 ]; + break; + } + case 0x200: // UInt16 + { + result = ( Double )BigEndianBinary.ToUInt16( buffer, 0 ); + break; + } + case 0x400: // UInt32 + { + result = ( Double )BigEndianBinary.ToUInt32( buffer, 0 ); + break; + } + case 0x800: // UInt64 + { + result = ( Double )BigEndianBinary.ToUInt64( buffer, 0 ); + break; + } + case 0x1100: // SByte + { + result = ( Double )( unchecked( ( SByte )buffer[ 0 ] ) ); + break; + } + case 0x1200: // Int16 + { + result = ( Double )BigEndianBinary.ToInt16( buffer, 0 ); + break; + } + case 0x1400: // Int32 + { + result = ( Double )BigEndianBinary.ToInt32( buffer, 0 ); + break; + } + case 0x1800: // Int64 + { + result = ( Double )BigEndianBinary.ToInt64( buffer, 0 ); + break; + } + case 0x2400: // Single + { + result = ( Double )BigEndianBinary.ToSingle( buffer, 0 ); + break; + } + case 0x2800: // Double + { + result = ( Double )BigEndianBinary.ToDouble( buffer, 0 ); + break; + } + default: + { + this.ThrowTypeException( typeof( Double ), header ); + // Never + result = default( Double ); + break; + } + } // switch + } // checked + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + + public sealed override async Task> ReadNullableDoubleAsync( CancellationToken cancellationToken ) + { + Double? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); + // Check sign + result = checked( ( Double? )immediateValue ); + offset++; + // goto tail + } + else + { + // Slow path + var slowAsyncResult = await this.ReadNullableDoubleSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + // goto tail + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadNullableDoubleSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( Double? ), offset + 1 ); + } + + Double value; + var asyncReadResult = await this.ReadDoubleSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + return AsyncReadResult.Success( ( Double? )value, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadBoolean( out Boolean result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Boolean ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + switch ( header ) + { + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( Boolean ), header ); + // never + result = false; + break; + } + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } // if ( isAsync && isPseudoAsync ) + + public sealed override bool ReadNullableBoolean( out Boolean? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Boolean? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + switch ( header ) + { + case ReadValueResult.Nil: + { + result = default( bool? ); + break; + } + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( Boolean? ), header ); + // never + result = false; + break; + } + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } // if ( isAsync && isPseudoAsync ) + +#if FEATURE_TAP + + public sealed override async Task> ReadBooleanAsync( CancellationToken cancellationToken ) + { + Boolean result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + switch ( header ) + { + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( Boolean ), header ); + // never + result = false; + break; + } + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } // if ( isAsync && isPseudoAsync ) + + public sealed override async Task> ReadNullableBooleanAsync( CancellationToken cancellationToken ) + { + Boolean? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + switch ( header ) + { + case ReadValueResult.Nil: + { + result = default( bool? ); + break; + } + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( Boolean? ), header ); + // never + result = false; + break; + } + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } // if ( isAsync && isPseudoAsync ) + +#endif // FEATURE_TAP + + public sealed override bool ReadBinary( out Byte[] result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Byte[] ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Byte[] can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + // Check type + if ( ( header & ReadValueResult.RawTypeMask ) != ReadValueResult.RawTypeMask ) + { + this.ThrowTypeException( "raw", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Raw8 + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Byte[] ); + return false; + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Raw16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Byte[] ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Raw32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Byte[] ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out result ) ) + { + result = default( Byte[] ); + return false; + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadBinaryAsync( CancellationToken cancellationToken ) + { + Byte[] result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Byte[] can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + // Check type + if ( ( header & ReadValueResult.RawTypeMask ) != ReadValueResult.RawTypeMask ) + { + this.ThrowTypeException( "raw", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Raw8 + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Raw16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Raw32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + var asyncReadResult = await this.ReadBinaryCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + result = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail(); + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadString( out String result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( String ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // String can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + // Check type + if ( ( header & ReadValueResult.RawTypeMask ) != ReadValueResult.RawTypeMask ) + { + this.ThrowTypeException( "raw", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Raw8 + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( String ); + return false; + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Raw16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( String ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Raw32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( String ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + if( !this.ReadStringCore( unchecked( ( int )length ), ref offset, out result ) ) + { + result = default( String ); + return false; + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadStringAsync( CancellationToken cancellationToken ) + { + String result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // String can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + // Check type + if ( ( header & ReadValueResult.RawTypeMask ) != ReadValueResult.RawTypeMask ) + { + this.ThrowTypeException( "raw", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Raw8 + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Raw16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Raw32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + var asyncReadResult = await this.ReadStringCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + result = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail(); + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + +#endif // FEATURE_TAP + + private bool ReadObject( bool isDeep, out MessagePackObject result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( !this.ReadObjectCore( isDeep, buffer, ref offset, out result ) ) + { + result = default( MessagePackObject ); + return false; + } + this._offset = offset; + return true; + } + + private bool ReadObjectCore( bool isDeep, byte[] buffer, ref Int64 offset, out MessagePackObject result ) + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackObject ); + return false; + } + + var byteHeader = buffer[ 0 ]; + offset++; + var collectionType = ReadValueResults.CollectionType[ byteHeader ]; + + if ( ReadValueResults.HasConstantObject[ byteHeader ] ) + { + result = ReadValueResults.ContantObject[ byteHeader ]; + } + else + { + var header = ReadValueResults.EncodedTypes[ byteHeader ]; + + if ( ( header & ReadValueResult.RawTypeMask ) == ReadValueResult.RawTypeMask && ( header & ReadValueResult.LengthOfLengthMask ) == 0 ) + { + // fixed raw + int length = ( int )( header & ReadValueResult.ValueOrLengthMask ); + + byte[] binary; + if ( !this.ReadBinaryCore( length, ref offset, out binary ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = binary; + } + else + { + if ( !this.ReadObjectSlow( header, buffer, ref offset, out result ) ) + { + result = default( MessagePackObject ); + return false; + } + } + } + + if ( isDeep && collectionType != CollectionType.None ) + { + if ( !this.ReadItems( result.AsInt32(), collectionType == CollectionType.Map, buffer, ref offset, out result ) ) + { + result = default( MessagePackObject ); + return false; + } + } + + this._data = result; + this._collectionType = collectionType; + return true; + } + + private bool ReadObjectSlow( ReadValueResult header, byte[] buffer, ref Int64 offset, out MessagePackObject result ) + { + switch ( header & ReadValueResult.TypeCodeMask ) + { + case ReadValueResult.Array16Type: + case ReadValueResult.Map16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt16( buffer, 0 ); + offset += 2; + break; + } + case ReadValueResult.Array32Type: + case ReadValueResult.Map32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt32( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.Str8Type: + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = buffer[ 0 ]; + this.CheckLength( length, header ); + offset += 1; + MessagePackString stringValue; + if( !this.ReadRawStringCore( unchecked( ( int )length ), ref offset, out stringValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Str16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt16( buffer, 0 ); + this.CheckLength( length, header ); + offset += 2; + MessagePackString stringValue; + if( !this.ReadRawStringCore( unchecked( ( int )length ), ref offset, out stringValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Str32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt32( buffer, 0 ); + this.CheckLength( length, header ); + offset += 4; + MessagePackString stringValue; + if( !this.ReadRawStringCore( unchecked( ( int )length ), ref offset, out stringValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Bin8Type: + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackObject ); + return false; + } + + var length = buffer[ 0 ]; + this.CheckLength( length, header ); + offset += 1; + byte[] binaryValue; + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out binaryValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.Bin16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt16( buffer, 0 ); + this.CheckLength( length, header ); + offset += 2; + byte[] binaryValue; + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out binaryValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.Bin32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt32( buffer, 0 ); + this.CheckLength( length, header ); + offset += 4; + byte[] binaryValue; + if( !this.ReadBinaryCore( unchecked( ( int )length ), ref offset, out binaryValue ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.FixExtType: + { + var length = ( header & ReadValueResult.ValueOrLengthMask ); + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), buffer, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Ext8Type: + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackObject ); + return false; + } + var length = buffer[ 0 ]; + offset += 1; + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), buffer, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Ext16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + var length = BigEndianBinary.ToUInt16( buffer, 0 ); + offset += 2; + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), buffer, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Ext32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + var length = BigEndianBinary.ToUInt32( buffer, 0 ); + offset += 4; + MessagePackExtendedTypeObject ext; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), buffer, ref offset, out ext ) ) + { + result = default( MessagePackObject ); + return false; + } + + result = ext; + break; + } + case ReadValueResult.Int8Type: + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackObject ); + return false; + } + result = unchecked( ( sbyte )buffer[ 0 ] ); + offset += 1; + break; + } + case ReadValueResult.Int16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToInt16( buffer, 0 ); + offset += 2; + break; + } + case ReadValueResult.Int32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToInt32( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.Int64Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 8; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToInt64( buffer, 0 ); + offset += 8; + break; + } + case ReadValueResult.UInt8Type: + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackObject ); + return false; + } + result = buffer[ 0 ]; + offset += 1; + break; + } + case ReadValueResult.UInt16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt16( buffer, 0 ); + offset += 2; + break; + } + case ReadValueResult.UInt32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt32( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.UInt64Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 8; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt64( buffer, 0 ); + offset += 8; + break; + } + case ReadValueResult.Real32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToSingle( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.Real64Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 8; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToDouble( buffer, 0 ); + offset += 8; + break; + } + default: + { +#if DEBUG + Contract.Assert( header == ReadValueResult.InvalidCode, header.ToString( "X" ) + " == ReadValueResult.InvalidCode" ); +#endif // DEBUG + this.ThrowUnassignedMessageTypeException( 0xC1 ); + // never + result = default( MessagePackObject ); + break; + } + } + + return true; + } + + private bool ReadItems( int count, bool isMap, byte[] buffer, ref Int64 offset, out MessagePackObject result ) + { + MessagePackObject container; + if ( !isMap ) + { + var array = new MessagePackObject[ count ]; + for ( var i = 0; i < count; i++ ) + { + MessagePackObject item; + if ( !this.ReadObjectCore( true, buffer, ref offset, out item ) ) + { + result = default( MessagePackObject ); + return false; + } + array[ i ] = item; + } + + container = new MessagePackObject( array, true ); + } + else + { + var map = new MessagePackObjectDictionary( count ); + + for ( var i = 0; i < count; i++ ) + { + MessagePackObject key; + if ( !this.ReadObjectCore( true, buffer, ref offset, out key ) ) + { + result = default( MessagePackObject ); + return false; + } + MessagePackObject value; + if ( !this.ReadObjectCore( true, buffer, ref offset, out value ) ) + { + result = default( MessagePackObject ); + return false; + } + map.Add( key, value ); + } + + container = new MessagePackObject( map, true ); + } + result = container; + return true; + } + +#if FEATURE_TAP + + private async Task> ReadObjectAsync( bool isDeep, CancellationToken cancellationToken ) + { + MessagePackObject result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + var asyncReadResult = await this.ReadObjectCoreAsync( isDeep, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + result = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + this._offset = offset; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadObjectCoreAsync( bool isDeep, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + + var byteHeader = buffer[ 0 ]; + offset++; + var collectionType = ReadValueResults.CollectionType[ byteHeader ]; + MessagePackObject result; + + if ( ReadValueResults.HasConstantObject[ byteHeader ] ) + { + result = ReadValueResults.ContantObject[ byteHeader ]; + } + else + { + var header = ReadValueResults.EncodedTypes[ byteHeader ]; + + if ( ( header & ReadValueResult.RawTypeMask ) == ReadValueResult.RawTypeMask && ( header & ReadValueResult.LengthOfLengthMask ) == 0 ) + { + // fixed raw + int length = ( int )( header & ReadValueResult.ValueOrLengthMask ); + + byte[] binary; + var asyncReadResult = await this.ReadBinaryCoreAsync( length, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + binary = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = binary; + } + else + { + var asyncReadReasult = await this.ReadObjectSlowAsync( header, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadReasult.Success ) + { + result = asyncReadReasult.Value.Result; + offset = asyncReadReasult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + } + } + + if ( isDeep && collectionType != CollectionType.None ) + { + var asyncReadReasult = await this.ReadItemsAsync( result.AsInt32(), collectionType == CollectionType.Map, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadReasult.Success ) + { + result = asyncReadReasult.Value.Result; + offset = asyncReadReasult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + } + + this._data = result; + this._collectionType = collectionType; + return AsyncReadResult.Success( result, offset ); + } + + private async Task>> ReadObjectSlowAsync( ReadValueResult header, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + MessagePackObject result; + switch ( header & ReadValueResult.TypeCodeMask ) + { + case ReadValueResult.Array16Type: + case ReadValueResult.Map16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt16( buffer, 0 ); + offset += 2; + break; + } + case ReadValueResult.Array32Type: + case ReadValueResult.Map32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt32( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.Str8Type: + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + + var length = buffer[ 0 ]; + this.CheckLength( length, header ); + offset += 1; + MessagePackString stringValue; + var asyncReadResult = await this.ReadRawStringCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + stringValue = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Str16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt16( buffer, 0 ); + this.CheckLength( length, header ); + offset += 2; + MessagePackString stringValue; + var asyncReadResult = await this.ReadRawStringCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + stringValue = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Str32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt32( buffer, 0 ); + this.CheckLength( length, header ); + offset += 4; + MessagePackString stringValue; + var asyncReadResult = await this.ReadRawStringCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + stringValue = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = new MessagePackObject( stringValue ); + break; + } + case ReadValueResult.Bin8Type: + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + + var length = buffer[ 0 ]; + this.CheckLength( length, header ); + offset += 1; + byte[] binaryValue; + var asyncReadResult = await this.ReadBinaryCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + binaryValue = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.Bin16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt16( buffer, 0 ); + this.CheckLength( length, header ); + offset += 2; + byte[] binaryValue; + var asyncReadResult = await this.ReadBinaryCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + binaryValue = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.Bin32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + var length = BigEndianBinary.ToUInt32( buffer, 0 ); + this.CheckLength( length, header ); + offset += 4; + byte[] binaryValue; + var asyncReadResult = await this.ReadBinaryCoreAsync( unchecked( ( int )length ), offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + offset = asyncReadResult.Value.Offset; + binaryValue = asyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = new MessagePackObject( binaryValue, /* isBinary */true ); + break; + } + case ReadValueResult.FixExtType: + { + var length = ( header & ReadValueResult.ValueOrLengthMask ); + MessagePackExtendedTypeObject ext; + var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + ext = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = ext; + break; + } + case ReadValueResult.Ext8Type: + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + var length = buffer[ 0 ]; + offset += 1; + MessagePackExtendedTypeObject ext; + var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + ext = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = ext; + break; + } + case ReadValueResult.Ext16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + var length = BigEndianBinary.ToUInt16( buffer, 0 ); + offset += 2; + MessagePackExtendedTypeObject ext; + var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + ext = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = ext; + break; + } + case ReadValueResult.Ext32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + var length = BigEndianBinary.ToUInt32( buffer, 0 ); + offset += 4; + MessagePackExtendedTypeObject ext; + var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + ext = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + + result = ext; + break; + } + case ReadValueResult.Int8Type: + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + result = unchecked( ( sbyte )buffer[ 0 ] ); + offset += 1; + break; + } + case ReadValueResult.Int16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToInt16( buffer, 0 ); + offset += 2; + break; + } + case ReadValueResult.Int32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToInt32( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.Int64Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 8; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToInt64( buffer, 0 ); + offset += 8; + break; + } + case ReadValueResult.UInt8Type: + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + result = buffer[ 0 ]; + offset += 1; + break; + } + case ReadValueResult.UInt16Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt16( buffer, 0 ); + offset += 2; + break; + } + case ReadValueResult.UInt32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt32( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.UInt64Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 8; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToUInt64( buffer, 0 ); + offset += 8; + break; + } + case ReadValueResult.Real32Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToSingle( buffer, 0 ); + offset += 4; + break; + } + case ReadValueResult.Real64Type: + { + // scope for local + { + var bufferOffset = 0; + var reading = 8; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + result = BigEndianBinary.ToDouble( buffer, 0 ); + offset += 8; + break; + } + default: + { +#if DEBUG + Contract.Assert( header == ReadValueResult.InvalidCode, header.ToString( "X" ) + " == ReadValueResult.InvalidCode" ); +#endif // DEBUG + this.ThrowUnassignedMessageTypeException( 0xC1 ); + // never + result = default( MessagePackObject ); + break; + } + } + + return AsyncReadResult.Success( result, offset ); + } + + private async Task>> ReadItemsAsync( int count, bool isMap, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + MessagePackObject container; + if ( !isMap ) + { + var array = new MessagePackObject[ count ]; + for ( var i = 0; i < count; i++ ) + { + MessagePackObject item; + var itemAsyncReadResult = await this.ReadObjectCoreAsync( true, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( itemAsyncReadResult.Success ) + { + offset = itemAsyncReadResult.Value.Offset; + item = itemAsyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + array[ i ] = item; + } + + container = new MessagePackObject( array, true ); + } + else + { + var map = new MessagePackObjectDictionary( count ); + + for ( var i = 0; i < count; i++ ) + { + MessagePackObject key; + var keyAsyncReadResult = await this.ReadObjectCoreAsync( true, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( keyAsyncReadResult.Success ) + { + offset = keyAsyncReadResult.Value.Offset; + key = keyAsyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + MessagePackObject value; + var valueAsyncReadResult = await this.ReadObjectCoreAsync( true, buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( valueAsyncReadResult.Success ) + { + offset = valueAsyncReadResult.Value.Offset; + value = valueAsyncReadResult.Value.Result; + } + else + { + return AsyncReadResult.Fail>(); + } + map.Add( key, value ); + } + + container = new MessagePackObject( map, true ); + } + return AsyncReadResult.Success( container, offset ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadArrayLength( out Int64 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.ArrayTypeMask ) != ReadValueResult.ArrayTypeMask ) + { + this.ThrowTypeException( "array", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Array8 + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Array16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int64 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Array32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int64 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + result = length; + this._data = length; + this._offset = offset; + this._collectionType = CollectionType.Array; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadArrayLengthAsync( CancellationToken cancellationToken ) + { + Int64 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.ArrayTypeMask ) != ReadValueResult.ArrayTypeMask ) + { + this.ThrowTypeException( "array", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Array8 + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Array16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Array32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + result = length; + this._data = length; + this._offset = offset; + this._collectionType = CollectionType.Array; + return AsyncReadResult.Success( result ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadMapLength( out Int64 result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int64 ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.MapTypeMask ) != ReadValueResult.MapTypeMask ) + { + this.ThrowTypeException( "map", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Map8 + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( Int64 ); + return false; + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Map16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int64 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Map32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( Int64 ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + result = length; + this._data = length; + this._offset = offset; + this._collectionType = CollectionType.Map; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadMapLengthAsync( CancellationToken cancellationToken ) + { + Int64 result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.MapTypeMask ) != ReadValueResult.MapTypeMask ) + { + this.ThrowTypeException( "map", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Map8 + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Map16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Map32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + result = length; + this._data = length; + this._offset = offset; + this._collectionType = CollectionType.Map; + return AsyncReadResult.Success( result ); + } + +#endif // FEATURE_TAP + + public sealed override bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.ExtTypeMask ) != ReadValueResult.ExtTypeMask ) + { + this.ThrowTypeException( "ext", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Ext8 + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Ext16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackExtendedTypeObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Ext32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackExtendedTypeObject ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), buffer, ref offset, out result ) ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + + private bool ReadMessagePackExtendedTypeObjectCore( int length, byte[] buffer, ref Int64 offset, out MessagePackExtendedTypeObject result ) + { + // Read type code + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + var typeCode = buffer[ 0 ]; + offset++; + + // Read body + byte[] body; + if ( !this.ReadBinaryCore( length, ref offset, out body ) ) + { + result = default( MessagePackExtendedTypeObject ); + return false; + } + + result = MessagePackExtendedTypeObject.Unpack( typeCode, body ); + return true; + } + + public sealed override bool ReadNullableMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject? result ) + { + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + if ( header == ReadValueResult.Nil ) + { + result = default( MessagePackExtendedTypeObject? ); + return true; + } + offset++; + + // Check type + if ( ( header & ReadValueResult.ExtTypeMask ) != ReadValueResult.ExtTypeMask ) + { + this.ThrowTypeException( "ext", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Ext8 + { + if ( this._source.Read( buffer, 0, 1 ) < 1 ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Ext16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackExtendedTypeObject? ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Ext32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = this._source.Read( buffer, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( MessagePackExtendedTypeObject? ); + return false; + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + MessagePackExtendedTypeObject value; + if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), buffer, ref offset, out value ) ) + { + result = default( MessagePackExtendedTypeObject? ); + return false; + } + + result = value; + this._offset = offset; + this._collectionType = CollectionType.None; + return true; + } + +#if FEATURE_TAP + + public sealed override async Task> ReadMessagePackExtendedTypeObjectAsync( CancellationToken cancellationToken ) + { + MessagePackExtendedTypeObject result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + offset++; + + // Check type + if ( ( header & ReadValueResult.ExtTypeMask ) != ReadValueResult.ExtTypeMask ) + { + this.ThrowTypeException( "ext", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Ext8 + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Ext16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Ext32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + result = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + + private async Task>> ReadMessagePackExtendedTypeObjectCoreAsync( int length, byte[] buffer, Int64 offset, CancellationToken cancellationToken ) + { + // Read type code + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail>(); + } + + var typeCode = buffer[ 0 ]; + offset++; + + // Read body + byte[] body; + var asyncReadResult = await this.ReadBinaryCoreAsync( length, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + body = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail>(); + } + return AsyncReadResult.Success( MessagePackExtendedTypeObject.Unpack( typeCode, body ), offset ); + } + + public sealed override async Task> ReadNullableMessagePackExtendedTypeObjectAsync( CancellationToken cancellationToken ) + { + MessagePackExtendedTypeObject? result; + var buffer = this._scalarBuffer; + var offset = this._offset; + this._lastOffset = this._offset; + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + var header = ReadValueResults.EncodedTypes[ buffer[ 0 ] ]; + if ( header == ReadValueResult.Nil ) + { + return AsyncReadResult.Success( default( MessagePackExtendedTypeObject? ) ); + } + offset++; + + // Check type + if ( ( header & ReadValueResult.ExtTypeMask ) != ReadValueResult.ExtTypeMask ) + { + this.ThrowTypeException( "ext", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // Ext8 + { + if ( await this._source.ReadAsync( buffer, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) + { + return AsyncReadResult.Fail(); + } + + length = BigEndianBinary.ToByte( buffer, 0 ); + + break; + } + case 2: // Ext16 + { + // scope for local + { + var bufferOffset = 0; + var reading = 2; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt16( buffer, 0 ); + + break; + } + default: // Ext32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG + // scope for local + { + var bufferOffset = 0; + var reading = 4; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { + var readLength = await this._source.ReadAsync( buffer, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail(); + } + } // if readLength < reading + + break; + } // while true + } // scope for local + + length = BigEndianBinary.ToUInt32( buffer, 0 ); + + break; + } + } + + offset += lengthOfLength; + this.CheckLength( length, header ); + var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), buffer, offset, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + result = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else + { + return AsyncReadResult.Fail(); + } + + this._offset = offset; + this._collectionType = CollectionType.None; + return AsyncReadResult.Success( result ); + } + +#endif // FEATURE_TAP + + protected sealed override long? SkipCore() + { + var startOffset = this._offset; + MessagePackObject notUsed; + if ( !this.ReadObject( /* isDeep */true, out notUsed ) ) + { + return null; + } + + return this._offset - startOffset; + } + +#if FEATURE_TAP + protected sealed override async Task SkipAsyncCore( CancellationToken cancellationToken ) + { + var startOffset = this._offset; + var asyncReadResult = await this.ReadObjectAsync( /* isDeep */true, cancellationToken ).ConfigureAwait( false ); + if ( !asyncReadResult.Success ) + { + return null; + } + + return this._offset - startOffset; + } + +#endif // FEATURE_TAP + public sealed override bool ReadObject( out MessagePackObject result ) + { + return this.ReadObject( /* isDeep*/true, out result ); + } + +#if FEATURE_TAP + + public sealed override Task> ReadObjectAsync( CancellationToken cancellationToken ) + { + return this.ReadObjectAsync( /* isDeep*/true, cancellationToken ); + } + +#endif // FEATURE_TAP + + protected sealed override bool ReadCore() + { + MessagePackObject value; + var success = this.ReadObject( /* isDeep */false, out value ); + if ( success ) + { + this._data = value; + return true; + } + else + { + return false; + } + } + +#if FEATURE_TAP + + protected sealed override async Task ReadAsyncCore( CancellationToken cancellationToken ) + { + var result = await this.ReadObjectAsync( /* isDeep */false, cancellationToken ).ConfigureAwait( false ); + if ( result.Success ) + { + this._data = result.Value; + return true; + } + else + { + return false; + } + } + +#endif // FEATURE_TAP + + private void ThrowUnassignedMessageTypeException( int header ) + { +#if DEBUG + Contract.Assert( header == 0xC1, "Unhandled header:" + header.ToString( "X2" ) ); +#endif // DEBUG + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + throw new UnassignedMessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Unknown header value 0x{0:X} at position {1:#,0}" + : "Unknown header value 0x{0:X} at offset {1:#,0}", + header, + offsetOrPosition + ) + ); + } + + private void CheckLength( uint length, ReadValueResult type ) + { + if ( length > Int32.MaxValue ) + { + this.ThrowTooLongLengthException( length, type ); + } + } + + private void ThrowTooLongLengthException( uint length, ReadValueResult type ) + { + string message; + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + + if ( ( type & ReadValueResult.ArrayTypeMask ) == ReadValueResult.ArrayTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at position {1:#,0}" + : "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at offset {1:#,0}"; + } + else if ( ( type & ReadValueResult.MapTypeMask ) == ReadValueResult.MapTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at position {1:#,0}" + : "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at offset {1:#,0}"; + } + else if ( ( type & ReadValueResult.ExtTypeMask ) == ReadValueResult.ExtTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large ext type (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" + : "MessagePack for CLI cannot handle large ext type (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; + } + else + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" + : "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; + } + + throw new MessageNotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + message, + length, + offsetOrPosition + ) + ); + } + + private void ThrowTypeException( string type, ReadValueResult header ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + var byteHeader = header.ToByte(); + throw new MessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Cannot convert '{0}' header from type '{2}'(0x{1:X}) in position {3:#,0}." + : "Cannot convert '{0}' header from type '{2}'(0x{1:X}) in offset {3:#,0}.", + type, + byteHeader, + MessagePackCode.ToString( byteHeader ), + offsetOrPosition + ) + ); + } + + private void ThrowTypeException( Type type, ReadValueResult header ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + var byteHeader = header.ToByte(); + throw new MessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in position {3:#,0}." + : "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in offset {3:#,0}.", + type, + byteHeader, + MessagePackCode.ToString( byteHeader ), + offsetOrPosition + ) + ); + } + } +} diff --git a/src/MsgPack/MessagePackStreamUnpacker.Unpack.tt b/src/MsgPack/MessagePackStreamUnpacker.Unpack.tt new file mode 100644 index 000000000..b4b700aca --- /dev/null +++ b/src/MsgPack/MessagePackStreamUnpacker.Unpack.tt @@ -0,0 +1,184 @@ +<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ include file=".\MessagePackUnpackerCommon.ttinclude" #> +<#@ Assembly Name="System.Core.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; +using System.IO; +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +#if !UNITY || MSGPACK_UNITY_FULL +using Int64Stack = System.Collections.Generic.Stack; +#endif // !UNITY || MSGPACK_UNITY_FULL + +namespace MsgPack +{ + // This file was generated from MessagePackStreamUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude T4Template. + // Do not modify this file. Edit MessagePackStreamUnpacker.Unpack.tt and MessagePackUnpackerCommon.ttinclude instead. + + partial class MessagePackStreamUnpacker + { +<# +this.WriteCommon( + "_offset", + new ReadMethodContext( "buffer", "offset", "Int64", useOffsetForBuffer: false ), + context => this.WritePrologue( context ), + ( context, collectionType ) => this.WriteEpilogue( context, collectionType ), + ( context, indentLevel, lengthExpression, onFail, isAsync ) => this.WriteReadBytes( context, indentLevel, lengthExpression, onFail, isAsync ), + isPseudoAsync: false +); +#> + } +} +<#+ +private void WritePrologue( ReadMethodContext context ) +{ +#> + var <#= context.BufferExpression #> = this._scalarBuffer; + var <#= context.OffsetExpression #> = this._offset; + this._lastOffset = this._offset; +<#+ +} // WritePrologue + +private void WriteEpilogue( ReadMethodContext context, string collectionType ) +{ +#> + this._offset = <#= context.OffsetExpression #>; +<#+ + if ( collectionType != null ) + { +#> + this._collectionType = <#= collectionType #>; +<#+ + } +} // WriteEpilogue + +private void WriteReadBytes( ReadMethodContext context, int indentLevel, string lengthExpression, Action onFail, bool isAsync ) +{ + this.PushIndent( indentLevel ); +#> +<#+ + if ( lengthExpression == "1" ) + { + if ( !isAsync ) + { +#> +if ( this._source.Read( <#= context.BufferExpression #>, 0, 1 ) < 1 ) +<#+ + } + else // if !isAsync + { +#> +if ( await this._source.ReadAsync( <#= context.BufferExpression #>, 0, 1, cancellationToken ).ConfigureAwait( false ) < 1 ) +<#+ + } // if !isAsync +#> +{ +<#+ + onFail( 1 ); +#> +} +<#+ + } + else // if lengthExpression == "1" + { +#> +// scope for local +{ + var bufferOffset = 0; + var reading = <#= lengthExpression #>; + // Retrying for splitted Stream such as NetworkStream + while( true ) + { +<#+ + if ( !isAsync ) + { +#> + var readLength = this._source.Read( <#= context.BufferExpression #>, bufferOffset, reading ); +<#+ + } + else // if !isAsync + { +#> + var readLength = await this._source.ReadAsync( <#= context.BufferExpression #>, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); +<#+ + } // if !isAsync +#> + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + +<#+ + onFail( 4 ); +#> + } + } // if readLength < reading + + break; + } // while true +} // scope for local +<#+ + } // if lengthExpression != "1" + + this.PopIndent(); +} // WriteReadBytes( context, indentLevel, lengthExpression, onFail, isAsync ) +#> diff --git a/src/MsgPack/MessagePackStreamUnpacker.cs b/src/MsgPack/MessagePackStreamUnpacker.cs new file mode 100644 index 000000000..18239f4f0 --- /dev/null +++ b/src/MsgPack/MessagePackStreamUnpacker.cs @@ -0,0 +1,580 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; +using System.IO; +using System.Text; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + /// + /// Implements common features for stream based MessagePack unpacker. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + abstract partial class MessagePackStreamUnpacker : Unpacker, IRootUnpacker + { + private readonly byte[] _oneByteBuffer = new byte[ 1 ]; + private readonly byte[] _scalarBuffer = new byte[ 8 ]; + private readonly Stream _source; + private readonly bool _useStreamPosition; + private readonly bool _ownsStream; + private CollectionType _collectionType; + private MessagePackObject _data; + private int _subtreeCount; + +#pragma warning disable CS0672 + public sealed override MessagePackObject? Data + { + get { return this._data; } + protected set { this._data = value.GetValueOrDefault(); } + } +#pragma warning restore CS0672 + + public sealed override MessagePackObject LastReadData + { + get { return this._data; } + protected set { this._data = value; } + } + + public sealed override bool IsArrayHeader + { + get { return this._collectionType == CollectionType.Array; } + } + + public sealed override bool IsMapHeader + { + get { return this._collectionType == CollectionType.Map; } + } + + public sealed override long ItemsCount + { + get { return this._collectionType == CollectionType.None ? 0 : this._data.AsInt64(); } + } + + public sealed override bool IsCollectionHeader + { + get { return this._collectionType != CollectionType.None; } + } + + CollectionType IRootUnpacker.CollectionType + { + get { return this._collectionType; } + } + + MessagePackObject? IRootUnpacker.Data + { +#pragma warning disable CS0618 + get { return this.Data; } + set { this.Data = value; } +#pragma warning restore CS0618 + } + + MessagePackObject IRootUnpacker.LastReadData + { + get { return this._data; } + set { this._data = value; } + } + +#if DEBUG +#if UNITY && DEBUG + public +#else + internal +#endif + Stream DebugSource + { + get { return this._source; } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + bool DebugOwnsStream + { + get { return this._ownsStream; } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + long DebugOffset + { + get { return this._offset; } + } + + internal sealed override long? UnderlyingStreamPosition + { + get { return this._offset; } + } + + long? IRootUnpacker.UnderlyingStreamPosition + { + get { return this.UnderlyingStreamPosition; } + } +#endif // DEBUG + + /// + /// An position of seekable or offset from start of this instance. + /// + private long _offset; + + /// + /// An position of seekable or offset from start of this instance before last operation. + /// + private long _lastOffset; + + internal override bool GetPreviousPosition( out long offsetOrPosition ) + { + offsetOrPosition = this._lastOffset; + return this._useStreamPosition; + } + + public MessagePackStreamUnpacker( Stream stream, PackerUnpackerStreamOptions streamOptions ) + { + if ( stream == null ) + { + throw new ArgumentNullException( "stream" ); + } + + var options = streamOptions ?? PackerUnpackerStreamOptions.None; + this._source = options.WrapStream( stream ); + this._ownsStream = options.OwnsStream; + this._useStreamPosition = stream.CanSeek; + this._offset = this._useStreamPosition ? stream.Position : 0L; + } + + protected override void Dispose( bool disposing ) + { + if ( disposing ) + { + if ( this._subtreeCount == 0 && this._ownsStream ) + { + this._source.Dispose(); + } + } + + base.Dispose( disposing ); + } + + protected void BeginReadSubtree() + { + this._subtreeCount++; + } + + protected internal override void EndReadSubtree() + { + base.EndReadSubtree(); + this._subtreeCount--; + } + + private bool ReadBinaryCore( int length, ref long offset, out byte[] result ) + { + this._lastOffset = this._offset; + + if ( length == 0 ) + { + result = Binary.Empty; + return true; + } + + result = new byte[ length ]; + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while ( true ) + { + var readLength = this._source.Read( result, bufferOffset, reading ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + } + + result = default( byte[] ); + return false; + } + + break; + } + + offset += length; + return true; + } + +#if FEATURE_TAP + + private async Task>> ReadBinaryCoreAsync( int length, long offset, CancellationToken cancellationToken ) + { + this._lastOffset = this._offset; + + if ( length == 0 ) + { + return AsyncReadResult.Success( Binary.Empty, offset ); + } + + var result = new byte[ length ]; + var bufferOffset = 0; + var reading = length; + // Retrying for splitted Stream such as NetworkStream + while ( true ) + { + var readLength = await this._source.ReadAsync( result, bufferOffset, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength < reading ) + { + if ( readLength > 0 ) + { + // retry reading + bufferOffset += readLength; + reading -= readLength; + continue; + } + else + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= ( bufferOffset + readLength ); + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + } + + return AsyncReadResult.Fail>(); + } + + break; + } + + offset += length; + return AsyncReadResult.Success( result, offset ); + } + +#endif // FEATURE_TAP + + private bool ReadStringCore( int length, ref long offset, out string result ) + { + this._lastOffset = this._offset; + + if ( length == 0 ) + { + result = String.Empty; + return true; + } + + // TODO: Span + var byteBuffer = BufferManager.NewByteBuffer( length * 4 ); + var charBuffer = BufferManager.NewCharBuffer( length ); + var resultBuffer = new StringBuilder( length ); + var decoder = MessagePackConvert.Utf8NonBomStrict.GetDecoder(); + var remaining = length; +#if DEBUG + bool isCompleted; +#endif // DEBUG + // Retrying for splitted Stream such as NetworkStream + do + { + var reading = Math.Min( byteBuffer.Length, remaining ); + var readLength = this._source.Read( byteBuffer, 0, reading ); + if ( readLength == 0 ) + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= resultBuffer.Length; + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + result = default( string ); + return false; + } + +#if DEBUG + isCompleted = +#endif // DEBUG + decoder.DecodeString( byteBuffer, 0, readLength, charBuffer, resultBuffer ); + + remaining -= readLength; + } while ( remaining > 0 ); + +#if DEBUG + Contract.Assert( isCompleted, "isCompleted == true" ); +#endif // DEBUG + result = resultBuffer.ToString(); + offset += length; + return true; + } + +#if FEATURE_TAP + + private async Task>> ReadStringCoreAsync( int length, long offset, CancellationToken cancellationToken ) + { + this._lastOffset = this._offset; + + if ( length == 0 ) + { + return AsyncReadResult.Success( String.Empty, offset ); + } + + // TODO: Span + var byteBuffer = BufferManager.NewByteBuffer( length * 4 ); + var charBuffer = BufferManager.NewCharBuffer( length ); + var resultBuffer = new StringBuilder( length ); + var decoder = MessagePackConvert.Utf8NonBomStrict.GetDecoder(); + var remaining = length; +#if DEBUG + bool isCompleted; +#endif // DEBUG + // Retrying for splitted Stream such as NetworkStream + do + { + var reading = Math.Min( byteBuffer.Length, remaining ); + var readLength = await this._source.ReadAsync( byteBuffer, 0, reading, cancellationToken ).ConfigureAwait( false ); + if ( readLength == 0 ) + { + if ( this._useStreamPosition ) + { + // Rollback + this._source.Position -= resultBuffer.Length; + } + else + { + // Throw because rollback is not available + this.ThrowEofException( reading ); + } + + return AsyncReadResult.Fail>(); + } + +#if DEBUG + isCompleted = +#endif // DEBUG + decoder.DecodeString( byteBuffer, 0, readLength, charBuffer, resultBuffer ); + + remaining -= readLength; + } while ( remaining > 0 ); + +#if DEBUG + Contract.Assert( isCompleted, "isCompleted == true" ); +#endif // DEBUG + offset += length; + return AsyncReadResult.Success( resultBuffer.ToString(), offset ); + } + +#endif // FEATURE_TAP + + private bool ReadRawStringCore( int length, ref long offset, out MessagePackString result ) + { + byte[] asBinary; + if ( !this.ReadBinaryCore( length, ref offset, out asBinary ) ) + { + result = default( MessagePackString ); + return false; + } + + try + { + result = new MessagePackString( MessagePackConvert.Utf8NonBomStrict.GetString( asBinary, 0, asBinary.Length ) ); + } + catch ( DecoderFallbackException ) + { + result = new MessagePackString( asBinary, true ); + } + + return true; + } + +#if FEATURE_TAP + + private async Task>> ReadRawStringCoreAsync( int length, long offset, CancellationToken cancellationToken ) + { + var asyncReadResult = await this.ReadBinaryCoreAsync( length, offset, cancellationToken ).ConfigureAwait( false ); + if ( !asyncReadResult.Success ) + { + return AsyncReadResult.Fail>(); + } + + var asBinary = asyncReadResult.Value.Result; + MessagePackString result; + try + { + result = new MessagePackString( MessagePackConvert.Utf8NonBomStrict.GetString( asBinary, 0, asBinary.Length ) ); + } + catch ( DecoderFallbackException ) + { + result = new MessagePackString( asBinary, true ); + } + + return AsyncReadResult.Success( result, asyncReadResult.Value.Offset ); + } + +#endif // FEATURE_TAP + + private bool Drain( uint size ) + { + this._lastOffset = this._offset; + + if ( this._useStreamPosition ) + { + var drained = this._source.Seek( size, SeekOrigin.Current ); + if ( drained < size ) + { + // Rollback + this._source.Position -= drained; + return false; + } + + this._offset += size; + return true; + } + else + { + // Actually, buffer size should be smaller than 2GB. + var buffer = BufferManager.NewByteBuffer( unchecked(( int )Math.Max( Int32.MaxValue, size )) ); + var totalSkipped = 0L; + while ( totalSkipped < size ) + { + var skipping = unchecked(( int )Math.Min( buffer.Length, size - totalSkipped )); + var skipped = this._source.Read( buffer, 0, skipping ); + totalSkipped += skipped; + if ( skipped < skipping ) + { + // Record + this._offset += totalSkipped; + return false; + } + } + + this._offset += totalSkipped; + return true; + } + } + +#if FEATURE_TAP + + private async Task DrainAsync( uint size, CancellationToken cancellationToken ) + { + this._lastOffset = this._offset; + + if ( this._useStreamPosition ) + { + var drained = this._source.Seek( size, SeekOrigin.Current ); + if ( drained < size ) + { + // Rollback + this._source.Position -= drained; + return false; + } + + this._offset += size; + return true; + } + else + { + // Actually, buffer size should be smaller than 2GB. + var buffer = BufferManager.NewByteBuffer( unchecked(( int )Math.Max( Int32.MaxValue, size )) ); + var totalSkipped = 0L; + while ( totalSkipped < size ) + { + var skipping = unchecked( ( int )Math.Min( buffer.Length, size - totalSkipped ) ); + var skipped = await this._source.ReadAsync( buffer, 0, skipping, cancellationToken ).ConfigureAwait( false ); + totalSkipped += skipped; + if ( skipped < skipping ) + { + // Record + this._offset += totalSkipped; + return false; + } + } + + this._offset += totalSkipped; + return true; + } + } + +#endif // FEATURE_TAP + + bool IRootUnpacker.ReadObject( bool isDeep, out MessagePackObject result ) + { + return this.ReadObject( isDeep, out result ); + } + + private void ThrowEofException( long reading ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + throw new InvalidMessagePackStreamException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Stream unexpectedly ends. Cannot read {0:#,0} bytes from stream at position {1:#,0}." + : "Stream unexpectedly ends. Cannot read {0:#,0} bytes from stream at offset {1:#,0}.", + reading, + offsetOrPosition + ) + ); + } + } +} diff --git a/src/MsgPack/MessagePackString.cs b/src/MsgPack/MessagePackString.cs index 1d38b1b3e..ad8b45e5d 100644 --- a/src/MsgPack/MessagePackString.cs +++ b/src/MsgPack/MessagePackString.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,11 +24,11 @@ using System; using System.Diagnostics; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; using System.Security; @@ -43,15 +43,20 @@ namespace MsgPack /// /// Encapselates and its serialized UTF-8 bytes. /// -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 [Serializable] -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 -#if !NETFX_35 && !UNITY +#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 +#if !NET35 && !UNITY [SecuritySafeCritical] -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY [DebuggerDisplay( "{DebuggerDisplayString}" )] [DebuggerTypeProxy( typeof( MessagePackStringDebuggerProxy ) )] - internal sealed class MessagePackString +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class MessagePackString { // TODO: CLOB support? // marker to indicate this is definitively binary. @@ -266,7 +271,7 @@ private static bool EqualsEncoded( MessagePackString left, MessagePackString rig return false; } -#if !UNITY && !WINDOWS_PHONE && !NETFX_CORE +#if !UNITY && !WINDOWS_PHONE && !NETFX_CORE && !UNITY if ( _isFastEqualsDisabled == 0 ) { try @@ -282,7 +287,7 @@ private static bool EqualsEncoded( MessagePackString left, MessagePackString rig Interlocked.Exchange( ref _isFastEqualsDisabled, 1 ); } } -#endif // if !UNITY && !WINDOWS_PHONE && !NETFX_CORE +#endif // if !UNITY && !WINDOWS_PHONE && !NETFX_CORE && !UNITY; return SlowEquals( left._encoded, right._encoded ); } @@ -300,7 +305,7 @@ private static bool SlowEquals( byte[] x, byte[] y ) return true; } -#if !UNITY && !WINDOWS_PHONE && !NETFX_CORE +#if !UNITY && !WINDOWS_PHONE && !NETFX_CORE && !UNITY #if SILVERLIGHT private static int _isFastEqualsDisabled = System.Windows.Application.Current.HasElevatedPermissions ? 0 : 1; @@ -316,9 +321,9 @@ internal static bool IsFastEqualsDisabled } #endif -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY private static bool UnsafeFastEquals( byte[] x, byte[] y ) { #if DEBUG @@ -336,7 +341,7 @@ private static bool UnsafeFastEquals( byte[] x, byte[] y ) return result == 0; } -#endif // if !UNITY && !WINDOWS_PHONE && !NETFX_CORE +#endif // if !UNITY && !WINDOWS_PHONE && !NETFX_CORE && !UNITY; #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 [Serializable] diff --git a/src/MsgPack/MessagePackUnpackerCommon.Read.ttinclude b/src/MsgPack/MessagePackUnpackerCommon.Read.ttinclude new file mode 100644 index 000000000..3a29d0d41 --- /dev/null +++ b/src/MsgPack/MessagePackUnpackerCommon.Read.ttinclude @@ -0,0 +1,1497 @@ +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Runtime.InteropServices" #><#+ +// +// MessagePack for CLI +// +// Copyright (C) 2010-2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +private void WriteReadOverrides( + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes, // context, indentLevel, lengthExpression, onFail, isAsync + bool isPseudoAsync +) +{ + foreach( var type in + new [] + { + typeof( byte ), typeof( sbyte ), + typeof( short ), typeof( ushort ), + typeof( int ), typeof( uint ), + typeof( long ), typeof( ulong ), + typeof( float ), typeof( double ), + } + ) + { + foreach ( var isAsync in new [] { false, true } ) + { + this.WriteBeginAsyncRegion( isAsync ); + + foreach ( var isNullable in new [] { false, true } ) + { + this.WriteReadScalar( type.Name, isNullable, isAsync, isPseudoAsync, context, prologue, epilogue, readBytes ); + } + + this.WriteEndAsyncRegion( isAsync ); + } + } + + foreach ( var isAsync in new [] { false, true } ) + { + this.WriteBeginAsyncRegion( isAsync ); + + foreach ( var isNullable in new [] { false, true } ) + { + this.WriteReadBoolean( isNullable, isAsync, isPseudoAsync, context, prologue, epilogue, readBytes ); + } + + this.WriteEndAsyncRegion( isAsync ); + } + + foreach ( var type in + new [] + { + new { Label = "Binary", Name = "Byte[]" }, + new { Label = "String", Name = "String" } + } + ) + { + foreach ( var isAsync in new [] { false, true } ) + { + this.WriteBeginAsyncRegion( isAsync ); + + this.WriteReadRaw( type.Label, type.Name, isAsync, isPseudoAsync, context, prologue, epilogue, readBytes ); + + this.WriteEndAsyncRegion( isAsync ); + } + } + + foreach ( var isAsync in new [] { false, true } ) + { + this.WriteBeginAsyncRegion( isAsync ); + + this.WriteReadObject( isAsync, isPseudoAsync, context, prologue, epilogue, readBytes ); + + this.WriteEndAsyncRegion( isAsync ); + } + + foreach ( var collectionType in + new [] + { + "Array", + "Map" + } + ) + { + foreach ( var isAsync in new [] { false, true } ) + { + this.WriteBeginAsyncRegion( isAsync ); + + this.WriteReadCollectionLength( collectionType, typeof( long ).Name, isAsync, isPseudoAsync, context, prologue, epilogue, readBytes ); + + this.WriteEndAsyncRegion( isAsync ); + } + } + + foreach ( var isAsync in new [] { false, true } ) + { + this.WriteBeginAsyncRegion( isAsync ); + + foreach ( var isNullable in new [] { false, true } ) + { + this.WriteReadExt( isNullable, isAsync, isPseudoAsync, context, prologue, epilogue, readBytes ); + } + + this.WriteEndAsyncRegion( isAsync ); + } +} // WriteReadOverrides + +private void WriteReadScalar( + string type, + bool isNullable, + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + var typeLabel = ( isNullable ? "Nullable" : String.Empty ) + type; + var typeName = type + ( isNullable ? "?" : String.Empty ); + var isSigned = typeName.StartsWith( "SByte" ) || typeName.StartsWith( "Int" ); +#> + public sealed override <#= Signature( typeLabel, typeName, "Read{0}", String.Empty, isAsync, isPseudoAsync ) #> + { +<#+ + if ( isAsync && isPseudoAsync ) + { +#> + <#= typeName #> result; + return Task.FromResult( this.Read<#= typeLabel #>( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail<<#= typeName #>>() ); +<#+ + } + else // if ( isAsync && isPseudoAsync ) + { + this.WriteReadPrologue( typeName, context, prologue, readBytes, isAsync ); +#> + + // Check immediate + if ( ( header & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + var immediateValue = unchecked( ( sbyte )( byte )( header & ReadValueResult.ValueOrLengthMask ) ); +<#+ + if ( !isSigned ) + { +#> + // Check sign + result = checked( ( <#= typeName #> )immediateValue ); +<#+ + } + else // if isSigned + { +#> + result = ( <#= typeName #> )immediateValue; +<#+ + } // if isSigned +#> + <#= context.OffsetExpression #>++; + // goto tail + } + else + { + // Slow path +<#+ + if ( !isAsync ) + { +#> + if ( !this.Read<#= typeLabel #>Slow( header, <#= context.BufferExpression #>, ref <#= context.OffsetExpression #>, out result ) ) +<#+ + } + else // if !isAsync + { +#> + var slowAsyncResult = await this.Read<#= typeLabel #>SlowAsync( header, <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); + if ( slowAsyncResult.Success ) + { + result = slowAsyncResult.Value.Result; + offset = slowAsyncResult.Value.Offset; + } + else +<#+ + } // if !isAsync +#> + { +<#+ + this.OnFail( typeName, context.OffsetType, 5, isAsync, withOffset: false ); +#> + } + // goto tail + } + +<#+ + this.WriteReadEpilogue( context, "CollectionType.None", epilogue, isAsync ); +#> + } + +<#+ + var slowParameters = + "ReadValueResult header, " + + "byte[] " + context.BufferExpression + ", " + + ( !isAsync ? "ref " : String.Empty ) + context.OffsetType + " " + context.OffsetExpression + ", "; +#> + private <#= SignatureWithOffset( typeLabel, typeName, context.OffsetType, "Read{0}Slow", slowParameters, isAsync, isPseudoAsync ) #> + { +<#+ + // nullable? + if ( typeName.EndsWith( "?" ) ) + { +#> + if ( header == ReadValueResult.Nil ) + { +<#+ + if ( !isAsync ) + { +#> + result = default( <#= typeName #> ); + <#= context.OffsetExpression #>++; + return true; +<#+ + } + else // if !isAsync + { +#> + return AsyncReadResult.Success( default( <#= typeName #> ), <#= context.OffsetExpression #> + 1 ); +<#+ + } // if !isAsync +#> + } + +<#+ + var nonNullableTypeName = typeName.Remove( typeName.Length - 1 ); +#> + <#= nonNullableTypeName #> value; +<#+ + if ( !isAsync ) + { +#> + if( !this.Read<#= nonNullableTypeName #>Slow( header, <#= context.BufferExpression #>, ref <#= context.OffsetExpression #>, out value ) ) +<#+ + } + else // if !isAsync + { +#> + var asyncReadResult = await this.Read<#= typeName.Remove( typeName.Length - 1 ) #>SlowAsync( header, <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + value = asyncReadResult.Value.Result; + <#= context.OffsetExpression #> = asyncReadResult.Value.Offset; + } + else +<#+ + } // if !isAsync +#> + { +<#+ + this.OnFail( typeName, context.OffsetType, 4, isAsync, withOffset: true ); +#> + } + +<#+ + if ( !isAsync ) + { +#> + result = value; + return true; +<#+ + } + else // if !isAsync + { +#> + return AsyncReadResult.Success( ( <#= typeName #> )value, <#= context.OffsetExpression #> ); +<#+ + } // if !isAsync + } + else // if !nullable + { + if ( isAsync ) + { +#> + <#= typeName #> result; +<#+ + } // if !isAsync +#> + // Check type + if ( ( header & ReadValueResult.NonScalarBitMask ) != 0 ) + { + this.ThrowTypeException( typeof( <#= typeName #> ), header ); + } + + <#= context.OffsetExpression #>++; + var length = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; +<#+ + readBytes( context, 3, "length", indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + + checked + { + switch( ( int )( header & ReadValueResult.TypeCodeMask ) ) + { + case 0x100: // Byte + { + result = ( <#= typeName #> )<#= context.BufferExpression #>[ <#= context.BufferOffsetExpression #> ]; + break; + } +<#+ + for ( var i = 1; i <= 3; i++ ) + { + var bytes = Math.Pow( 2, i ).ToString( CultureInfo.InvariantCulture ); + var bits = ( Math.Pow( 2, i ) * 8 ).ToString( CultureInfo.InvariantCulture ); +#> + case 0x<#= bytes #>00: // UInt<#= bits #> + { + result = ( <#= typeName #> )BigEndianBinary.ToUInt<#= bits #>( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + break; + } +<#+ + } // for +#> + case 0x1100: // SByte + { + result = ( <#= typeName #> )( unchecked( ( SByte )<#= context.BufferExpression #>[ <#= context.BufferOffsetExpression #> ] ) ); + break; + } +<#+ + for ( var i = 1; i <= 3; i++ ) + { + var bytes = Math.Pow( 2, i ).ToString( CultureInfo.InvariantCulture ); + var bits = ( Math.Pow( 2, i ) * 8 ).ToString( CultureInfo.InvariantCulture ); +#> + case 0x1<#= bytes #>00: // Int<#= bits #> + { + result = ( <#= typeName #> )BigEndianBinary.ToInt<#= bits #>( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + break; + } +<#+ + } // for +#> + case 0x2400: // Single + { + result = ( <#= typeName #> )BigEndianBinary.ToSingle( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + break; + } + case 0x2800: // Double + { + result = ( <#= typeName #> )BigEndianBinary.ToDouble( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + break; + } + default: + { + this.ThrowTypeException( typeof( <#= typeName #> ), header ); + // Never + result = default( <#= typeName #> ); + break; + } + } // switch + } // checked + + <#= context.OffsetExpression #> += length; +<#+ + if ( !isAsync ) + { +#> + return true; +<#+ + } + else // if !isAsync + { +#> + return AsyncReadResult.Success( result, <#= context.OffsetExpression #> ); +<#+ + } // if !isAsync + } // if !nullable + } // if ( isAsync && isPseudoAsync ) +#> + } + +<#+ +} // WriteReadScalar + + +private void WriteReadBoolean( + bool isNullable, + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + var typeLabel = ( isNullable ? "Nullable" : String.Empty ) + "Boolean"; + var typeName = "Boolean" + ( isNullable ? "?" : String.Empty ); +#> + public sealed override <#= Signature( typeLabel, typeName, "Read{0}", String.Empty, isAsync, isPseudoAsync ) #> + { +<#+ + if ( isAsync && isPseudoAsync ) + { +#> + <#= typeName #> result; + return Task.FromResult( this.Read<#= typeLabel #>( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail<<#= typeName #>>() ); +<#+ + } + else // if ( isAsync && isPseudoAsync ) + { + this.WriteReadPrologue( typeName, context, prologue, readBytes, isAsync ); +#> + <#= context.OffsetExpression #>++; + + switch ( header ) + { +<#+ + if ( isNullable ) + { +#> + case ReadValueResult.Nil: + { + result = default( bool? ); + break; + } +<#+ + } // if isNullable +#> + case ReadValueResult.True: + { + result = true; + break; + } + case ReadValueResult.False: + { + result = false; + break; + } + default: + { + this.ThrowTypeException( typeof( <#= typeName #> ), header ); + // never + result = false; + break; + } + } + +<#+ + this.WriteReadEpilogue( context, "CollectionType.None", epilogue, isAsync ); + } +#> + } // if ( isAsync && isPseudoAsync ) + +<#+ +} // WriteReadBoolean + + +private void WriteReadCollectionLength( + string collectionType, + string typeName, + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + this.WriteReadCollectionCore( + collectionType, + collectionType + "Length", + typeName, + isAsync, + isPseudoAsync, + context, + prologue, + epilogue, + readBytes, + null, + ( !isAsync || !isPseudoAsync ) ? () => this.WriteReadCollectionLengthCore() : default( Action ) + ); +} // WriteReadCollectionLength + +private void WriteReadCollectionLengthCore() +{ +#> + result = length; + this._data = length; +<#+ +} // WriteReadCollectionLengthCore + +private void WriteReadRaw( + string typeLabel, + string typeName, + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + this.WriteReadCollectionCore( + "Raw", + typeLabel, + typeName, + isAsync, + isPseudoAsync, + context, + prologue, + epilogue, + readBytes, + null, + ( !isAsync || !isPseudoAsync ) ? () => this.WriteReadRawCoreCall( context, typeLabel, typeName, typeName, 3, "result", isAsync, withOffset: false ) : default( Action ) + ); +} // WriteReadRaw + +private void WriteReadRawCoreCall( + ReadMethodContext context, + string typeLabel, + string typeName, + string returnTypeName, + int indentLevel, + string resultExpression, + bool isAsync, + bool withOffset +) +{ + this.PushIndent( indentLevel ); + if ( !isAsync ) + { +#> +if( !this.Read<#= typeLabel #>Core( unchecked( ( int )length ), ref <#= context.OffsetExpression #>, out <#= resultExpression #> ) ) +<#+ + } + else // if !isAsync + { +#> +var asyncReadResult = await this.Read<#= typeLabel #>CoreAsync( unchecked( ( int )length ), <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); +if ( asyncReadResult.Success ) +{ + <#= context.OffsetExpression #> = asyncReadResult.Value.Offset; + <#= resultExpression #> = asyncReadResult.Value.Result; +} +else +<#+ + } // if !isAsync +#> +{ +<#+ + this.OnFail( returnTypeName, context.OffsetType, 1, isAsync, withOffset ); +#> +} + +<#+ + this.PopIndent(); +} // WriteReadRawCoreCall + + +private void WriteReadExt( + bool isNullable, + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + var typeLabel = ( isNullable ? "Nullable" : String.Empty ) + "MessagePackExtendedTypeObject"; + var typeName = "MessagePackExtendedTypeObject" + ( isNullable ? "?" : String.Empty ); + this.WriteReadCollectionCore( + "Ext", + typeLabel, + typeName, + isAsync, + isPseudoAsync, + context, + prologue, + epilogue, + readBytes, + ( ( !isAsync || !isPseudoAsync ) && isNullable ) ? () => this.WriteNullableReadExtPrologue( isAsync ) : default( Action ), + ( !isAsync || !isPseudoAsync ) ? () => this.WriteReadExtEpilogue( isNullable, isAsync, typeName, context, readBytes ) : default( Action ) + ); + + if ( !isNullable && ( !isAsync || !isPseudoAsync ) ) + { + var parameters = + "int length, " + + "byte[] " + context.BufferExpression + ", " + + ( !isAsync ? "ref " : String.Empty ) + context.OffsetType + " " + context.OffsetExpression + ", "; +#> + private <#= SignatureWithOffset( typeLabel, typeName, context.OffsetType, "Read{0}Core", parameters, isAsync, isPseudoAsync ) #> + { + // Read type code +<#+ + readBytes( context, 3, "1", indentLevel => this.OnFail( "MessagePackExtendedTypeObject", context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + + var typeCode = <#= context.BufferExpression #>[ <#= context.BufferOffsetExpression #> ]; + <#= context.OffsetExpression #>++; + + // Read body +<#+ + this.WriteReadBinaryCoreCall( typeName, context, "body", "length", 3, isAsync ); + + if ( !isAsync ) + { +#> + + result = MessagePackExtendedTypeObject.Unpack( typeCode, body ); + return true; +<#+ + } + else + { +#> + return AsyncReadResult.Success( MessagePackExtendedTypeObject.Unpack( typeCode, body ), <#= context.OffsetExpression #> ); +<#+ + } +#> + } + +<#+ + } // if !isNullable +} // WriteReadExt + +private void WriteNullableReadExtPrologue( bool isAsync ) +{ +#> + if ( header == ReadValueResult.Nil ) + { +<#+ + if ( !isAsync ) + { +#> + result = default( MessagePackExtendedTypeObject? ); + return true; +<#+ + } + else + { +#> + return AsyncReadResult.Success( default( MessagePackExtendedTypeObject? ) ); +<#+ + } +#> + } +<#+ +} // WriteNullableReadExtPrologue + +private void WriteReadExtEpilogue( + bool isNullable, + bool isAsync, + string typeName, + ReadMethodContext context, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + this.WriteReadExtCoreCall( isNullable, isAsync, typeName, context, 3, "result", readBytes, withOffset: false ); + + if ( isNullable && !isAsync ) + { +#> + result = value; +<#+ + } +} // WriteReadExtEpilogue + +private void WriteReadExtCoreCall( + bool isNullable, + bool isAsync, + string returnType, + ReadMethodContext context, + int indentLevel, + string resultExpression, + Action, bool> readBytes, // context, indentLevel, lengthExpression, onFail, isAsync + bool withOffset +) +{ + this.PushIndent( indentLevel ); + + var variable = isNullable ? "value" : resultExpression; + if ( !isAsync ) + { + if ( isNullable ) + { +#> +MessagePackExtendedTypeObject <#= variable #>; +<#+ + } +#> +if ( !this.ReadMessagePackExtendedTypeObjectCore( unchecked( ( int )length ), <#= context.BufferExpression #>, ref <#= context.OffsetExpression #>, out <#= variable #> ) ) +<#+ + } + else + { +#> +var asyncReadResult = await this.ReadMessagePackExtendedTypeObjectCoreAsync( unchecked( ( int )length ), <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); +if ( asyncReadResult.Success ) +{ + <#= resultExpression #> = asyncReadResult.Value.Result; + <#= context.OffsetExpression #> = asyncReadResult.Value.Offset; +} +else +<#+ + } +#> +{ +<#+ + this.OnFail( returnType, context.OffsetType, 1, isAsync, withOffset ); +#> +} + +<#+ + this.PopIndent(); +} // WriteReadExtCoreCall + + +private void WriteReadCollectionCore( + string collectionType, + string typeLabel, + string typeName, + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes, // context, indentLevel, lengthExpression, onFail, isAsync + Action onHeaderRead, + Action onLengthChecked +) +{ +#> + public sealed override <#= Signature( typeLabel, typeName, "Read{0}", String.Empty, isAsync, isPseudoAsync ) #> + { +<#+ + if ( isAsync && isPseudoAsync ) + { +#> + <#= typeName #> result; + return Task.FromResult( this.Read<#= typeLabel #>( out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail<<#= typeName #>>() ); +<#+ + } + else // if ( isAsync && isPseudoAsync ) + { + this.WriteReadPrologue( typeName, context, prologue, readBytes, isAsync ); + if ( onHeaderRead != null ) + { + onHeaderRead(); + } +#> + <#= context.OffsetExpression #>++; +<#+ + if ( collectionType == "Raw" ) + { +#> + + // <#= typeName #> can be null. + if ( header == ReadValueResult.Nil ) + { + result = null; +<#+ + this.PushIndent( 1 ); + this.WriteReadEpilogue( context, "CollectionType.None", epilogue, isAsync ); + this.PopIndent(); +#> + } +<#+ + } // if collectionType == "Raw" +#> + + // Check type + if ( ( header & ReadValueResult.<#= collectionType #>TypeMask ) != ReadValueResult.<#= collectionType #>TypeMask ) + { + this.ThrowTypeException( "<#= collectionType.ToLowerInvariant() #>", header ); + } + + // Get length + var lengthOfLength = ( int )( header & ReadValueResult.LengthOfLengthMask ) >> 8; + uint length; + switch ( lengthOfLength ) + { + case 0: + { + length = ( byte )( header & ReadValueResult.ValueOrLengthMask ); + break; + } + case 1: // <#= collectionType #>8 + { +<#+ + this.WriteReadCollectionLengthSlowCall( context, 1, typeName, readBytes, isAsync ); +#> + break; + } + case 2: // <#= collectionType #>16 + { +<#+ + this.WriteReadCollectionLengthSlowCall( context, 2, typeName, readBytes, isAsync ); +#> + break; + } + default: // <#= collectionType #>32 + { +#if DEBUG + Contract.Assert( lengthOfLength == 4, lengthOfLength + " == 4" ); +#endif // DEBUG +<#+ + this.WriteReadCollectionLengthSlowCall( context, 4, typeName, readBytes, isAsync ); +#> + break; + } + } + + <#= context.OffsetExpression #> += lengthOfLength; + this.CheckLength( length, header ); +<#+ + onLengthChecked(); + + this.WriteReadEpilogue( context, "CollectionType." + ( ( collectionType == "Array" || collectionType == "Map" ) ? collectionType : "None" ), epilogue, isAsync ); + } // if ( isAsync && isPseudoAsync ) +#> + } + +<#+ +} // WriteReadCollectionCore + +private void WriteReadCollectionLengthSlowCall( + ReadMethodContext context, + int byteLength, + string typeName, + Action, bool> readBytes, // context, indentLevel, lengthExpression, onFail, isAsync + bool isAsync +) +{ + var bytes = byteLength.ToString( CultureInfo.InvariantCulture ); + var bits = ( byteLength * 8 ).ToString( CultureInfo.InvariantCulture ); + + readBytes( context, 5, bytes, indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: false ), isAsync ); +#> + + length = BigEndianBinary.To<#= byteLength == 1 ? "Byte" : "UInt" + bits #>( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + +<#+ +} // WriteReadCollectionLengthSlowCall + + +private void WriteReadObject( + bool isAsync, + bool isPseudoAsync, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes // context, indentLevel, lengthExpression, onFail, isAsync +) +{ + var typeLabel = "Object"; + var typeName = "MessagePackObject"; +#> + private <#= Signature( typeLabel, typeName, "Read{0}", "bool isDeep, ", isAsync, isPseudoAsync ) #> + { +<#+ + if ( isAsync && isPseudoAsync ) + { +#> + <#= typeName #> result; + return Task.FromResult( this.Read<#= typeLabel #>( isDeep, out result ) ? AsyncReadResult.Success( result ) : AsyncReadResult.Fail<<#= typeName #>>() ); +<#+ + } + else // if ( isAsync && isPseudoAsync ) + { + // Do not read header yet. + if ( isAsync ) + { +#> + <#= typeName #> result; +<#+ + } // if isAsync + + prologue( context ); + + if ( !isAsync ) + { +#> + if ( !this.ReadObjectCore( isDeep, <#= context.BufferExpression #>, ref <#= context.OffsetExpression #>, out result ) ) +<#+ + } + else // if !isAsync + { +#> + var asyncReadResult = await this.ReadObjectCoreAsync( isDeep, <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadResult.Success ) + { + result = asyncReadResult.Value.Result; + offset = asyncReadResult.Value.Offset; + } + else +<#+ + } // if !isAsync +#> + { +<#+ + this.OnFail( typeName, context.OffsetType, 4, isAsync, withOffset: false ); +#> + } +<#+ + epilogue( context, null ); +#> + return <#= !isAsync ? "true" : "AsyncReadResult.Success( result )" #>; + } + +<#+ + var coreParameters = + "bool isDeep, " + + "byte[] " + context.BufferExpression + ", " + + ( !isAsync ? "ref " : String.Empty ) + context.OffsetType + " " + context.OffsetExpression + ", "; +#> + private <#= SignatureWithOffset( typeLabel, typeName, context.OffsetType, "Read{0}Core", coreParameters, isAsync, isPseudoAsync ) #> + { +<#+ + readBytes( context, 3, "1", indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + + var byteHeader = <#= context.BufferExpression #>[ <#= context.BufferOffsetExpression #> ]; + <#= context.OffsetExpression #>++; + var collectionType = ReadValueResults.CollectionType[ byteHeader ]; +<#+ + if ( isAsync ) + { +#> + <#= typeName #> result; +<#+ + } // !isAsync +#> + + if ( ReadValueResults.HasConstantObject[ byteHeader ] ) + { + result = ReadValueResults.ContantObject[ byteHeader ]; + } + else + { + var header = ReadValueResults.EncodedTypes[ byteHeader ]; + + if ( ( header & ReadValueResult.RawTypeMask ) == ReadValueResult.RawTypeMask && ( header & ReadValueResult.LengthOfLengthMask ) == 0 ) + { + // fixed raw + int length = ( int )( header & ReadValueResult.ValueOrLengthMask ); + +<#+ + this.WriteReadBinaryCoreCall( typeName, context, "binary", "length", 5, isAsync ); +#> + + result = binary; + } + else + { +<#+ + if ( !isAsync ) + { +#> + if ( !this.ReadObjectSlow( header, <#= context.BufferExpression #>, ref <#= context.OffsetExpression #>, out result ) ) +<#+ + } + else // if !isAsync + { +#> + var asyncReadReasult = await this.ReadObjectSlowAsync( header, <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadReasult.Success ) + { + result = asyncReadReasult.Value.Result; + <#= context.OffsetExpression #> = asyncReadReasult.Value.Offset; + } + else +<#+ + } // if !isAsync +#> + { +<#+ + this.OnFail( typeName, context.OffsetType, 6, isAsync, withOffset: true ); +#> + } + } + } + + if ( isDeep && collectionType != CollectionType.None ) + { +<#+ + if ( !isAsync ) + { +#> + if ( !this.ReadItems( result.AsInt32(), collectionType == CollectionType.Map, <#= context.BufferExpression #>, ref offset, out result ) ) +<#+ + } + else // if !isAsync + { +#> + var asyncReadReasult = await this.ReadItemsAsync( result.AsInt32(), collectionType == CollectionType.Map, <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); + if ( asyncReadReasult.Success ) + { + result = asyncReadReasult.Value.Result; + <#= context.OffsetExpression #> = asyncReadReasult.Value.Offset; + } + else +<#+ + } // if !isAsync +#> + { +<#+ + this.OnFail( typeName, context.OffsetType, 5, isAsync, withOffset: true ); +#> + } + } + + this._data = result; + this._collectionType = collectionType; + return <#= !isAsync ? "true" : "AsyncReadResult.Success( result, offset )" #>; + } + +<#+ + var slowParameters = + "ReadValueResult header, " + + "byte[] " + context.BufferExpression + ", " + + ( !isAsync ? "ref " : String.Empty ) + context.OffsetType + " " + context.OffsetExpression + ", "; +#> + private <#= SignatureWithOffset( typeLabel, typeName, context.OffsetType, "Read{0}Slow", slowParameters, isAsync, isPseudoAsync ) #> + { +<#+ + if ( isAsync ) + { +#> + <#= typeName #> result; +<#+ + } // if !isAsync +#> + switch ( header & ReadValueResult.TypeCodeMask ) + { + case ReadValueResult.Array16Type: + case ReadValueResult.Map16Type: + { +<#+ + readBytes( context, 5, "2", indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + result = BigEndianBinary.ToUInt16( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + <#= context.OffsetExpression #> += 2; + break; + } + case ReadValueResult.Array32Type: + case ReadValueResult.Map32Type: + { +<#+ + readBytes( context, 5, "4", indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + result = BigEndianBinary.ToUInt32( <#= context.BufferExpression #>, <#= context.BufferOffsetExpression #> ); + <#= context.OffsetExpression #> += 4; + break; + } +<#+ + foreach ( var item in + new [] + { + new { Label = "String", Type = "string", RawCallLabel = "RawString", RawCallType = "MessagePackString", Code = "Str", ConstructorFormat = "new MessagePackObject( {0} )" }, + new { Label = "Binary", Type = "byte[]", RawCallLabel = "Binary", RawCallType = "byte[]", Code = "Bin", ConstructorFormat = "new MessagePackObject( {0}, /* isBinary */true )" }, + } + ) + { + foreach ( var bits in + new [] + { + new { Value = "8", Bytes = "1", Decode = "{0}[ {1} ]" }, + new { Value = "16", Bytes = "2", Decode = "BigEndianBinary.ToUInt16( {0}, {1} )" }, + new { Value = "32", Bytes = "4", Decode = "BigEndianBinary.ToUInt32( {0}, {1} )" } + } + ) + { + var variable = item.Label.ToLowerInvariant() + "Value"; +#> + case ReadValueResult.<#= item.Code #><#= bits.Value #>Type: + { +<#+ + readBytes( context, 5, bits.Bytes, indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + + var length = <#= String.Format( CultureInfo.InvariantCulture, bits.Decode, context.BufferExpression , context.BufferOffsetExpression ) #>; + this.CheckLength( length, header ); + <#= context.OffsetExpression #> += <#= bits.Bytes #>; + <#= item.RawCallType #> <#= variable #>; +<#+ + this.WriteReadRawCoreCall( context, item.RawCallLabel, item.Type, typeName, 5, variable, isAsync, withOffset: true ); +#> + result = <#= String.Format( CultureInfo.InvariantCulture, item.ConstructorFormat, variable ) #>; + break; + } +<#+ + } // foreach bits + } // foreach item +#> + case ReadValueResult.FixExtType: + { + var length = ( header & ReadValueResult.ValueOrLengthMask ); + MessagePackExtendedTypeObject ext; +<#+ + this.WriteReadExtCoreCall( false, isAsync, typeName, context, 5, "ext", readBytes, withOffset: true ); +#> + result = ext; + break; + } +<#+ + foreach ( var bits in + new [] + { + new { Value = "8", Bytes = "1", Decode = "{0}[ {1} ]" }, + new { Value = "16", Bytes = "2", Decode = "BigEndianBinary.ToUInt16( {0}, {1} )" }, + new { Value = "32", Bytes = "4", Decode = "BigEndianBinary.ToUInt32( {0}, {1} )" } + } + ) + { +#> + case ReadValueResult.Ext<#= bits.Value #>Type: + { +<#+ + readBytes( context, 5, bits.Bytes, indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + var length = <#= String.Format( CultureInfo.InvariantCulture, bits.Decode, context.BufferExpression , context.BufferOffsetExpression ) #>; + <#= context.OffsetExpression #> += <#= bits.Bytes #>; + MessagePackExtendedTypeObject ext; +<#+ + this.WriteReadExtCoreCall( false, isAsync, typeName, context, 5, "ext", readBytes, withOffset: true ); +#> + result = ext; + break; + } +<#+ + } // foreach bits + + foreach ( var item in + new [] + { + new { Prefix = String.Empty, ByteDecode = "unchecked( ( sbyte ){0}[ {1} ] )" }, + new { Prefix = "U", ByteDecode = "{0}[ {1} ]" } + } + ) + { + foreach ( var bits in + new [] + { + new { Value = "8", Bytes = "1", Decode = item.ByteDecode }, + new { Value = "16", Bytes = "2", Decode = "BigEndianBinary.To" + item.Prefix + "Int16( {0}, {1} )" }, + new { Value = "32", Bytes = "4", Decode = "BigEndianBinary.To" + item.Prefix + "Int32( {0}, {1} )" }, + new { Value = "64", Bytes = "8", Decode = "BigEndianBinary.To" + item.Prefix + "Int64( {0}, {1} )" } + } + ) + { +#> + case ReadValueResult.<#= item.Prefix #>Int<#= bits.Value #>Type: + { +<#+ + readBytes( context, 5, bits.Bytes, indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + result = <#= String.Format( CultureInfo.InvariantCulture, bits.Decode, context.BufferExpression , context.BufferOffsetExpression ) #>; + <#= context.OffsetExpression #> += <#= bits.Bytes #>; + break; + } +<#+ + } // foreach bits + } // foreach item + + foreach ( var bits in + new [] + { + new { Value = "32", Bytes = "4", Decode = "BigEndianBinary.ToSingle( {0}, {1} )" }, + new { Value = "64", Bytes = "8", Decode = "BigEndianBinary.ToDouble( {0}, {1} )" } + } + ) + { +#> + case ReadValueResult.Real<#= bits.Value #>Type: + { +<#+ + readBytes( context, 5, bits.Bytes, indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: true ), isAsync ); +#> + result = <#= String.Format( CultureInfo.InvariantCulture, bits.Decode, context.BufferExpression , context.BufferOffsetExpression ) #>; + <#= context.OffsetExpression #> += <#= bits.Bytes #>; + break; + } +<#+ + } // foreach bits +#> + default: + { +#if DEBUG + Contract.Assert( header == ReadValueResult.InvalidCode, header.ToString( "X" ) + " == ReadValueResult.InvalidCode" ); +#endif // DEBUG + this.ThrowUnassignedMessageTypeException( 0xC1 ); + // never + result = default( MessagePackObject ); + break; + } + } + + return <#= !isAsync ? "true" : "AsyncReadResult.Success( result, " + context.OffsetExpression + " )" #>; + } + +<#+ + var itemsParameters = + "int count, bool isMap, " + + "byte[] " + context.BufferExpression + ", " + + ( !isAsync ? "ref " : String.Empty ) + context.OffsetType + " " + context.OffsetExpression + ", "; +#> + private <#= SignatureWithOffset( typeLabel, typeName, context.OffsetType, "ReadItems", itemsParameters, isAsync, isPseudoAsync ) #> + { + MessagePackObject container; + if ( !isMap ) + { + var array = new MessagePackObject[ count ]; + for ( var i = 0; i < count; i++ ) + { + MessagePackObject item; +<#+ + this.WriteReadItemCore( context, "item", isAsync ); +#> + array[ i ] = item; + } + + container = new MessagePackObject( array, true ); + } + else + { + var map = new MessagePackObjectDictionary( count ); + + for ( var i = 0; i < count; i++ ) + { + MessagePackObject key; +<#+ + this.WriteReadItemCore( context, "key", isAsync ); +#> + MessagePackObject value; +<#+ + this.WriteReadItemCore( context, "value", isAsync ); +#> + map.Add( key, value ); + } + + container = new MessagePackObject( map, true ); + } +<#+ + if ( !isAsync ) + { +#> + result = container; + return true; +<#+ + } + else // if !isAsync + { +#> + return AsyncReadResult.Success( container, <#= context.OffsetExpression #> ); +<#+ + } // if !isAsync + } // if ( isAsync && isPseudoAsync ) +#> + } + +<#+ +} // WriteReadObject + +private void WriteReadItemCore( + ReadMethodContext context, + string resultVariable, + bool isAsync +) +{ +#> +<#+ + if ( !isAsync ) + { +#> + if ( !this.ReadObjectCore( true, <#= context.BufferExpression #>, ref <#= context.OffsetExpression #>, out <#= resultVariable #> ) ) +<#+ + } + else + { + var variable = resultVariable + "AsyncReadResult"; +#> + var <#= variable #> = await this.ReadObjectCoreAsync( true, <#= context.BufferExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); + if ( <#= variable #>.Success ) + { + <#= context.OffsetExpression #> = <#= variable #>.Value.Offset; + <#= resultVariable #> = <#= variable #>.Value.Result; + } + else +<#+ + } +#> + { +<#+ + this.OnFail( "MessagePackObject", context.OffsetType, 6, isAsync, withOffset: true ); +#> + } +<#+ +} // WriteReadItemCore + + +private void WriteReadBinaryCoreCall( + string typeName, + ReadMethodContext context, + string resultVariable, + string lengthExpression, + int indentLevel, + bool isAsync +) +{ + this.PushIndent( indentLevel ); +#> +byte[] <#= resultVariable #>; +<#+ + if ( !isAsync ) + { +#> +if ( !this.ReadBinaryCore( <#= lengthExpression #>, ref <#= context.OffsetExpression #>, out <#= resultVariable #> ) ) +<#+ + } + else // !isAsync + { +#> +var asyncReadResult = await this.ReadBinaryCoreAsync( <#= lengthExpression #>, <#= context.OffsetExpression #>, cancellationToken ).ConfigureAwait( false ); +if ( asyncReadResult.Success ) +{ + <#= resultVariable #> = asyncReadResult.Value.Result; + <#= context.OffsetExpression #> = asyncReadResult.Value.Offset; +} +else +<#+ + } // if !isAsync +#> +{ +<#+ + this.OnFail( typeName, context.OffsetType, 1, isAsync, withOffset: true ); +#> +} +<#+ + this.PopIndent(); +} // WriteReadBinaryCoreCall + +private void WriteReadPrologue( + string typeName, + ReadMethodContext context, + Action prologue, + Action, bool> readBytes, // context, indentLevel, lengthExpression, onFail, isAsync + bool isAsync +) +{ + if ( isAsync ) + { +#> + <#= typeName #> result; +<#+ + } + + prologue( context ); + + readBytes( context, 3, "1", indentLevel => this.OnFail( typeName, context.OffsetType, indentLevel, isAsync, withOffset: false ), isAsync ); +#> + + var header = ReadValueResults.EncodedTypes[ <#= context.BufferExpression #>[ <#= context.BufferOffsetExpression #> ] ]; +<#+ +} // WriteReadPrologue + +private void WriteReadEpilogue( + ReadMethodContext context, + string collectionType, + Action epilogue, + bool isAsync +) +{ + epilogue( context, collectionType ); +#> + return <#= !isAsync ? "true" : "AsyncReadResult.Success( result )" #>; +<#+ +} // WriteReadEpilogue + + +private void OnFail( string typeName, string offsetType, int indentLevel, bool isAsync, bool withOffset ) +{ + this.PushIndent( indentLevel ); + + if ( !isAsync ) + { +#> +result = default( <#= typeName #> ); +return false; +<#+ + } + else + { +#> +return AsyncReadResult.Fail<<#= withOffset ? ( offsetType + "OffsetValue<" + typeName + ">" ) : typeName #>>(); +<#+ + } + + this.PopIndent(); +} // OnFail + +private static string Signature( string typeLabel, string typeName, string nameFormat, string precedingParameters, bool isAsync, bool isPseudoAsync ) +{ + return SignatureCore( typeLabel, typeName, nameFormat, precedingParameters, isAsync, isPseudoAsync, "AsyncReadResult<{0}>" ); +} + +private static string SignatureWithOffset( string typeLabel, string typeName, string offsetType, string nameFormat, string precedingParameters, bool isAsync, bool isPseudoAsync ) +{ + return SignatureCore( typeLabel, typeName, nameFormat, precedingParameters, isAsync, isPseudoAsync, "AsyncReadResult<" + offsetType + "OffsetValue<{0}>>" ); +} + +private static string SignatureCore( string typeLabel, string typeName, string nameFormat, string precedingParameters, bool isAsync, bool isPseudoAsync, string asyncResultTypeFormat ) +{ + var signature = new StringBuilder(); + + if ( isAsync ) + { + if( ! isPseudoAsync ) + { + signature.Append( "async " ); + } + + signature.Append( "Task<" ).AppendFormat( asyncResultTypeFormat, typeName ).Append( "> " ); + } + else + { + signature.Append( "bool " ); + } + + signature.AppendFormat( nameFormat, typeLabel ); + + if ( isAsync ) + { + signature.Append( "Async( " ).Append( precedingParameters ).Append( "CancellationToken cancellationToken )" ); + } + else + { + signature.Append( "( " ).Append( precedingParameters ).Append( "out " ).Append( typeName ).Append( " result )" ); + } + + return signature.ToString(); +} + +private sealed class ReadMethodContext +{ + private readonly bool _useOffsetForBuffer; + + public string BufferExpression { get; private set; } + + public string OffsetExpression { get; private set; } + + public string OffsetType { get; private set; } + + public string BufferOffsetExpression + { + get { return this._useOffsetForBuffer ? this.OffsetExpression : "0"; } + } + + public ReadMethodContext( string bufferExpression, string offsetExpression, string offsetType, bool useOffsetForBuffer ) + { + this.BufferExpression = bufferExpression; + this.OffsetExpression = offsetExpression; + this.OffsetType = offsetType; + this._useOffsetForBuffer = useOffsetForBuffer; + } +} + +private enum Nullability +{ + Reference, + Value, + Nullable +} + +private string ToPrimitive( Type type ) +{ + return + type.Name + .Replace( "Int64", "long ") + .Replace( "Int16", "short ") + .Replace( "Int32", "int ") + .Replace( "Single", "float ") + .Replace( "Boolean", "bool ") + .ToLowerInvariant(); +} +#> diff --git a/src/MsgPack/MessagePackUnpackerCommon.Skip.ttinclude b/src/MsgPack/MessagePackUnpackerCommon.Skip.ttinclude new file mode 100644 index 000000000..bea0e11d5 --- /dev/null +++ b/src/MsgPack/MessagePackUnpackerCommon.Skip.ttinclude @@ -0,0 +1,68 @@ +<#@ import namespace="System.Collections.Generic" #><#+ +// +// MessagePack for CLI +// +// Copyright (C) 2010-2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +private void WriteSkipOverrides( + string offsetExpression +) +{ + foreach ( var isAsync in new [] { false, true } ) + { + if ( isAsync ) + { +#> +#if FEATURE_TAP +<#+ + } +#> + protected sealed override <#= isAsync ? "async Task" : "long?" #> Skip<#= AsyncSuffix( isAsync ) #>Core(<#= Parameter( isAsync ) #>) + { + var startOffset = this.<#= offsetExpression #>; +<#+ + if ( !isAsync ) + { +#> + MessagePackObject notUsed; + if ( !this.ReadObject( /* isDeep */true, out notUsed ) ) +<#+ + } + else + { +#> + var asyncReadResult = await this.ReadObjectAsync( /* isDeep */true, cancellationToken ).ConfigureAwait( false ); + if ( !asyncReadResult.Success ) +<#+ + } +#> + { + return null; + } + + return this.<#= offsetExpression #> - startOffset; + } + +<#+ + if ( isAsync ) + { +#> +#endif // FEATURE_TAP +<#+ + } + } +} // WriteSkipOverrides +#> \ No newline at end of file diff --git a/src/MsgPack/MessagePackUnpackerCommon.ttinclude b/src/MsgPack/MessagePackUnpackerCommon.ttinclude new file mode 100644 index 000000000..dcba602ee --- /dev/null +++ b/src/MsgPack/MessagePackUnpackerCommon.ttinclude @@ -0,0 +1,286 @@ +<#@ include file="..\Core.ttinclude" #> +<#@ include file=".\MessagePackUnpackerCommon.Read.ttinclude" #> +<#@ include file=".\MessagePackUnpackerCommon.Skip.ttinclude" #> +<#@ import namespace="System.Collections.Generic" #><#+ +// +// MessagePack for CLI +// +// Copyright (C) 2010-2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +private void WriteCommon( + string offsetExpression, + ReadMethodContext context, + Action prologue, + Action epilogue, + Action, bool> readBytes, // context, indentLevel, lengthExpression, onFail, isAsync + bool isPseudoAsync +) +{ + this.WriteReadOverrides( context, prologue, epilogue, readBytes, isPseudoAsync ); + this.WriteSkipOverrides( offsetExpression ); +#> + public sealed override bool ReadObject( out MessagePackObject result ) + { + return this.ReadObject( /* isDeep*/true, out result ); + } + +#if FEATURE_TAP + + public sealed override Task> ReadObjectAsync( CancellationToken cancellationToken ) + { + return this.ReadObjectAsync( /* isDeep*/true, cancellationToken ); + } + +#endif // FEATURE_TAP + + protected sealed override bool ReadCore() + { + MessagePackObject value; + var success = this.ReadObject( /* isDeep */false, out value ); + if ( success ) + { + this._data = value; + return true; + } + else + { + return false; + } + } + +#if FEATURE_TAP + + protected sealed override async Task ReadAsyncCore( CancellationToken cancellationToken ) + { + var result = await this.ReadObjectAsync( /* isDeep */false, cancellationToken ).ConfigureAwait( false ); + if ( result.Success ) + { + this._data = result.Value; + return true; + } + else + { + return false; + } + } + +#endif // FEATURE_TAP + + private void ThrowUnassignedMessageTypeException( int header ) + { +#if DEBUG + Contract.Assert( header == 0xC1, "Unhandled header:" + header.ToString( "X2" ) ); +#endif // DEBUG + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + throw new UnassignedMessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Unknown header value 0x{0:X} at position {1:#,0}" + : "Unknown header value 0x{0:X} at offset {1:#,0}", + header, + offsetOrPosition + ) + ); + } + + private void CheckLength( uint length, ReadValueResult type ) + { + if ( length > Int32.MaxValue ) + { + this.ThrowTooLongLengthException( length, type ); + } + } + + private void ThrowTooLongLengthException( uint length, ReadValueResult type ) + { + string message; + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + + if ( ( type & ReadValueResult.ArrayTypeMask ) == ReadValueResult.ArrayTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at position {1:#,0}" + : "MessagePack for CLI cannot handle large array (0x{0:X} elements) which has more than Int32.MaxValue elements, at offset {1:#,0}"; + } + else if ( ( type & ReadValueResult.MapTypeMask ) == ReadValueResult.MapTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at position {1:#,0}" + : "MessagePack for CLI cannot handle large map (0x{0:X} entries) which has more than Int32.MaxValue entries, at offset {1:#,0}"; + } + else if ( ( type & ReadValueResult.ExtTypeMask ) == ReadValueResult.ExtTypeMask ) + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large ext type (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" + : "MessagePack for CLI cannot handle large ext type (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; + } + else + { + message = + isRealOffset + ? "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at position {1:#,0}" + : "MessagePack for CLI cannot handle large binary or string (0x{0:X} bytes) which has more than Int32.MaxValue bytes, at offset {1:#,0}"; + } + + throw new MessageNotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + message, + length, + offsetOrPosition + ) + ); + } + + private void ThrowTypeException( string type, ReadValueResult header ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + var byteHeader = header.ToByte(); + throw new MessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Cannot convert '{0}' header from type '{2}'(0x{1:X}) in position {3:#,0}." + : "Cannot convert '{0}' header from type '{2}'(0x{1:X}) in offset {3:#,0}.", + type, + byteHeader, + MessagePackCode.ToString( byteHeader ), + offsetOrPosition + ) + ); + } + + private void ThrowTypeException( Type type, ReadValueResult header ) + { + long offsetOrPosition; + var isRealOffset = this.GetPreviousPosition( out offsetOrPosition ); + var byteHeader = header.ToByte(); + throw new MessageTypeException( + String.Format( + CultureInfo.CurrentCulture, + isRealOffset + ? "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in position {3:#,0}." + : "Cannot convert '{0}' type value from type '{2}'(0x{1:X}) in offset {3:#,0}.", + type, + byteHeader, + MessagePackCode.ToString( byteHeader ), + offsetOrPosition + ) + ); + } +<#+ +} // WriteCommon + +private void WriteBeginAsyncRegion( bool isAsync ) +{ + if ( !isAsync ) + { + return; + } +#> +#if FEATURE_TAP + +<#+ +} // WriteBeginAsyncRegion + +private void WriteEndAsyncRegion( bool isAsync ) +{ + if ( !isAsync ) + { + return; + } +#> +#endif // FEATURE_TAP + +<#+ +} // WriteEndAsyncRegion + +private static readonly string[] scalarTypes = + new [] + { + "Byte", "SByte", + "Int16", "UInt16", + "Int32", "UInt32", + "Int64", "UInt64", + "Single", + "Double" + }; +private static readonly Dictionary primitiveNames = + new Dictionary + { + { "Byte", "byte" }, + { "SByte", "sbyte" }, + { "Int16", "short" }, + { "UInt16", "ushort" }, + { "Int32", "int" }, + { "UInt32", "uint" }, + { "Int64", "long" }, + { "UInt64", "ulong" }, + { "Single", "float" }, + { "Double", "double" } + }; +// type: return-type +private static readonly Dictionary lengthTypes = + new Dictionary + { + { "Byte", "int" }, + { "UInt16", "int" }, + { "UInt32", "long" } + }; + + +private static string Await( bool isAsync, string expression ) +{ + return ( isAsync ? "await ": String.Empty ) + expression + ( isAsync ? ".ConfigureAwait( false )" : String.Empty ); +} + +private static string AsyncSuffix( bool isAsync ) +{ + return isAsync ? "Async": String.Empty; +} + +private static string AsyncReturnValue( string type, bool isAsync ) +{ + return ( isAsync ? "async Task<" : String.Empty ) + type + ( isAsync ? ">" : String.Empty ); +} + +private static string Parameter( bool isAsync ) +{ + return isAsync ? " CancellationToken cancellationToken " : String.Empty; +} + +private static string LastParameter( bool isAsync ) +{ + return isAsync ? ", CancellationToken cancellationToken " : String.Empty; +} + +private static string LastArgument( bool isAsync ) +{ + return isAsync ? ", cancellationToken" : String.Empty; +} + +private static string Argument( bool isAsync ) +{ + return isAsync ? " cancellationToken " : String.Empty; +} +#> \ No newline at end of file diff --git a/src/MsgPack/MsgPack.csproj b/src/MsgPack/MsgPack.csproj index 5e3a56488..d503aedb1 100644 --- a/src/MsgPack/MsgPack.csproj +++ b/src/MsgPack/MsgPack.csproj @@ -1,633 +1,493 @@ - - + + - Debug - AnyCPU - 8.0.30703 - 2.0 {5BCEC32E-990E-4DE5-945F-BD27326A7418} Library - Properties - MsgPack MsgPack - v4.6.1 - 512 - - - - - true - full - false - bin\Debug\ - TRACE;DEBUG;FEATURE_TAP;FEATURE_ET - prompt - 4 - bin\Debug\MsgPack.XML + net46;net35;net45;netstandard1.1;netstandard1.3;netstandard2.0;MonoAndroid10;Xamarin.iOS10;netcoreapp3.1;net6.0 + True AllRules.ruleset - false - - - pdbonly - true - ..\..\bin\net461\ - TRACE;FEATURE_TAP - prompt - 4 - ..\..\bin\net461\MsgPack.XML - false - - - bin\Performance Test\ - TRACE;FEATURE_TAP;PERFORMANCE_TEST - bin\Release\MsgPack.XML - true - pdbonly - AnyCPU - prompt - true - true - true - 4 - false - - - true + $(SolutionDir)/msgpack.nuspec - - ..\MsgPack.snk - - - bin\Instrument\ - TRACE;FEATURE_TAP;PERFORMANCE_TEST - bin\Instrument\MsgPack.XML - false - pdbonly - AnyCPU - prompt - true - true - false - 4 - false - - - bin\CodeAnalysis\ - TRACE;FEATURE_TAP;CODE_ANALYSIS - - - true - pdbonly - AnyCPU - prompt - false - true - 4 - false - AllRules.ruleset - true + + + ..\..\bin\ - - bin\CoreProfile\ - TRACE;FEATURE_TAP;CORE_PROFILE - bin\CoreProfile\MsgPack.XML - true - pdbonly - AnyCPU - prompt - 4 - false + + bin\$(Configuration)\ - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Properties\CommonAssemblyInfo.cs - - - - - - Code - - - - - - - - - - - Code - - - - ItemsUnpacker.Unpacking.tt - True - True - - - True - True - ItemsUnpacker.Read.tt - - - - Code - - - - - - - - - - - - - - - - - + + True + True + ByteArrayPackerWriter.TypedWrite.tt + + + True + True + MessagePackByteArrayPacker.Pack.tt + + + True + True + MessagePackByteArrayUnpacker.Unpack.tt + + + True + True + MessagePackStreamPacker.Pack.tt + + + True + True + DefaultStreamUnpacker.Unpacking.tt + + + True + True + StreamPackerWriter.TypedWrite.tt + + + Unpacker.Unpacking.tt + True + True + + + True + True + MessagePackStreamUnpacker.Unpack.tt + + + True + True + MessagePackUnpacker.Read.tt + + True True Packer.Packing.tt - - + True True PackerUnpackerExtensions.tt - - - + True True MessagePackObject.tt - - - + True True Packer.Nullable.tt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + True True ArraySerializer.Primitives.tt - - - - - - - Code - - - - + True True SimdTypeSerializers.tt - - - - - - - - - - - + MessagePackRuntimeTypeAttributes.tt True True - + True True MessagePackKnownTypeAttributes.tt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + TeeTextWriter.tt + True + True + + + True + True + PackHelperParameters.tt + + + True + True + NullTextWriter.tt + + True True DefaultSerializers.tt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - FromExpression.ToMethod.tt - - + True True _UnpackHelpers.direct.tt - - - - - Code - - - - - - - - - - - + True True SerializerRepository.defaults.tt - - - - - - - - - - - - - - - - + True True - UnpackHelpers.direct.tt + UnpackHelperParameters.tt - + True True UnpackHelpers.facade.tt - - - - - - - Code - - + True True - Unpacking.Numerics.tt + UnpackHelpers.direct.tt - - Unpacking.Others.tt - Code + True True + Unpacker.Leaf.tt - - - Code + + True + True + ByteArrayUnpackerReader.TypedRead.tt - - - - - - - - - - Unpacker.Unpacking.tt + + True + True + UnpackerReader.TypedRead.tt + + True True + Unpacking.Numerics.tt + + + Unpacking.Others.tt + True + True - - ItemsUnpacker.Skipping.tt + + MessagePackUnpacker`1.Skipping.tt True True - + SubtreeUnpacker.Unpacking.tt True True - MsgPack.snk - + + True + True + MessagePackByteArrayUnpacker.Unpack.tt + + TextTemplatingFileGenerator - DefaultSerializers.cs + MessagePackByteArrayPacker.Pack.cs - - ArraySerializer.Primitives.cs + + TextTemplatingFileGenerator + MessagePackByteArrayUnpacker.Unpack.cs + + + TextTemplatingFileGenerator + MessagePackStreamPacker.Pack.cs + + TextTemplatingFileGenerator + MessagePackUnpacker.Read.cs - + TextTemplatingFileGenerator - FromExpression.ToMethod.cs + Packer.Leaf.cs - + + TextTemplatingFileGenerator + DefaultSerializers.cs + + + ArraySerializer.Primitives.cs + TextTemplatingFileGenerator + + TextTemplatingFileGenerator MessagePackRuntimeTypeAttributes.cs - + TextTemplatingFileGenerator MessagePackKnownTypeAttributes.cs - + TextTemplatingFileGenerator _UnpackHelpers.direct.cs - + TextTemplatingFileGenerator SerializerRepository.defaults.cs - + TextTemplatingFileGenerator UnpackHelpers.direct.cs - + + DefaultStreamUnpacker.Unpacking.cs + TextTemplatingFileGenerator + + + ByteArrayPackerWriter.TypedWrite.cs + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + StreamPackerWriter.TypedWrite.cs + + + TextTemplatingFileGenerator + Unpacker.Leaf.cs + + + MessagePackStreamUnpacker.Unpack.cs + TextTemplatingFileGenerator + + + ByteArrayUnpackerReader.TypedRead.cs + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + UnpackerReader.TypedRead.cs + + TextTemplatingFileGenerator Unpacking.Numerics.cs - + TextTemplatingFileGenerator Unpacking.Others.cs - + TextTemplatingFileGenerator MessagePackObject.cs - + TextTemplatingFileGenerator Packer.Nullable.cs - + TextTemplatingFileGenerator Unpacker.Unpacking.cs - + TextTemplatingFileGenerator - ItemsUnpacker.Skipping.cs + MessagePackUnpacker`1.Skipping.cs - + TextTemplatingFileGenerator SubtreeUnpacker.Unpacking.cs - - - - - - - - - TextTemplatingFileGenerator - ItemsUnpacker.Read.cs - - - TextTemplatingFileGenerator - ItemsUnpacker.Unpacking.cs - - + TextTemplatingFileGenerator Packer.Packing.cs - - + + TextTemplatingFileGenerator PackerUnpackerExtensions.cs - - + + + TextTemplatingFileGenerator + TeeTextWriter.cs + + + TextTemplatingFileGenerator + NullTextWriter.cs + + + TextTemplatingFileGenerator + PackHelperParameters.cs + + + TextTemplatingFileGenerator + UnpackHelperParameters.cs + + TextTemplatingFileGenerator UnpackHelpers.facade.cs - - + + TextTemplatingFileGenerator SimdTypeSerializers.cs - + + + - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(MSBuildExtensionsPath) + + diff --git a/src/MsgPack.Net35/NetFxCompatibilities.cs b/src/MsgPack/NetFxCompatibilities.cs similarity index 100% rename from src/MsgPack.Net35/NetFxCompatibilities.cs rename to src/MsgPack/NetFxCompatibilities.cs diff --git a/src/netstandard/NetStandardCompatibility.cs b/src/MsgPack/NetStandardCompatibility.cs similarity index 100% rename from src/netstandard/NetStandardCompatibility.cs rename to src/MsgPack/NetStandardCompatibility.cs diff --git a/src/MsgPack/Packer.Factory.cs b/src/MsgPack/Packer.Factory.cs new file mode 100644 index 000000000..d0b9a25e9 --- /dev/null +++ b/src/MsgPack/Packer.Factory.cs @@ -0,0 +1,224 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2017 FUJIWARA, Yusuke and contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; + +namespace MsgPack +{ + partial class Packer + { + #region -- Stream -- + + /// + /// Create standard Safe instance wrapping specified with . + /// + /// object. This stream will be closed when is called. + /// Safe . This will not be null. + /// is null. + /// + /// You can specify any derived class like FileStream, , + /// NetworkStream, UnmanagedMemoryStream, or so. + /// + public static Packer Create( Stream stream ) + { + return Create( stream, true ); + } + + /// + /// Create standard Safe instance wrapping specified with specified . + /// + /// object. This stream will be closed when is called. + /// A which specifies compatibility options. + /// Safe . This will not be null. + /// is null. + /// + /// You can specify any derived class like FileStream, , + /// NetworkStream, UnmanagedMemoryStream, or so. + /// + public static Packer Create( Stream stream, PackerCompatibilityOptions compatibilityOptions ) + { + return Create( stream, compatibilityOptions, true ); + } + + /// + /// Create standard Safe instance wrapping specified with . + /// + /// object. + /// + /// true to close when this instance is disposed; + /// false, otherwise. + /// + /// Safe . This will not be null. + /// is null. + /// + /// You can specify any derived class like FileStream, , + /// NetworkStream, UnmanagedMemoryStream, or so. + /// + public static Packer Create( Stream stream, bool ownsStream ) + { + return Create( stream, DefaultCompatibilityOptions, ownsStream ); + } + + /// + /// Create standard Safe instance wrapping specified with specified . + /// + /// object. + /// A which specifies compatibility options. + /// + /// true to close when this instance is disposed; + /// false, otherwise. + /// + /// Safe . This will not be null. + /// is null. + /// + /// You can specify any derived class like FileStream, , + /// NetworkStream, UnmanagedMemoryStream, or so. + /// + public static Packer Create( Stream stream, PackerCompatibilityOptions compatibilityOptions, bool ownsStream ) + { + return new MessagePackStreamPacker( stream, ownsStream ? PackerUnpackerStreamOptions.SingletonOwnsStream : PackerUnpackerStreamOptions.None, compatibilityOptions ); + } + + /// + /// Create standard Safe instance wrapping specified with specified . + /// + /// object. + /// A which specifies compatibility options. + /// which specifies stream handling options. + /// Safe . This will not be null. + /// is null. + /// + /// You can specify any derived class like FileStream, , + /// NetworkStream, UnmanagedMemoryStream, or so. + /// + public static Packer Create( Stream stream, PackerCompatibilityOptions compatibilityOptions, PackerUnpackerStreamOptions streamOptions ) + { + return new MessagePackStreamPacker( stream, streamOptions, compatibilityOptions ); + } + + #endregion -- Stream -- + + #region -- byte[] -- + + /// + /// Creates a new from specified byte array with allowing expansion. + /// + /// The source byte array. + /// instance. This value will not be null. + public static ByteArrayPacker Create( byte[] buffer ) + { + return Create( buffer, true, DefaultCompatibilityOptions ); + } + + /// + /// Creates a new from specified byte array list with allowing expansion. + /// + /// The source byte array. + /// The effective start offset of the . + /// instance. This value will not be null. + /// + /// is negative. + /// + /// The array length of is too small. + public static ByteArrayPacker Create( byte[] buffer, int startOffset ) + { + return Create( buffer, startOffset, true, DefaultCompatibilityOptions ); + } + + /// + /// Creates a new from specified byte array list with compatibility options. + /// + /// The source byte array. + /// + /// If true, new buffer is allocated in product of the original size and golden ratio. + /// Otherwise, the buffer will never be replaced. + /// + /// A which specifies compatibility options. + /// instance. This value will not be null. + public static ByteArrayPacker Create( byte[] buffer, bool allowsBufferExpansion, PackerCompatibilityOptions compatibilityOptions ) + { + return new MessagePackByteArrayPacker( buffer, 0, allowsBufferExpansion ? SingleArrayBufferAllocator.Default : FixedArrayBufferAllocator.Instance, compatibilityOptions ); + } + + /// + /// Creates a new from specified byte array with compatibility options. + /// + /// The source byte array. + /// The effective start offset of the . + /// + /// If true, new buffer is allocated in product of the original size and golden ratio. + /// Otherwise, the buffer will never be replaced. + /// + /// A which specifies compatibility options. + /// instance. This value will not be null. + /// + /// is negative. + /// + /// The array length of is too small. + public static ByteArrayPacker Create( byte[] buffer, int startOffset, bool allowsBufferExpansion, PackerCompatibilityOptions compatibilityOptions ) + { + return new MessagePackByteArrayPacker( buffer, startOffset, allowsBufferExpansion ? SingleArrayBufferAllocator.Default : FixedArrayBufferAllocator.Instance, compatibilityOptions ); + } + + /// + /// Creates a new from specified byte array with compatibility options and custom allocator. + /// + /// The source byte array. + /// + /// A delegate to allocate new byte array which has requested size at least. + /// The first argument is old buffer which contains written data and second argument is requested (required) size. + /// The delegate must return new byte array which has enough size for requested write and contains old buffer's content. + /// If the delegate returns null, the packer will consider it as allocation failure. + /// + /// A which specifies compatibility options. + /// instance. This value will not be null. + /// is null. + public static ByteArrayPacker Create( byte[] buffer, Func allocator, PackerCompatibilityOptions compatibilityOptions ) + { + return Create( buffer, 0, allocator, compatibilityOptions ); + } + + /// + /// Creates a new from specified byte array with compatibility options and custom allocator. + /// + /// The source byte array. + /// The effective start offset of the . + /// + /// A delegate to allocate new byte array which has requested size at least. + /// The first argument is old buffer which contains written data and second argument is requested (required) size. + /// The delegate must return new byte array which has enough size for requested write and contains old buffer's content. + /// If the delegate returns null, the packer will consider it as allocation failure. + /// + /// A which specifies compatibility options. + /// instance. This value will not be null. + /// is null. + /// + /// is negative. + /// + /// The array length of is too small. + public static ByteArrayPacker Create( byte[] buffer, int startOffset, Func allocator, PackerCompatibilityOptions compatibilityOptions ) + { + return new MessagePackByteArrayPacker( buffer, startOffset, new SingleArrayBufferAllocator( allocator ), compatibilityOptions ); + } + + #endregion -- byte[] -- + } +} diff --git a/src/MsgPack/Packer.Packing.cs b/src/MsgPack/Packer.Packing.cs index b3e75be12..f0d4a6247 100644 --- a/src/MsgPack/Packer.Packing.cs +++ b/src/MsgPack/Packer.Packing.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -24,11 +24,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; using System.Text; #if FEATURE_TAP @@ -56,11 +56,15 @@ public Packer Pack( Int16 value ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( Int16 value ) + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( Int16 value ) { if ( this.TryPackTinySignedInteger( value ) ) { @@ -123,10 +127,16 @@ public Task PackAsync( Int16 value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( Int16 value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackAsyncCore( Int16 value, CancellationToken cancellationToken ) { if ( await this.TryPackTinySignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -201,11 +211,16 @@ public Packer Pack( UInt16 value ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( UInt16 value ) + /// + /// Packs value to current stream. + /// + /// value. + [CLSCompliant( false )] + protected virtual void PackCore( UInt16 value ) { if ( this.TryPackTinyUnsignedInteger( value ) ) { @@ -271,10 +286,17 @@ public Task PackAsync( UInt16 value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( UInt16 value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + [CLSCompliant( false )] + protected virtual async Task PackAsyncCore( UInt16 value, CancellationToken cancellationToken ) { if ( await this.TryPackTinyUnsignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -350,11 +372,15 @@ public Packer Pack( Int32 value ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( Int32 value ) + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( Int32 value ) { if ( this.TryPackTinySignedInteger( value ) ) { @@ -424,10 +450,16 @@ public Task PackAsync( Int32 value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( Int32 value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackAsyncCore( Int32 value, CancellationToken cancellationToken ) { if ( await this.TryPackTinySignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -509,11 +541,16 @@ public Packer Pack( UInt32 value ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( UInt32 value ) + /// + /// Packs value to current stream. + /// + /// value. + [CLSCompliant( false )] + protected virtual void PackCore( UInt32 value ) { if ( this.TryPackTinyUnsignedInteger( value ) ) { @@ -586,10 +623,17 @@ public Task PackAsync( UInt32 value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( UInt32 value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + [CLSCompliant( false )] + protected virtual async Task PackAsyncCore( UInt32 value, CancellationToken cancellationToken ) { if ( await this.TryPackTinyUnsignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -672,11 +716,15 @@ public Packer Pack( Int64 value ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( Int64 value ) + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( Int64 value ) { if ( this.TryPackTinySignedInteger( value ) ) { @@ -751,10 +799,16 @@ public Task PackAsync( Int64 value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( Int64 value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackAsyncCore( Int64 value, CancellationToken cancellationToken ) { if ( await this.TryPackTinySignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -841,11 +895,16 @@ public Packer Pack( UInt64 value ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( UInt64 value ) + /// + /// Packs value to current stream. + /// + /// value. + [CLSCompliant( false )] + protected virtual void PackCore( UInt64 value ) { if ( this.TryPackTinyUnsignedInteger( value ) ) { @@ -923,10 +982,17 @@ public Task PackAsync( UInt64 value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( UInt64 value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + [CLSCompliant( false )] + protected virtual async Task PackAsyncCore( UInt64 value, CancellationToken cancellationToken ) { if ( await this.TryPackTinyUnsignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -1012,17 +1078,22 @@ protected async Task TryPackUInt64Async( UInt64 value, CancellationToken c public Packer Pack( float value ) { this.VerifyNotDisposed(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( float value ) + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( float value ) { this.WriteByte( MessagePackCode.Real32 ); var bits = new Float32Bits( value ); + // Float32Bits usage is effectively pointer dereference operation rather than shifting operators, so we must consider endianness here. if ( BitConverter.IsLittleEndian ) { this.WriteByte( bits.Byte3 ); @@ -1060,16 +1131,23 @@ public Task PackAsync( float value ) public Task PackAsync( float value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( float value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackAsyncCore( float value, CancellationToken cancellationToken ) { await this.WriteByteAsync( MessagePackCode.Real32, cancellationToken ).ConfigureAwait( false ); var bits = new Float32Bits( value ); + // Float32Bits usage is effectively pointer dereference operation rather than shifting operators, so we must consider endianness here. if ( BitConverter.IsLittleEndian ) { await this.WriteByteAsync( bits.Byte3, cancellationToken ).ConfigureAwait( false ); @@ -1100,12 +1178,16 @@ private async Task PrivatePackAsyncCore( float value, CancellationToken cancella public Packer Pack( double value ) { this.VerifyNotDisposed(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } - private void PrivatePackCore( double value ) + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( double value ) { this.WriteByte( MessagePackCode.Real64 ); unchecked @@ -1143,11 +1225,17 @@ public Task PackAsync( double value ) public Task PackAsync( double value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } - private async Task PrivatePackAsyncCore( double value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackAsyncCore( double value, CancellationToken cancellationToken ) { await this.WriteByteAsync( MessagePackCode.Real64, cancellationToken ).ConfigureAwait( false ); unchecked @@ -1177,16 +1265,6 @@ private async Task PrivatePackAsyncCore( double value, CancellationToken cancell /// This instance. /// This instance has been disposed. public Packer PackArrayHeader( int count ) - { - this.PackArrayHeaderCore( count ); - return this; - } - - /// - /// Bookkeep array length or list items count to be packed on current stream. - /// - /// Array length or list items count. - protected void PackArrayHeaderCore( int count ) { if ( count < 0 ) { @@ -1196,10 +1274,15 @@ protected void PackArrayHeaderCore( int count ) Contract.EndContractBlock(); this.VerifyNotDisposed(); - this.PrivatePackArrayHeaderCore( count ); + this.PackArrayHeaderCore( count ); + return this; } - private void PrivatePackArrayHeaderCore( int count ) + /// + /// Bookkeep array length or list items count to be packed on current stream. + /// + /// Array length or list items count. + protected virtual void PackArrayHeaderCore( int count ) { #if !UNITY Contract.Assert( 0 <= count, "0 <= count" ); @@ -1230,6 +1313,7 @@ private void PrivatePackArrayHeaderCore( int count ) } } + #if FEATURE_TAP /// @@ -1240,6 +1324,14 @@ private void PrivatePackArrayHeaderCore( int count ) /// This instance has been disposed. public Task PackArrayHeaderAsync( int count ) { + if ( count < 0 ) + { + ThrowCannotBeNegativeException( "count" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + return this.PackArrayHeaderAsyncCore( count ); } @@ -1261,17 +1353,6 @@ protected Task PackArrayHeaderAsyncCore( int count ) /// A that represents the asynchronous operation. /// This instance has been disposed. public Task PackArrayHeaderAsync( int count, CancellationToken cancellationToken ) - { - return this.PackArrayHeaderAsyncCore( count, cancellationToken ); - } - - /// - /// Bookkeep array length or list items count to be packed on current stream asynchronously. - /// - /// Array length or list items count. - /// The token to monitor for cancellation requests. The default value is . - /// A that represents the asynchronous operation. - protected Task PackArrayHeaderAsyncCore( int count, CancellationToken cancellationToken ) { if ( count < 0 ) { @@ -1281,10 +1362,16 @@ protected Task PackArrayHeaderAsyncCore( int count, CancellationToken cancellati Contract.EndContractBlock(); this.VerifyNotDisposed(); - return this.PrivatePackArrayHeaderAsyncCore( count, cancellationToken ); + return this.PackArrayHeaderAsyncCore( count, cancellationToken ); } - private async Task PrivatePackArrayHeaderAsyncCore( int count, CancellationToken cancellationToken ) + /// + /// Bookkeep array length or list items count to be packed on current stream asynchronously. + /// + /// Array length or list items count. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackArrayHeaderAsyncCore( int count, CancellationToken cancellationToken ) { #if !UNITY Contract.Assert( 0 <= count, "0 <= count" ); @@ -1324,16 +1411,6 @@ private async Task PrivatePackArrayHeaderAsyncCore( int count, CancellationToken /// This instance. /// This instance has been disposed. public Packer PackMapHeader( int count ) - { - this.PackMapHeaderCore( count ); - return this; - } - - /// - /// Bookkeep dictionary (map) items count to be packed on current stream. - /// - /// Dictionary (map) items count. - protected void PackMapHeaderCore( int count ) { if ( count < 0 ) { @@ -1343,10 +1420,15 @@ protected void PackMapHeaderCore( int count ) Contract.EndContractBlock(); this.VerifyNotDisposed(); - this.PrivatePackMapHeaderCore( count ); + this.PackMapHeaderCore( count ); + return this; } - private void PrivatePackMapHeaderCore( int count ) + /// + /// Bookkeep dictionary (map) items count to be packed on current stream. + /// + /// Dictionary (map) items count. + protected virtual void PackMapHeaderCore( int count ) { #if !UNITY Contract.Assert( 0 <= count, "0 <= count" ); @@ -1377,6 +1459,7 @@ private void PrivatePackMapHeaderCore( int count ) } } + #if FEATURE_TAP /// @@ -1387,6 +1470,14 @@ private void PrivatePackMapHeaderCore( int count ) /// This instance has been disposed. public Task PackMapHeaderAsync( int count ) { + if ( count < 0 ) + { + ThrowCannotBeNegativeException( "count" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + return this.PackMapHeaderAsyncCore( count ); } @@ -1408,17 +1499,6 @@ protected Task PackMapHeaderAsyncCore( int count ) /// A that represents the asynchronous operation. /// This instance has been disposed. public Task PackMapHeaderAsync( int count, CancellationToken cancellationToken ) - { - return this.PackMapHeaderAsyncCore( count, cancellationToken ); - } - - /// - /// Bookkeep dictionary (map) items count to be packed on current stream asynchronously. - /// - /// Dictionary (map) items count. - /// The token to monitor for cancellation requests. The default value is . - /// A that represents the asynchronous operation. - protected Task PackMapHeaderAsyncCore( int count, CancellationToken cancellationToken ) { if ( count < 0 ) { @@ -1428,10 +1508,16 @@ protected Task PackMapHeaderAsyncCore( int count, CancellationToken cancellation Contract.EndContractBlock(); this.VerifyNotDisposed(); - return this.PrivatePackMapHeaderAsyncCore( count, cancellationToken ); + return this.PackMapHeaderAsyncCore( count, cancellationToken ); } - private async Task PrivatePackMapHeaderAsyncCore( int count, CancellationToken cancellationToken ) + /// + /// Bookkeep dictionary (map) items count to be packed on current stream asynchronously. + /// + /// Dictionary (map) items count. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackMapHeaderAsyncCore( int count, CancellationToken cancellationToken ) { #if !UNITY Contract.Assert( 0 <= count, "0 <= count" ); @@ -1476,7 +1562,14 @@ private async Task PrivatePackMapHeaderAsyncCore( int count, CancellationToken c [Obsolete( "Use PackStringHeader(Int32) or Use PackBinaryHeader(Int32) instead." )] public Packer PackRawHeader( int length ) { - this.PackRawHeaderCore( length ); + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + this.PackStringHeaderCore( length ); return this; } @@ -1494,7 +1587,14 @@ public Packer PackRawHeader( int length ) [Obsolete( "Use PackStringHeader(Int32) or Use PackBinaryHeader(Int32) instead." )] public Task PackRawHeaderAsync( int length ) { - return this.PackRawHeaderAsyncCore( length ); + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + return this.PackStringHeaderAsyncCore( length ); } /// @@ -1510,7 +1610,14 @@ public Task PackRawHeaderAsync( int length ) [Obsolete( "Use PackStringHeader(Int32) or Use PackBinaryHeader(Int32) instead." )] public Task PackRawHeaderAsync( int length, CancellationToken cancellationToken ) { - return this.PackRawHeaderAsyncCore( length, cancellationToken ); + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + return this.PackStringHeaderAsyncCore( length, cancellationToken ); } #endif // FEATURE_TAP @@ -1523,6 +1630,13 @@ public Task PackRawHeaderAsync( int length, CancellationToken cancellationToken /// This instance has been disposed. public Packer PackStringHeader( int length ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); this.PackStringHeaderCore( length ); return this; } @@ -1537,6 +1651,13 @@ public Packer PackStringHeader( int length ) /// This instance has been disposed. public Task PackStringHeaderAsync( int length ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); return this.PackStringHeaderAsyncCore( length ); } @@ -1549,6 +1670,13 @@ public Task PackStringHeaderAsync( int length ) /// This instance has been disposed. public Task PackStringHeaderAsync( int length, CancellationToken cancellationToken ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); return this.PackStringHeaderAsyncCore( length, cancellationToken ); } @@ -1562,6 +1690,19 @@ public Task PackStringHeaderAsync( int length, CancellationToken cancellationTok /// This instance has been disposed. public Packer PackBinaryHeader( int length ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) + { + // In compat mode, use raw(str) header. + this.PackStringHeaderCore( length ); + return this; + } this.PackBinaryHeaderCore( length ); return this; } @@ -1576,6 +1717,18 @@ public Packer PackBinaryHeader( int length ) /// This instance has been disposed. public Task PackBinaryHeaderAsync( int length ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) + { + // In compat mode, use raw(str) header. + return this.PackStringHeaderAsyncCore( length ); + } return this.PackBinaryHeaderAsyncCore( length ); } @@ -1588,6 +1741,18 @@ public Task PackBinaryHeaderAsync( int length ) /// This instance has been disposed. public Task PackBinaryHeaderAsync( int length, CancellationToken cancellationToken ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) + { + // In compat mode, use raw(str) header. + return this.PackStringHeaderAsyncCore( length, cancellationToken ); + } return this.PackBinaryHeaderAsyncCore( length, cancellationToken ); } @@ -1643,147 +1808,108 @@ protected Task PackRawHeaderAsyncCore( int length, CancellationToken cancellatio /// Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string. /// /// A length of encoded byte array. - protected void PackStringHeaderCore( int length ) + protected virtual void PackStringHeaderCore( int length ) { - if ( length < 0 ) + if ( length < 32 ) { - ThrowCannotBeNegativeException( "length" ); + this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ) ); + return; } - Contract.EndContractBlock(); - this.VerifyNotDisposed(); - - this.PrivatePackRawHeaderCore( length, true ); - } - -#if FEATURE_TAP - - /// - /// Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string asynchronously. - /// - /// A length of encoded byte array. - /// A that represents the asynchronous operation. - protected Task PackStringHeaderAsyncCore( int length ) - { - return this.PackStringHeaderAsyncCore( length, CancellationToken.None ); - } - - /// - /// Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string asynchronously. - /// - /// A length of encoded byte array. - /// The token to monitor for cancellation requests. The default value is . - /// A that represents the asynchronous operation. - protected Task PackStringHeaderAsyncCore( int length, CancellationToken cancellationToken ) - { - if ( length < 0 ) - { - ThrowCannotBeNegativeException( "length" ); - } - - Contract.EndContractBlock(); - this.VerifyNotDisposed(); - - return this.PrivatePackRawHeaderAsyncCore( length, true, cancellationToken ); - } - -#endif // FEATURE_TAP - - /// - /// Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string. - /// - /// A length of byte array. - protected void PackBinaryHeaderCore( int length ) - { - if ( length < 0 ) - { - ThrowCannotBeNegativeException( "length" ); - } - - Contract.EndContractBlock(); - this.VerifyNotDisposed(); - - this.PrivatePackRawHeaderCore( length, false ); + if ( length <= Byte.MaxValue && ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.WriteByte( MessagePackCode.Str8 ); + unchecked + { + this.WriteByte( ( byte )( length & 0xFF ) ); + } + } + else if ( length <= UInt16.MaxValue ) + { + this.WriteByte( MessagePackCode.Str16 ); + unchecked + { + this.WriteByte( ( byte )( ( length >> 8 ) & 0xFF ) ); + this.WriteByte( ( byte )( length & 0xFF ) ); + } + } + else + { + this.WriteByte( MessagePackCode.Str32 ); + unchecked + { + this.WriteByte( ( byte )( ( length >> 24 ) & 0xFF ) ); + this.WriteByte( ( byte )( ( length >> 16 ) & 0xFF ) ); + this.WriteByte( ( byte )( ( length >> 8 ) & 0xFF ) ); + this.WriteByte( ( byte )( length & 0xFF ) ); + } + } } #if FEATURE_TAP /// - /// Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string asynchronously. + /// Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string asynchronously. /// - /// A length of byte array. + /// A length of encoded byte array. /// A that represents the asynchronous operation. - protected Task PackBinaryHeaderAsyncCore( int length ) + protected Task PackStringHeaderAsyncCore( int length ) { - return this.PackBinaryHeaderAsyncCore( length, CancellationToken.None ); + return this.PackStringHeaderAsyncCore( length, CancellationToken.None ); } /// - /// Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string asynchronously. + /// Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string asynchronously. /// - /// A length of byte array. + /// A length of encoded byte array. /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. - protected Task PackBinaryHeaderAsyncCore( int length, CancellationToken cancellationToken ) + protected virtual async Task PackStringHeaderAsyncCore( int length, CancellationToken cancellationToken ) { - if ( length < 0 ) + if ( length < 32 ) { - ThrowCannotBeNegativeException( "length" ); + await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ), cancellationToken ).ConfigureAwait( false ); + return; } - Contract.EndContractBlock(); - this.VerifyNotDisposed(); - - return this.PrivatePackRawHeaderAsyncCore( length, false, cancellationToken ); - } - -#endif // FEATURE_TAP - - private void PrivatePackRawHeaderCore( int length, bool isString ) - { - Contract.Assert( 0 <= length, "0 <= length" ); - - if ( isString || ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) - { - if ( length < 32 ) - { - this.WriteByte( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ) ); - return; - } - if ( length <= Byte.MaxValue && ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) { - this.WriteByte( MessagePackCode.Str8 ); + await this.WriteByteAsync( MessagePackCode.Str8, cancellationToken ).ConfigureAwait( false ); unchecked { - this.WriteByte( ( byte )( length & 0xFF ) ); + await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); } } else if ( length <= UInt16.MaxValue ) { - this.WriteByte( MessagePackCode.Str16 ); + await this.WriteByteAsync( MessagePackCode.Str16, cancellationToken ).ConfigureAwait( false ); unchecked { - this.WriteByte( ( byte )( ( length >> 8 ) & 0xFF ) ); - this.WriteByte( ( byte )( length & 0xFF ) ); + await this.WriteByteAsync( ( byte )( ( length >> 8 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); + await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); } } else { - this.WriteByte( MessagePackCode.Str32 ); + await this.WriteByteAsync( MessagePackCode.Str32, cancellationToken ).ConfigureAwait( false ); unchecked { - this.WriteByte( ( byte )( ( length >> 24 ) & 0xFF ) ); - this.WriteByte( ( byte )( ( length >> 16 ) & 0xFF ) ); - this.WriteByte( ( byte )( ( length >> 8 ) & 0xFF ) ); - this.WriteByte( ( byte )( length & 0xFF ) ); + await this.WriteByteAsync( ( byte )( ( length >> 24 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); + await this.WriteByteAsync( ( byte )( ( length >> 16 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); + await this.WriteByteAsync( ( byte )( ( length >> 8 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); + await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); } } - } - else - { - // !isString && compat options is not set. + } +#endif // FEATURE_TAP + + /// + /// Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string. + /// + /// A length of byte array. + protected virtual void PackBinaryHeaderCore( int length ) + { if ( length <= Byte.MaxValue ) { this.WriteByte( MessagePackCode.Bin8 ); @@ -1812,56 +1938,28 @@ private void PrivatePackRawHeaderCore( int length, bool isString ) this.WriteByte( ( byte )( length & 0xFF ) ); } } - } } #if FEATURE_TAP - private async Task PrivatePackRawHeaderAsyncCore( int length, bool isString, CancellationToken cancellationToken ) + /// + /// Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string asynchronously. + /// + /// A length of byte array. + /// A that represents the asynchronous operation. + protected Task PackBinaryHeaderAsyncCore( int length ) { - Contract.Assert( 0 <= length, "0 <= length" ); - - if ( isString || ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) - { - if ( length < 32 ) - { - await this.WriteByteAsync( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) ), cancellationToken ).ConfigureAwait( false ); - return; - } - - if ( length <= Byte.MaxValue && ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) - { - await this.WriteByteAsync( MessagePackCode.Str8, cancellationToken ).ConfigureAwait( false ); - unchecked - { - await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); - } - } - else if ( length <= UInt16.MaxValue ) - { - await this.WriteByteAsync( MessagePackCode.Str16, cancellationToken ).ConfigureAwait( false ); - unchecked - { - await this.WriteByteAsync( ( byte )( ( length >> 8 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); - await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); - } - } - else - { - await this.WriteByteAsync( MessagePackCode.Str32, cancellationToken ).ConfigureAwait( false ); - unchecked - { - await this.WriteByteAsync( ( byte )( ( length >> 24 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); - await this.WriteByteAsync( ( byte )( ( length >> 16 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); - await this.WriteByteAsync( ( byte )( ( length >> 8 ) & 0xFF ), cancellationToken ).ConfigureAwait( false ); - await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); - } - } - } - else - { - // !isString && compat options is not set. + return this.PackBinaryHeaderAsyncCore( length, CancellationToken.None ); + } + /// + /// Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string asynchronously. + /// + /// A length of byte array. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackBinaryHeaderAsyncCore( int length, CancellationToken cancellationToken ) + { if ( length <= Byte.MaxValue ) { await this.WriteByteAsync( MessagePackCode.Bin8, cancellationToken ).ConfigureAwait( false ); @@ -1890,7 +1988,6 @@ private async Task PrivatePackRawHeaderAsyncCore( int length, bool isString, Can await this.WriteByteAsync( ( byte )( length & 0xFF ), cancellationToken ).ConfigureAwait( false ); } } - } } #endif // FEATURE_TAP @@ -1913,16 +2010,21 @@ public Packer PackRaw( IEnumerable value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asCollection = value as ICollection; - if ( asCollection == null ) + if ( value == null ) + { + this.PrivatePackNullCore(); + return this; + } + + var asArray = value as byte[]; + if ( asArray != null ) { - this.PrivatePackRaw( value ); + this.PackRawCore( asArray ); } else { - this.PrivatePackRaw( asCollection ); + this.PackRawCore( value.ToArray() ); } - return this; } @@ -1940,16 +2042,21 @@ public Packer PackRaw( IList value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asByteArray = value as byte[]; - if ( asByteArray == null ) + if ( value == null ) { - this.PrivatePackRaw( value ); + this.PrivatePackNullCore(); + return this; + } + + var asArray = value as byte[]; + if ( asArray != null ) + { + this.PackRawCore( asArray ); } else { - this.PrivatePackRaw( asByteArray ); + this.PackRawCore( value.ToArray() ); } - return this; } @@ -1967,63 +2074,25 @@ public Packer PackRaw( byte[] value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackRaw( value ); - return this; - } - - private void PrivatePackRaw( ICollection value ) - { - if ( value == null ) - { - this.PrivatePackNullCore(); - return; - } - - this.PrivatePackRawHeaderCore( value.Count, /*isString:*/ true ); - this.WriteBytes( value ); - } - - private void PrivatePackRaw( byte[] value ) - { - if ( value == null ) - { - this.PrivatePackNullCore(); - return; - } - - this.PrivatePackRawCore( value, false ); - } - - private void PrivatePackRaw( IEnumerable value ) - { if ( value == null ) { this.PrivatePackNullCore(); - return; + return this; } - this.PrivatePackRawCore( value ); + this.PackRawCore( value ); + return this; } - private void PrivatePackRawCore( byte[] value, bool isImmutable ) - { - this.PrivatePackRawHeaderCore( value.Length, /*isString:*/ true ); - this.WriteBytes( value, isImmutable ); - } - private void PrivatePackRawCore( IEnumerable value ) + /// + /// Packs specified byte array(it may or may not be string to current stream. + /// + /// A byte array. + protected virtual void PackRawCore( byte[] value ) { - if ( !this.CanSeek ) - { - // buffered - this.PrivatePackRawCore( value.ToArray(), true ); - } - else - { - // Header - this.WriteByte( MessagePackCode.Raw32 ); - this.StreamWrite( value, ( items, _ ) => this.PrivatePackRawBodyCore( items ), null ); - } + this.PackStringHeaderCore( value.Length ); + this.WriteBytes( value, false ); } #if FEATURE_TAP @@ -2057,16 +2126,20 @@ public Task PackRawAsync( IEnumerable value, CancellationToken cancellatio this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asCollection = value as ICollection; - if ( asCollection == null ) + if ( value == null ) { - return this.PrivatePackRawAsync( value, cancellationToken ); + return this.PrivatePackNullAsyncCore( cancellationToken ); + } + + var asArray = value as byte[]; + if ( asArray != null ) + { + return this.PackRawAsyncCore( asArray, cancellationToken ); } else { - return this.PrivatePackRawAsync( asCollection, cancellationToken ); + return this.PackRawAsyncCore( value.ToArray(), cancellationToken ); } - } /// @@ -2098,16 +2171,20 @@ public Task PackRawAsync( IList value, CancellationToken cancellationToken this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asByteArray = value as byte[]; - if ( asByteArray == null ) + if ( value == null ) + { + return this.PrivatePackNullAsyncCore( cancellationToken ); + } + + var asArray = value as byte[]; + if ( asArray != null ) { - return this.PrivatePackRawAsync( value, cancellationToken ); + return this.PackRawAsyncCore( asArray, cancellationToken ); } else { - return this.PrivatePackRawAsync( asByteArray, cancellationToken ); + return this.PackRawAsyncCore( value.ToArray(), cancellationToken ); } - } /// @@ -2139,62 +2216,25 @@ public Task PackRawAsync( byte[] value, CancellationToken cancellationToken ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackRawAsync( value, cancellationToken ); - } - - private async Task PrivatePackRawAsync( ICollection value, CancellationToken cancellationToken ) - { if ( value == null ) { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; + return this.PrivatePackNullAsyncCore( cancellationToken ); } - await this.PrivatePackRawHeaderAsyncCore( value.Count, /*isString:*/ true, cancellationToken ).ConfigureAwait( false ); - await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); + return this.PackRawAsyncCore( value, cancellationToken ); } - private async Task PrivatePackRawAsync( byte[] value, CancellationToken cancellationToken ) - { - if ( value == null ) - { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; - } - - await this.PrivatePackRawAsyncCore( value, false, cancellationToken ).ConfigureAwait( false ); - } - private async Task PrivatePackRawAsync( IEnumerable value, CancellationToken cancellationToken ) - { - if ( value == null ) - { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; - } - - await this.PrivatePackRawAsyncCore( value, cancellationToken ).ConfigureAwait( false ); - } - - private async Task PrivatePackRawAsyncCore( byte[] value, bool isImmutable, CancellationToken cancellationToken ) - { - await this.PrivatePackRawHeaderAsyncCore( value.Length, /*isString:*/ true, cancellationToken ).ConfigureAwait( false ); - await this.WriteBytesAsync( value, isImmutable, cancellationToken ).ConfigureAwait( false ); - } - - private async Task PrivatePackRawAsyncCore( IEnumerable value, CancellationToken cancellationToken ) + /// + /// Packs specified byte array(it may or may not be string to current stream asynchronously. + /// + /// A byte array. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackRawAsyncCore( byte[] value, CancellationToken cancellationToken ) { - if ( !this.CanSeek ) - { - // buffered - await this.PrivatePackRawAsyncCore( value.ToArray(), true, cancellationToken ).ConfigureAwait( false ); - } - else - { - // Header - await this.WriteByteAsync( MessagePackCode.Raw32, cancellationToken ).ConfigureAwait( false ); - await this.StreamWriteAsync( value, ( items, _, cts ) => this.PrivatePackRawBodyAsyncCore( items, cts ), null, cancellationToken ).ConfigureAwait( false ); - } + await this.PackStringHeaderAsyncCore( value.Length, cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, false, cancellationToken ).ConfigureAwait( false ); } #endif // FEATURE_TAP @@ -2217,16 +2257,37 @@ public Packer PackBinary( IEnumerable value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asCollection = value as ICollection; - if ( asCollection == null ) + if ( value == null ) { - this.PrivatePackBinary( value ); + this.PrivatePackNullCore(); + return this; + } + + var asArray = value as byte[]; + if ( asArray != null ) + { + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.PackBinaryCore( asArray ); + } + else + { + this.PackRawCore( asArray ); + } + } else { - this.PrivatePackBinary( asCollection ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.PackBinaryCore( value.ToArray() ); + } + else + { + this.PackRawCore( value.ToArray() ); + } + } - return this; } @@ -2244,16 +2305,37 @@ public Packer PackBinary( IList value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asByteArray = value as byte[]; - if ( asByteArray == null ) + if ( value == null ) + { + this.PrivatePackNullCore(); + return this; + } + + var asArray = value as byte[]; + if ( asArray != null ) { - this.PrivatePackBinary( value ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.PackBinaryCore( asArray ); + } + else + { + this.PackRawCore( asArray ); + } + } else { - this.PrivatePackBinary( asByteArray ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + this.PackBinaryCore( value.ToArray() ); + } + else + { + this.PackRawCore( value.ToArray() ); + } + } - return this; } @@ -2271,72 +2353,33 @@ public Packer PackBinary( byte[] value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackBinary( value ); - return this; - } - - private void PrivatePackBinary( ICollection value ) - { if ( value == null ) { this.PrivatePackNullCore(); - return; + return this; } - this.PrivatePackRawHeaderCore( value.Count, /*isString:*/ false ); - this.WriteBytes( value ); - } - - private void PrivatePackBinary( byte[] value ) - { - if ( value == null ) + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) { - this.PrivatePackNullCore(); - return; + this.PackBinaryCore( value ); } - - this.PrivatePackBinaryCore( value, false ); - } - - private void PrivatePackBinary( IEnumerable value ) - { - if ( value == null ) + else { - this.PrivatePackNullCore(); - return; + this.PackRawCore( value ); } - this.PrivatePackBinaryCore( value ); + return this; } - private void PrivatePackBinaryCore( byte[] value, bool isImmutable ) - { - this.PrivatePackRawHeaderCore( value.Length, /*isString:*/ false ); - this.WriteBytes( value, isImmutable ); - } - private void PrivatePackBinaryCore( IEnumerable value ) + /// + /// Packs specified byte array(it should not be string to current stream. + /// + /// A byte array. + protected virtual void PackBinaryCore( byte[] value ) { - if ( !this.CanSeek ) - { - // buffered - this.PrivatePackBinaryCore( value.ToArray(), true ); - } - else - { - // Header - // Use biggest data size because actual binary length is not known. - if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) - { - this.WriteByte( MessagePackCode.Raw32 ); - } - else - { - this.WriteByte( MessagePackCode.Bin32 ); - } - - this.StreamWrite( value, ( items, _ ) => this.PrivatePackRawBodyCore( items ), null ); - } + this.PackBinaryHeaderCore( value.Length ); + this.WriteBytes( value, false ); } #if FEATURE_TAP @@ -2370,16 +2413,36 @@ public Task PackBinaryAsync( IEnumerable value, CancellationToken cancella this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asCollection = value as ICollection; - if ( asCollection == null ) + if ( value == null ) + { + return this.PrivatePackNullAsyncCore( cancellationToken ); + } + + var asArray = value as byte[]; + if ( asArray != null ) { - return this.PrivatePackBinaryAsync( value, cancellationToken ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + return this.PackBinaryAsyncCore( asArray, cancellationToken ); + } + else + { + return this.PackRawAsyncCore( asArray, cancellationToken ); + } + } else { - return this.PrivatePackBinaryAsync( asCollection, cancellationToken ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + return this.PackBinaryAsyncCore( value.ToArray(), cancellationToken ); + } + else + { + return this.PackRawAsyncCore( value.ToArray(), cancellationToken ); + } + } - } /// @@ -2411,16 +2474,36 @@ public Task PackBinaryAsync( IList value, CancellationToken cancellationTo this.VerifyNotDisposed(); Contract.EndContractBlock(); - var asByteArray = value as byte[]; - if ( asByteArray == null ) + if ( value == null ) + { + return this.PrivatePackNullAsyncCore( cancellationToken ); + } + + var asArray = value as byte[]; + if ( asArray != null ) { - return this.PrivatePackBinaryAsync( value, cancellationToken ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + return this.PackBinaryAsyncCore( asArray, cancellationToken ); + } + else + { + return this.PackRawAsyncCore( asArray, cancellationToken ); + } + } else { - return this.PrivatePackBinaryAsync( asByteArray, cancellationToken ); + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + return this.PackBinaryAsyncCore( value.ToArray(), cancellationToken ); + } + else + { + return this.PackRawAsyncCore( value.ToArray(), cancellationToken ); + } + } - } /// @@ -2452,71 +2535,33 @@ public Task PackBinaryAsync( byte[] value, CancellationToken cancellationToken ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackBinaryAsync( value, cancellationToken ); - } - - private async Task PrivatePackBinaryAsync( ICollection value, CancellationToken cancellationToken ) - { if ( value == null ) { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; + return this.PrivatePackNullAsyncCore( cancellationToken ); } - await this.PrivatePackRawHeaderAsyncCore( value.Count, /*isString:*/ false, cancellationToken ).ConfigureAwait( false ); - await this.WriteBytesAsync( value, cancellationToken ).ConfigureAwait( false ); - } - - private async Task PrivatePackBinaryAsync( byte[] value, CancellationToken cancellationToken ) - { - if ( value == null ) + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; + return this.PackBinaryAsyncCore( value, cancellationToken ); } - - await this.PrivatePackBinaryAsyncCore( value, false, cancellationToken ).ConfigureAwait( false ); - } - - private async Task PrivatePackBinaryAsync( IEnumerable value, CancellationToken cancellationToken ) - { - if ( value == null ) + else { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; + return this.PackRawAsyncCore( value, cancellationToken ); } - await this.PrivatePackBinaryAsyncCore( value, cancellationToken ).ConfigureAwait( false ); } - private async Task PrivatePackBinaryAsyncCore( byte[] value, bool isImmutable, CancellationToken cancellationToken ) - { - await this.PrivatePackRawHeaderAsyncCore( value.Length, /*isString:*/ false, cancellationToken ).ConfigureAwait( false ); - await this.WriteBytesAsync( value, isImmutable, cancellationToken ).ConfigureAwait( false ); - } - private async Task PrivatePackBinaryAsyncCore( IEnumerable value, CancellationToken cancellationToken ) + /// + /// Packs specified byte array(it should not be string to current stream asynchronously. + /// + /// A byte array. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackBinaryAsyncCore( byte[] value, CancellationToken cancellationToken ) { - if ( !this.CanSeek ) - { - // buffered - await this.PrivatePackBinaryAsyncCore( value.ToArray(), true, cancellationToken ).ConfigureAwait( false ); - } - else - { - // Header - // Use biggest data size because actual binary length is not known. - if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) - { - await this.WriteByteAsync( MessagePackCode.Raw32, cancellationToken ).ConfigureAwait( false ); - } - else - { - await this.WriteByteAsync( MessagePackCode.Bin32, cancellationToken ).ConfigureAwait( false ); - } - - await this.StreamWriteAsync( value, ( items, _, cts ) => this.PrivatePackRawBodyAsyncCore( items, cts ), null, cancellationToken ).ConfigureAwait( false ); - } + await this.PackBinaryHeaderAsyncCore( value.Length, cancellationToken ).ConfigureAwait( false ); + await this.WriteBytesAsync( value, false, cancellationToken ).ConfigureAwait( false ); } #endif // FEATURE_TAP @@ -2533,7 +2578,14 @@ private async Task PrivatePackBinaryAsyncCore( IEnumerable value, Cancella /// This instance has been disposed. public Packer PackString( IEnumerable value ) { - this.PackStringCore( value, Encoding.UTF8 ); + + if ( value == null ) + { + this.PrivatePackNullCore(); + return this; + } + + this.PackRawCore( value ); return this; } @@ -2567,33 +2619,17 @@ protected virtual void PackStringCore( IEnumerable value, Encoding encodin Contract.EndContractBlock(); this.VerifyNotDisposed(); - this.PrivatePackString( value, encoding ); - } - - private void PrivatePackString( IEnumerable value, Encoding encoding ) - { - Contract.Assert( encoding != null, "encoding != null" ); - if ( value == null ) { this.PrivatePackNullCore(); return; } - this.PrivatePackStringCore( value, encoding ); - } - - private void PrivatePackStringCore( IEnumerable value, Encoding encoding ) - { - Contract.Assert( value != null, "value != null" ); - Contract.Assert( encoding != null, "encoding != null" ); - - // TODO: streaming encoding var encoded = encoding.GetBytes( value.ToArray() ); - this.PrivatePackRawHeaderCore( encoded.Length, /*isString:*/ true ); - this.WriteBytes( encoded, true ); + this.PackRawCore( encoded ); } + #if FEATURE_TAP /// @@ -2604,7 +2640,7 @@ private void PrivatePackStringCore( IEnumerable value, Encoding encoding ) /// This instance has been disposed. public Task PackStringAsync( IEnumerable value ) { - return this.PackStringAsyncCore( value, Encoding.UTF8 ); + return this.PackStringAsync( value, CancellationToken.None ); } /// @@ -2617,7 +2653,7 @@ public Task PackStringAsync( IEnumerable value ) /// This instance has been disposed. public Task PackStringAsync( IEnumerable value, Encoding encoding ) { - return this.PackStringAsyncCore( value, encoding ); + return this.PackStringAsync( value, encoding, CancellationToken.None ); } /// @@ -2641,7 +2677,12 @@ protected Task PackStringAsyncCore( IEnumerable value, Encoding encoding ) /// This instance has been disposed. public Task PackStringAsync( IEnumerable value, CancellationToken cancellationToken ) { - return this.PackStringAsyncCore( value, Encoding.UTF8, cancellationToken ); + if ( value == null ) + { + return this.PrivatePackNullAsyncCore( cancellationToken ); + } + + return this.PackRawAsyncCore( value, cancellationToken ); } /// @@ -2666,7 +2707,7 @@ public Task PackStringAsync( IEnumerable value, Encoding encoding, Cancell /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. /// is null. - protected virtual Task PackStringAsyncCore( IEnumerable value, Encoding encoding, CancellationToken cancellationToken ) + protected virtual async Task PackStringAsyncCore( IEnumerable value, Encoding encoding, CancellationToken cancellationToken ) { if ( encoding == null ) { @@ -2676,33 +2717,17 @@ protected virtual Task PackStringAsyncCore( IEnumerable value, Encoding en Contract.EndContractBlock(); this.VerifyNotDisposed(); - return this.PrivatePackStringAsync( value, encoding, cancellationToken ); - } - - private async Task PrivatePackStringAsync( IEnumerable value, Encoding encoding, CancellationToken cancellationToken ) - { - Contract.Assert( encoding != null, "encoding != null" ); - if ( value == null ) { await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); return; } - await this.PrivatePackStringAsyncCore( value, encoding, cancellationToken ).ConfigureAwait( false ); - } - - private async Task PrivatePackStringAsyncCore( IEnumerable value, Encoding encoding, CancellationToken cancellationToken ) - { - Contract.Assert( value != null, "value != null" ); - Contract.Assert( encoding != null, "encoding != null" ); - - // TODO: streaming encoding var encoded = encoding.GetBytes( value.ToArray() ); - await this.PrivatePackRawHeaderAsyncCore( encoded.Length, /*isString:*/ true, cancellationToken ).ConfigureAwait( false ); - await this.WriteBytesAsync( encoded, true, cancellationToken ).ConfigureAwait( false ); + await this.PackRawAsyncCore( encoded, cancellationToken ).ConfigureAwait( false ); } + #endif // FEATURE_TAP /// @@ -2713,7 +2738,14 @@ private async Task PrivatePackStringAsyncCore( IEnumerable value, Encoding /// This instance has been disposed. public Packer PackString( string value ) { - this.PackStringCore( value, Encoding.UTF8 ); + + if ( value == null ) + { + this.PrivatePackNullCore(); + return this; + } + + this.PackRawCore( value ); return this; } @@ -2747,33 +2779,17 @@ protected virtual void PackStringCore( string value, Encoding encoding ) Contract.EndContractBlock(); this.VerifyNotDisposed(); - this.PrivatePackString( value, encoding ); - } - - private void PrivatePackString( string value, Encoding encoding ) - { - Contract.Assert( encoding != null, "encoding != null" ); - if ( value == null ) { this.PrivatePackNullCore(); return; } - this.PrivatePackStringCore( value, encoding ); - } - - private void PrivatePackStringCore( string value, Encoding encoding ) - { - Contract.Assert( value != null, "value != null" ); - Contract.Assert( encoding != null, "encoding != null" ); - - // TODO: streaming encoding var encoded = encoding.GetBytes( value ); - this.PrivatePackRawHeaderCore( encoded.Length, /*isString:*/ true ); - this.WriteBytes( encoded, true ); + this.PackRawCore( encoded ); } + #if FEATURE_TAP /// @@ -2784,7 +2800,7 @@ private void PrivatePackStringCore( string value, Encoding encoding ) /// This instance has been disposed. public Task PackStringAsync( string value ) { - return this.PackStringAsyncCore( value, Encoding.UTF8 ); + return this.PackStringAsync( value, CancellationToken.None ); } /// @@ -2797,7 +2813,7 @@ public Task PackStringAsync( string value ) /// This instance has been disposed. public Task PackStringAsync( string value, Encoding encoding ) { - return this.PackStringAsyncCore( value, encoding ); + return this.PackStringAsync( value, encoding, CancellationToken.None ); } /// @@ -2821,7 +2837,12 @@ protected Task PackStringAsyncCore( string value, Encoding encoding ) /// This instance has been disposed. public Task PackStringAsync( string value, CancellationToken cancellationToken ) { - return this.PackStringAsyncCore( value, Encoding.UTF8, cancellationToken ); + if ( value == null ) + { + return this.PrivatePackNullAsyncCore( cancellationToken ); + } + + return this.PackRawAsyncCore( value, cancellationToken ); } /// @@ -2846,7 +2867,7 @@ public Task PackStringAsync( string value, Encoding encoding, CancellationToken /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. /// is null. - protected virtual Task PackStringAsyncCore( string value, Encoding encoding, CancellationToken cancellationToken ) + protected virtual async Task PackStringAsyncCore( string value, Encoding encoding, CancellationToken cancellationToken ) { if ( encoding == null ) { @@ -2856,31 +2877,69 @@ protected virtual Task PackStringAsyncCore( string value, Encoding encoding, Can Contract.EndContractBlock(); this.VerifyNotDisposed(); - return this.PrivatePackStringAsync( value, encoding, cancellationToken ); + if ( value == null ) + { + await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); + return; + } + + var encoded = encoding.GetBytes( value ); + await this.PackRawAsyncCore( encoded, cancellationToken ).ConfigureAwait( false ); } - private async Task PrivatePackStringAsync( string value, Encoding encoding, CancellationToken cancellationToken ) + +#endif // FEATURE_TAP + + /// + /// Packs specified to current stream with UTF-8 . + /// + /// A string. + protected virtual void PackRawCore( string value ) { - Contract.Assert( encoding != null, "encoding != null" ); + this.PackStringCore( value, Encoding.UTF8 ); + } - if ( value == null ) + private void PackRawCore( IEnumerable value ) + { +#if !NETSTANDARD1_1 + var asString = value as string; + if ( asString == null ) { - await this.PrivatePackNullAsyncCore( cancellationToken ).ConfigureAwait( false ); - return; + asString = new String( value.ToArray() ); } +#else + var asString = new String( value.ToArray() ); +#endif // !NETSTANDARD1_1 + + this.PackStringCore( asString, Encoding.UTF8 ); + } + +#if FEATURE_TAP - await this.PrivatePackStringAsyncCore( value, encoding, cancellationToken ).ConfigureAwait( false ); + /// + /// Packs specified to current stream with UTF-8 asynchronously. + /// + /// A string. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual Task PackRawAsyncCore( string value, CancellationToken cancellationToken ) + { + return this.PackStringAsyncCore( value, Encoding.UTF8, cancellationToken ); } - private async Task PrivatePackStringAsyncCore( string value, Encoding encoding, CancellationToken cancellationToken ) + private Task PackRawAsyncCore( IEnumerable value, CancellationToken cancellationToken ) { - Contract.Assert( value != null, "value != null" ); - Contract.Assert( encoding != null, "encoding != null" ); +#if !NETSTANDARD1_1 + var asString = value as string; + if ( asString == null ) + { + asString = new String( value.ToArray() ); + } +#else + var asString = new String( value.ToArray() ); +#endif // !NETSTANDARD1_1 - // TODO: streaming encoding - var encoded = encoding.GetBytes( value ); - await this.PrivatePackRawHeaderAsyncCore( encoded.Length, /*isString:*/ true, cancellationToken ).ConfigureAwait( false ); - await this.WriteBytesAsync( encoded, true, cancellationToken ).ConfigureAwait( false ); + return this.PackStringAsyncCore( asString, Encoding.UTF8, cancellationToken ); } #endif // FEATURE_TAP @@ -3178,7 +3237,7 @@ public Task PackMapHeaderAsync( IDictionary map, Can #region -- Ext -- /// - /// Packs an extended type value. + /// Packs an extended type value. /// /// A type code of the extended type value. /// A binary value portion of the extended type value. @@ -3193,10 +3252,15 @@ public Packer PackExtendedTypeValue( byte typeCode, byte[] body ) ThrowArgumentNullException( "body" ); } + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) + { + ThrowExtTypeIsProhibitedException(); + } + this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackExtendedTypeValueCore( typeCode, body ); + this.PackExtendedTypeValueCore( typeCode, body ); return this; } @@ -3215,17 +3279,22 @@ public Packer PackExtendedTypeValue( MessagePackExtendedTypeObject mpeto ) ThrowMissingBodyOfExtTypeValueException( "mpeto" ); } - this.PrivatePackExtendedTypeValueCore( mpeto.TypeCode, mpeto.Body ); - return this; - } - - private void PrivatePackExtendedTypeValueCore( byte typeCode, byte[] body ) - { if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) { ThrowExtTypeIsProhibitedException(); } + this.PackExtendedTypeValueCore( mpeto.TypeCode, mpeto.Body ); + return this; + } + + /// + /// Packs an extended type value. + /// + /// A type code of the extended type value. + /// A binary value portion of the extended type value. + protected virtual void PackExtendedTypeValueCore( byte typeCode, byte[] body ) + { switch ( body.Length ) { case 1: @@ -3288,7 +3357,7 @@ private void PrivatePackExtendedTypeValueCore( byte typeCode, byte[] body ) #if FEATURE_TAP /// - /// Packs an extended type value asynchronously. + /// Packs an extended type value asynchronously. /// /// A type code of the extended type value. /// A binary value portion of the extended type value. @@ -3315,7 +3384,7 @@ public Task PackExtendedTypeValueAsync( MessagePackExtendedTypeObject mpeto ) } /// - /// Packs an extended type value asynchronously. + /// Packs an extended type value asynchronously. /// /// A type code of the extended type value. /// A binary value portion of the extended type value. @@ -3331,10 +3400,15 @@ public Task PackExtendedTypeValueAsync( byte typeCode, byte[] body, Cancellation ThrowArgumentNullException( "body" ); } + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) + { + ThrowExtTypeIsProhibitedException(); + } + this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackExtendedTypeValueAsyncCore( typeCode, body, cancellationToken ); + return this.PackExtendedTypeValueAsyncCore( typeCode, body, cancellationToken ); } /// @@ -3353,16 +3427,22 @@ public Task PackExtendedTypeValueAsync( MessagePackExtendedTypeObject mpeto, Can ThrowMissingBodyOfExtTypeValueException( "mpeto" ); } - return this.PrivatePackExtendedTypeValueAsyncCore( mpeto.TypeCode, mpeto.Body, cancellationToken ); - } - - private async Task PrivatePackExtendedTypeValueAsyncCore( byte typeCode, byte[] body, CancellationToken cancellationToken ) - { if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) { ThrowExtTypeIsProhibitedException(); } + return this.PackExtendedTypeValueAsyncCore( mpeto.TypeCode, mpeto.Body, cancellationToken ); + } + + /// + /// Packs an extended type value asynchronously. + /// + /// A type code of the extended type value. + /// A binary value portion of the extended type value. + /// The token to monitor for cancellation requests. The default value is . + protected virtual async Task PackExtendedTypeValueAsyncCore( byte typeCode, byte[] body, CancellationToken cancellationToken ) + { switch ( body.Length ) { case 1: diff --git a/src/MsgPack/Packer.Packing.tt b/src/MsgPack/Packer.Packing.tt index 6e5391bd4..529d5c231 100644 --- a/src/MsgPack/Packer.Packing.tt +++ b/src/MsgPack/Packer.Packing.tt @@ -1,4 +1,4 @@ -<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ template debug="true" hostSpecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ include file="..\Core.ttinclude" #> <#@ Assembly Name="System.Core.dll" #> @@ -35,11 +35,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; using System.Text; #if FEATURE_TAP @@ -131,14 +131,14 @@ for ( var bits = 16; bits < 128; bits *= 2 ) if ( !isAsync ) { #> - this.PrivatePackCore( value ); + this.PackCore( value ); return this; <# } else { #> - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); <# } } @@ -148,7 +148,27 @@ for ( var bits = 16; bits < 128; bits *= 2 ) <# } // w/ | w/o cancel #> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= Async( isAsync ) #>Core( <#= typeName #> value<#= Parameter( isAsync ) #> ) + /// + /// Packs value to current stream<#= AsyncSummarySuffix( isAsync ) #>. + /// + /// value. +<# + if ( isAsync ) + { +#> + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. +<# + } + + if ( !isSigned ) + { +#> + [CLSCompliant( false )] +<# + } +#> + protected virtual <#= AsyncReturn( isAsync ) #> Pack<#= Async( isAsync ) #>Core( <#= typeName #> value<#= Parameter( isAsync ) #> ) { if ( <#= Await( isAsync, "this.TryPackTiny" + ( isSigned ? "Signed" : "Unsigned" ) + "Integer" + Async( isAsync ) + "( value" + LastArgument( isAsync ) + " )" ) #> ) { @@ -338,14 +358,14 @@ foreach ( var isAsync in new [] { false, true } ) if ( !isAsync ) { #> - this.PrivatePackCore( value ); + this.PackCore( value ); return this; <# } else { #> - return this.PrivatePackAsyncCore( value<#= LastArgument( isAsync ) #> ); + return this.PackAsyncCore( value<#= LastArgument( isAsync ) #> ); <# } } @@ -356,12 +376,26 @@ foreach ( var isAsync in new [] { false, true } ) } // w/ | w/o cancel #> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= Async( isAsync ) #>Core( float value<#= Parameter( isAsync ) #> ) + /// + /// Packs value to current stream<#= AsyncSummarySuffix( isAsync ) #>. + /// + /// value. +<# + if ( isAsync ) + { +#> + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. +<# + } +#> + protected virtual <#= AsyncReturn( isAsync ) #> Pack<#= Async( isAsync ) #>Core( float value<#= Parameter( isAsync ) #> ) { <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( MessagePackCode.Real32" + LastArgument( isAsync ) + " )" ) #>; var bits = new Float32Bits( value ); + // Float32Bits usage is effectively pointer dereference operation rather than shifting operators, so we must consider endianness here. if ( BitConverter.IsLittleEndian ) { <# @@ -447,14 +481,14 @@ foreach ( var isAsync in new [] { false, true } ) if ( !isAsync ) { #> - this.PrivatePackCore( value ); + this.PackCore( value ); return this; <# } else { #> - return this.PrivatePackAsyncCore( value<#= LastArgument( isAsync ) #> ); + return this.PackAsyncCore( value<#= LastArgument( isAsync ) #> ); <# } } @@ -465,7 +499,20 @@ foreach ( var isAsync in new [] { false, true } ) } // w/ | w/o cancel #> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= Async( isAsync ) #>Core( double value<#= Parameter( isAsync ) #> ) + /// + /// Packs value to current stream<#= AsyncSummarySuffix( isAsync ) #>. + /// + /// value. +<# + if ( isAsync ) + { +#> + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. +<# + } +#> + protected virtual <#= AsyncReturn( isAsync ) #> Pack<#= Async( isAsync ) #>Core( double value<#= Parameter( isAsync ) #> ) { <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( MessagePackCode.Real64" + LastArgument( isAsync ) + " )" ) #>; unchecked @@ -545,6 +592,14 @@ foreach ( var item in /// This instance has been disposed. public <#= ReturnThis( isAsync ) #> Pack<#= item.Type #>Header<#= Async( isAsync ) #>( int count<#= Parameter( withCancel ) #> ) { + if ( count < 0 ) + { + ThrowCannotBeNegativeException( "count" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); + <# if ( !isAsync ) { @@ -580,7 +635,7 @@ foreach ( var item in <# } #> - protected <#= Return( isAsync ) #> Pack<#= item.Type #>Header<#= Async( isAsync ) #>Core( int count<#= Parameter( withCancel ) #> ) + protected <#= ( !isAsync || withCancel ) ? "virtual " : String.Empty #><#= !isAsync ? "void" : withCancel ? "async Task" : "Task" #> Pack<#= item.Type #>Header<#= Async( isAsync ) #>Core( int count<#= Parameter( withCancel ) #> ) { <# if ( isAsync && !withCancel ) @@ -592,25 +647,6 @@ foreach ( var item in else { #> - if ( count < 0 ) - { - ThrowCannotBeNegativeException( "count" ); - } - - Contract.EndContractBlock(); - this.VerifyNotDisposed(); - - <#= isAsync ? "return " : String.Empty #>this.PrivatePack<#= item.Type #>Header<#= Async( isAsync ) #>Core( count<#= LastArgument( isAsync ) #> ); -<# - } -#> - } - -<# - } // w/ | w/o cancel -#> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= item.Type #>Header<#= Async( isAsync ) #>Core( int count<#= Parameter( isAsync ) #> ) - { #if !UNITY Contract.Assert( 0 <= count, "0 <= count" ); #endif // !UNITY @@ -638,12 +674,17 @@ foreach ( var item in #> } } +<# + } +#> } + <# + } // w/ | w/o cancel + if ( isAsync ) { #> - #endif // FEATURE_TAP <# } @@ -717,18 +758,50 @@ foreach ( var item in stringBinaryItems ) #> public <#= ReturnThis( isAsync ) #> Pack<#= item.Type #>Header<#= Async( isAsync ) #>( int length<#= Parameter( withCancel ) #> ) { + if ( length < 0 ) + { + ThrowCannotBeNegativeException( "length" ); + } + + Contract.EndContractBlock(); + this.VerifyNotDisposed(); +<# + if ( item.Type == "Binary" ) + { +#> + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) + { + // In compat mode, use raw(str) header. <# + if ( !isAsync ) + { +#> + this.PackStringHeaderCore( length ); + return this; +<# + } + else + { +#> + return this.PackStringHeaderAsyncCore( length<#= LastArgument( withCancel ) #> ); +<# + } // if !isAsync +#> + } +<# + } // if item.Type == "Binary" + if ( !isAsync ) { #> - this.Pack<#= item.Type #>HeaderCore( length ); + this.Pack<#= item.Type == "Raw" ? "String" : item.Type #>HeaderCore( length ); return this; <# } else { #> - return this.Pack<#= item.Type #>HeaderAsyncCore( length<#= LastArgument( withCancel ) #> ); + return this.Pack<#= item.Type == "Raw" ? "String" : item.Type #>HeaderAsyncCore( length<#= LastArgument( withCancel ) #> ); <# } #> @@ -798,7 +871,7 @@ foreach ( var item in stringBinaryItems ) else { #> - protected <#= Return( isAsync ) #> Pack<#= item.Type #>Header<#= Async( isAsync ) #>Core( int length<#= Parameter( withCancel ) #> ) + protected <#= ( !isAsync || withCancel ) ? "virtual " : String.Empty #><#= !isAsync ? "void" : withCancel ? "async Task" : "Task" #> Pack<#= item.Type #>Header<#= Async( isAsync ) #>Core( int length<#= Parameter( withCancel ) #> ) { <# if ( isAsync && !withCancel ) @@ -809,17 +882,19 @@ foreach ( var item in stringBinaryItems ) } else { + if ( item.Type == "String" ) + { #> - if ( length < 0 ) + if ( length < 32 ) { - ThrowCannotBeNegativeException( "length" ); + <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) )" + LastArgument( isAsync ) + " )" ) #>; + return; } - Contract.EndContractBlock(); - this.VerifyNotDisposed(); - - <#= isAsync ? "return " : String.Empty #>this.PrivatePackRawHeader<#= Async( isAsync ) #>Core( length, <#= ( item.Type == "String" ).ToString().ToLowerInvariant() #><#= LastArgument( isAsync ) #> ); <# + } + + WritePackBinary( isString: item.Type == "String", isAsync: isAsync ); } #> } @@ -840,54 +915,6 @@ foreach ( var item in stringBinaryItems ) } // sync | async } // End String/Binary header core - -foreach ( var isAsync in new [] { false, true } ) -{ - if ( isAsync ) - { -#> -#if FEATURE_TAP - -<# - } -#> - private <#= AsyncReturn( isAsync ) #> PrivatePackRawHeader<#= Async( isAsync ) #>Core( int length, bool isString<#= Parameter( isAsync ) #> ) - { - Contract.Assert( 0 <= length, "0 <= length" ); - - if ( isString || ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) - { - if ( length < 32 ) - { - <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( unchecked( ( byte )( MessagePackCode.MinimumFixedRaw | length ) )" + LastArgument( isAsync ) + " )" ) #>; - return; - } - -<# - WritePackBinary( isString: true, isAsync: isAsync ); -#> - } - else - { - // !isString && compat options is not set. - -<# - WritePackBinary( isString: false, isAsync: isAsync ); -#> - } - } -<# - if ( isAsync ) - { -#> - -#endif // FEATURE_TAP -<# - } -#> - -<# -} // sync | async #> #endregion -- Collection Header -- @@ -917,9 +944,9 @@ foreach ( var item in foreach ( var parameter in new [] { - new { Type = "IEnumerable", AsType = "ICollection", AsName = "asCollection", Label = "byte sequence", Description = "Source bytes its size is not known." }, - new { Type = "IList", AsType = "byte[]", AsName = "asByteArray", Label = "byte collection", Description = "Source bytes its size is known." }, - new { Type = "byte[]", AsType = default( string ), AsName = default( string ), Label = "byte array", Description = "A byte array." } + new { Type = "IEnumerable", Label = "byte sequence", Description = "Source bytes its size is not known." }, + new { Type = "IList", Label = "byte collection", Description = "Source bytes its size is known." }, + new { Type = "byte[]", Label = "byte array", Description = "A byte array." } } ) { @@ -969,26 +996,44 @@ foreach ( var item in this.VerifyNotDisposed(); Contract.EndContractBlock(); + if ( value == null ) + { + <#= isAsync ? "return " : String.Empty #>this.PrivatePackNull<#= Async( isAsync ) #>Core(<#= Argument( isAsync )#>); <# - if ( parameter.AsType != null ) + if ( !isAsync ) { #> - var <#= parameter.AsName #> = value as <#= parameter.AsType #>; - if ( <#= parameter.AsName #> == null ) - { - <#= isAsync ? "return " : String.Empty #>this.PrivatePack<#= item.Type #><#= Async( isAsync ) #>( value<#= LastArgument( isAsync ) #> ); - } - else - { - <#= isAsync ? "return " : String.Empty #>this.PrivatePack<#= item.Type #><#= Async( isAsync ) #>( <#= parameter.AsName #><#= LastArgument( isAsync ) #> ); + return this; +<# + } +#> } <# + if ( parameter.Type == "byte[]" ) + { + WriteCallPackBinaryCore( item.Type, "value", isAsync ); } else { #> - <#= isAsync ? "return " : String.Empty #>this.PrivatePack<#= item.Type #><#= Async( isAsync ) #>( value<#= LastArgument( isAsync ) #> ); + var asArray = value as byte[]; + if ( asArray != null ) + { +<# + PushIndent( 1 ); + WriteCallPackBinaryCore( item.Type, "asArray", isAsync ); + PopIndent(); +#> + } + else + { +<# + PushIndent( 1 ); + WriteCallPackBinaryCore( item.Type, "value.ToArray()", isAsync ); + PopIndent(); +#> + } <# } @@ -1006,85 +1051,24 @@ foreach ( var item in } // w/ | w/o cancel } // end parameter foreach #> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= item.Type #><#= Async( isAsync ) #>( ICollection value<#= Parameter( isAsync ) #> ) - { - if ( value == null ) - { - <#= Await( isAsync, "this.PrivatePackNull" + Async( isAsync ) + "Core(" + Argument( isAsync ) + ")" ) #>; - return; - } - - <#= Await( isAsync, "this.PrivatePackRawHeader" + Async( isAsync ) + "Core( value.Count, /*isString:*/ " + ( item.Type == "Raw" ).ToString().ToLowerInvariant() + LastArgument( isAsync ) + " )" ) #>; - <#= Await( isAsync, "this.WriteBytes" + Async( isAsync ) + "( value" + LastArgument( isAsync ) + " )" ) #>; - } + /// + /// Packs specified byte array(<#= item.TypeNote #> to current stream<#= AsyncSummarySuffix( isAsync ) #>. + /// + /// A byte array. <# - foreach ( var type in - new [] - { - new { Name = "byte[]", ExtraArguments = ", false" }, - new { Name = "IEnumerable", ExtraArguments = String.Empty } - } - ) - { -#> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= item.Type #><#= Async( isAsync ) #>( <#= type.Name #> value<#= Parameter( isAsync ) #> ) - { - if ( value == null ) + if ( isAsync ) { - <#= Await( isAsync, "this.PrivatePackNull" + Async( isAsync ) + "Core(" + Argument( isAsync ) + ")" ) #>; - return; - } - - <#= Await( isAsync, "this.PrivatePack" + item.Type + Async( isAsync ) + "Core( value" + type.ExtraArguments + LastArgument( isAsync ) + " )" ) #>; - } - -<# - } // end foreach #> - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= item.Type #><#= Async( isAsync ) #>Core( byte[] value, bool isImmutable<#= Parameter( isAsync ) #> ) - { - <#= Await( isAsync, "this.PrivatePackRawHeader" + Async( isAsync ) + "Core( value.Length, /*isString:*/ " + ( item.Type == "Raw" ).ToString().ToLowerInvariant() + LastArgument( isAsync ) + " )" ) #>; - <#= Await( isAsync, "this.WriteBytes" + Async( isAsync ) + "( value, isImmutable" + LastArgument( isAsync ) + " )" ) #>; - } - - private <#= AsyncReturn( isAsync ) #> PrivatePack<#= item.Type #><#= Async( isAsync ) #>Core( IEnumerable value<#= Parameter( isAsync ) #> ) - { - if ( !this.CanSeek ) - { - // buffered - <#= Await( isAsync, "this.PrivatePack" + item.Type + Async( isAsync ) + "Core( value.ToArray(), true" + LastArgument( isAsync ) + " )" ) #>; - } - else - { - // Header + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. <# - if ( item.Type == "Raw" ) - { + } #> - <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( MessagePackCode.Raw32" + LastArgument( isAsync ) + " )" ) #>; -<# - } - else + protected virtual <#= AsyncReturn( isAsync ) #> Pack<#= item.Type #><#= Async( isAsync ) #>Core( byte[] value<#= Parameter( isAsync ) #> ) { -#> - // Use biggest data size because actual binary length is not known. - if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) != 0 ) - { - <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( MessagePackCode.Raw32" + LastArgument( isAsync ) + " )" ) #>; - } - else - { - <#= Await( isAsync, "this.WriteByte" + Async( isAsync ) + "( MessagePackCode.Bin32" + LastArgument( isAsync ) + " )" ) #>; - } - -<# - } - - var lamdaParameter = isAsync ? ", cts" : String.Empty; -#> - <#= Await( isAsync, "this.StreamWrite" + Async( isAsync ) + "( value, ( items, _" + lamdaParameter + " ) => this.PrivatePackRawBody" + Async( isAsync ) + "Core( items" + lamdaParameter + " ), null" + LastArgument( isAsync ) + " )" ) #>; - } + <#= Await( isAsync, "this.Pack" + ( item.Type == "Raw" ? "String" : item.Type ) + "Header" + Async( isAsync ) + "Core( value.Length" + LastArgument( isAsync ) + " )" ) #>; + <#= Await( isAsync, "this.WriteBytes" + Async( isAsync ) + "( value, false" + LastArgument( isAsync ) + " )" ) #>; } <# if ( isAsync ) @@ -1172,21 +1156,74 @@ foreach ( var item in stringItems ) } #> /// This instance has been disposed. - public <#= ReturnThis( isAsync ) #> PackString<#= Async( isAsync ) #>( <#= item.Type #> value<#= withEncoding ? ", Encoding encoding" : String.Empty #><#= Parameter( withCancel ) #> ) + public <#= ReturnThis( isAsync ) #> PackString<#= Async( isAsync ) #>( <#= item.Type #> value<#= withEncoding ? ", Encoding encoding" : String.Empty #><#= Parameter( withCancel ) #> ) { <# if ( !isAsync ) { + if ( withEncoding ) + { +#> + this.PackStringCore( value, encoding ); +<# + } + else + { +#> + + if ( value == null ) + { + <#= isAsync ? "return " : String.Empty #>this.PrivatePackNull<#= Async( isAsync ) #>Core(<#= Argument( isAsync )#>); +<# + if ( !isAsync ) + { +#> + return this; +<# + } +#> + } + + this.PackRawCore( value ); +<# + } #> - this.PackStringCore( value, <#= withEncoding ? "encoding" : "Encoding.UTF8" #> ); return this; +<# + } + else if ( !withCancel ) + { +#> + return this.PackStringAsync( value<#= withEncoding ? ", encoding" : String.Empty #>, CancellationToken.None ); <# } else { + if ( withEncoding ) + { +#> + return this.PackStringAsyncCore( value, encoding<#= LastArgument( withCancel ) #> ); +<# + } + else + { +#> + if ( value == null ) + { + <#= isAsync ? "return " : String.Empty #>this.PrivatePackNull<#= Async( isAsync ) #>Core(<#= Argument( isAsync )#>); +<# + if ( !isAsync ) + { +#> + return this; +<# + } #> - return this.PackStringAsyncCore( value, <#= withEncoding ? "encoding" : "Encoding.UTF8" #><#= LastArgument( withCancel ) #> ); + } + + return this.PackRawAsyncCore( value<#= LastArgument( withCancel ) #> ); <# + } } #> } @@ -1215,7 +1252,7 @@ foreach ( var item in stringItems ) } #> /// is null. - protected <#= ( !isAsync || withCancel ) ? "virtual " : String.Empty #><#= Return( isAsync ) #> PackString<#= Async( isAsync ) #>Core( <#= item.Type #> value, Encoding encoding<#= Parameter( withCancel ) #> ) + protected <#= ( !isAsync || withCancel ) ? "virtual " : String.Empty #><#= AsyncReturn( isAsync, withCancel ) #> PackString<#= Async( isAsync ) #>Core( <#= item.Type #> value, Encoding encoding<#= Parameter( withCancel ) #> ) { <# if ( isAsync && !withCancel ) @@ -1235,39 +1272,21 @@ foreach ( var item in stringItems ) Contract.EndContractBlock(); this.VerifyNotDisposed(); - <#= isAsync ? "return " : String.Empty #>this.PrivatePackString<#= Async( isAsync ) #>( value, encoding<#= LastArgument( isAsync ) #> ); -<# - } -#> - } - -<# - } // w/ | w/o cancel -#> - private <#= AsyncReturn( isAsync ) #> PrivatePackString<#= Async( isAsync ) #>( <#= item.Type #> value, Encoding encoding<#= Parameter( isAsync ) #> ) - { - Contract.Assert( encoding != null, "encoding != null" ); - if ( value == null ) { <#= Await( isAsync, "this.PrivatePackNull" + Async( isAsync ) + "Core(" + Argument( isAsync ) + ")" ) #>; return; } - <#= Await( isAsync, "this.PrivatePackString" + Async( isAsync ) + "Core( value, encoding" + LastArgument( isAsync ) + " )" ) #>; - } - - private <#= isAsync ? "async Task" : "void" #> PrivatePackString<#= Async( isAsync ) #>Core( <#= item.Type #> value, Encoding encoding<#= Parameter( isAsync ) #> ) - { - Contract.Assert( value != null, "value != null" ); - Contract.Assert( encoding != null, "encoding != null" ); - - // TODO: streaming encoding var encoded = encoding.GetBytes( value<#= item.Type != "string" ? ".ToArray()" : String.Empty #> ); - <#= Await( isAsync, "this.PrivatePackRawHeader" + Async( isAsync ) + "Core( encoded.Length, /*isString:*/ true" + LastArgument( isAsync ) + " )" ) #>; - <#= Await( isAsync, "this.WriteBytes" + Async( isAsync ) + "( encoded, true" + LastArgument( isAsync ) + " )" ) #>; + <#= Await( isAsync, "this.PackRaw" + Async( isAsync ) + "Core( encoded" + LastArgument( isAsync ) + " )" ) #>; +<# + } +#> } + <# + } // w/ | w/o cancel if ( isAsync ) { @@ -1280,7 +1299,60 @@ foreach ( var item in stringItems ) <# } // sync | async -} +} // foreach item + +foreach ( var isAsync in new [] { false, true } ) +{ + if ( isAsync ) + { +#> +#if FEATURE_TAP + +<# + } +#> + /// + /// Packs specified to current stream with UTF-8 <#= AsyncSummarySuffix( isAsync ) #>. + /// + /// A string. +<# + if ( isAsync ) + { +#> + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. +<# + } +#> + protected virtual <#= Return( isAsync ) #> PackRaw<#= Async( isAsync ) #>Core( string value<#= Parameter( isAsync ) #> ) + { + <#= isAsync ? "return " : String.Empty #>this.PackString<#= Async( isAsync ) #>Core( value, Encoding.UTF8<#= LastArgument( isAsync ) #> ); + } + + private <#= Return( isAsync ) #> PackRaw<#= Async( isAsync ) #>Core( IEnumerable value<#= Parameter( isAsync ) #> ) + { +#if !NETSTANDARD1_1 + var asString = value as string; + if ( asString == null ) + { + asString = new String( value.ToArray() ); + } +#else + var asString = new String( value.ToArray() ); +#endif // !NETSTANDARD1_1 + + <#= isAsync ? "return " : String.Empty #>this.PackString<#= Async( isAsync ) #>Core( asString, Encoding.UTF8<#= LastArgument( isAsync ) #> ); + } + +<# + if ( isAsync ) + { +#> +#endif // FEATURE_TAP + +<# + } +} // foreach isAsync // End string w/ header #> #endregion -- String with Header -- @@ -1650,7 +1722,7 @@ foreach ( var isAsync in new [] { false, true } ) { #> /// - /// Packs an extended type value<#= AsyncSummarySuffix( isAsync ) #>. + /// Packs an extended type value<#= AsyncSummarySuffix( isAsync ) #>. /// /// A type code of the extended type value. /// A binary value portion of the extended type value. @@ -1694,6 +1766,11 @@ foreach ( var isAsync in new [] { false, true } ) ThrowArgumentNullException( "body" ); } + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) + { + ThrowExtTypeIsProhibitedException(); + } + this.VerifyNotDisposed(); Contract.EndContractBlock(); @@ -1701,14 +1778,14 @@ foreach ( var isAsync in new [] { false, true } ) if ( !isAsync ) { #> - this.PrivatePackExtendedTypeValueCore( typeCode, body ); + this.PackExtendedTypeValueCore( typeCode, body ); return this; <# } else { #> - return this.PrivatePackExtendedTypeValueAsyncCore( typeCode, body<#= LastArgument( isAsync ) #> ); + return this.PackExtendedTypeValueAsyncCore( typeCode, body<#= LastArgument( isAsync ) #> ); <# } } @@ -1759,18 +1836,23 @@ foreach ( var isAsync in new [] { false, true } ) ThrowMissingBodyOfExtTypeValueException( "mpeto" ); } + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) + { + ThrowExtTypeIsProhibitedException(); + } + <# if ( !isAsync ) { #> - this.PrivatePackExtendedTypeValueCore( mpeto.TypeCode, mpeto.Body ); + this.PackExtendedTypeValueCore( mpeto.TypeCode, mpeto.Body ); return this; <# } else { #> - return this.PrivatePackExtendedTypeValueAsyncCore( mpeto.TypeCode, mpeto.Body<#= LastArgument( isAsync ) #> ); + return this.PackExtendedTypeValueAsyncCore( mpeto.TypeCode, mpeto.Body<#= LastArgument( isAsync ) #> ); <# } } @@ -1780,13 +1862,21 @@ foreach ( var isAsync in new [] { false, true } ) <# } // w/ | w/o cancel #> - private <#= AsyncReturn( isAsync ) #> PrivatePackExtendedTypeValue<#= Async( isAsync ) #>Core( byte typeCode, byte[] body<#= Parameter( isAsync ) #> ) + /// + /// Packs an extended type value<#= AsyncSummarySuffix( isAsync ) #>. + /// + /// A type code of the extended type value. + /// A binary value portion of the extended type value. +<# + if ( isAsync ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<# + } +#> + protected virtual <#= AsyncReturn( isAsync ) #> PackExtendedTypeValue<#= Async( isAsync ) #>Core( byte typeCode, byte[] body<#= Parameter( isAsync ) #> ) { - if ( ( this._compatibilityOptions & PackerCompatibilityOptions.ProhibitExtendedTypeObjects ) != 0 ) - { - ThrowExtTypeIsProhibitedException(); - } - switch ( body.Length ) { <# @@ -1984,6 +2074,30 @@ void WritePackBinary( bool isString, bool isAsync ) <#+ } +void WriteCallPackBinaryCore( string itemType, string variable, bool isAsync ) +{ + if ( itemType == "Binary" ) + { +#> + if ( ( this._compatibilityOptions & PackerCompatibilityOptions.PackBinaryAsRaw ) == 0 ) + { + <#= isAsync ? "return " : String.Empty #>this.PackBinary<#= Async( isAsync ) #>Core( <#= variable #><#= LastArgument( isAsync ) #> ); + } + else + { + <#= isAsync ? "return " : String.Empty #>this.PackRaw<#= Async( isAsync ) #>Core( <#= variable #><#= LastArgument( isAsync ) #> ); + } + +<#+ + } + else + { +#> + <#= isAsync ? "return " : String.Empty #>this.Pack<#= itemType #><#= Async( isAsync ) #>Core( <#= variable #><#= LastArgument( isAsync ) #> ); +<#+ + } +} + private static string Async( bool isAsync ) { return isAsync ? "Async" : String.Empty; diff --git a/src/MsgPack/Packer.cs b/src/MsgPack/Packer.cs index 26a279364..c421c6869 100644 --- a/src/MsgPack/Packer.cs +++ b/src/MsgPack/Packer.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,11 +24,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.IO; #if FEATURE_TAP @@ -129,93 +129,6 @@ protected Packer( PackerCompatibilityOptions compatibilityOptions ) this._compatibilityOptions = compatibilityOptions; } - /// - /// Create standard Safe instancde wrapping specified with . - /// - /// object. This stream will be closed when is called. - /// Safe . This will not be null. - /// is null. - /// - /// You can specify any derived class like FileStream, , - /// NetworkStream, UnmanagedMemoryStream, or so. - /// - public static Packer Create( Stream stream ) - { - return Create( stream, true ); - } - - /// - /// Create standard Safe instancde wrapping specified with specified . - /// - /// object. This stream will be closed when is called. - /// A which specifies compatibility options. - /// Safe . This will not be null. - /// is null. - /// - /// You can specify any derived class like FileStream, , - /// NetworkStream, UnmanagedMemoryStream, or so. - /// - public static Packer Create( Stream stream, PackerCompatibilityOptions compatibilityOptions ) - { - return Create( stream, compatibilityOptions, true ); - } - - /// - /// Create standard Safe instancde wrapping specified with . - /// - /// object. - /// - /// true to close when this instance is disposed; - /// false, otherwise. - /// - /// Safe . This will not be null. - /// is null. - /// - /// You can specify any derived class like FileStream, , - /// NetworkStream, UnmanagedMemoryStream, or so. - /// - public static Packer Create( Stream stream, bool ownsStream ) - { - return Create( stream, DefaultCompatibilityOptions, ownsStream ); - } - - /// - /// Create standard Safe instancde wrapping specified with specified . - /// - /// object. - /// A which specifies compatibility options. - /// - /// true to close when this instance is disposed; - /// false, otherwise. - /// - /// Safe . This will not be null. - /// is null. - /// - /// You can specify any derived class like FileStream, , - /// NetworkStream, UnmanagedMemoryStream, or so. - /// - public static Packer Create( Stream stream, PackerCompatibilityOptions compatibilityOptions, bool ownsStream ) - { - return new StreamPacker( stream, compatibilityOptions, ownsStream ? PackerUnpackerStreamOptions.SingletonOwnsStream : PackerUnpackerStreamOptions.None ); - } - - /// - /// Create standard Safe instancde wrapping specified with specified . - /// - /// object. - /// A which specifies compatibility options. - /// which specifies stream handling options. - /// Safe . This will not be null. - /// is null. - /// - /// You can specify any derived class like FileStream, , - /// NetworkStream, UnmanagedMemoryStream, or so. - /// - public static Packer Create( Stream stream, PackerCompatibilityOptions compatibilityOptions, PackerUnpackerStreamOptions streamOptions ) - { - return new StreamPacker( stream, compatibilityOptions, streamOptions ); - } - /// /// Clean up internal resources. /// @@ -250,6 +163,37 @@ private void ThrowObjectDisposedException() throw new ObjectDisposedException( this.ToString() ); } + /// + /// Flushes internal buffer (including underlying stream). + /// + public virtual void Flush() + { + // nop + } + +#if FEATURE_TAP + + /// + /// Flushes internal buffer (including underlying stream) asynchronously. + /// + /// A to represent pending asynchronous operation. + public Task FlushAsync() + { + return this.FlushAsync( CancellationToken.None ); + } + + /// + /// Flushes internal buffer (including underlying stream) asynchronously. + /// + /// The token to monitor for cancellation requests. The default value is . + /// A to represent pending asynchronous operation. + public virtual Task FlushAsync( CancellationToken cancellationToken ) + { + return Task.FromResult( default( object ) ); + } + +#endif // FEATURE_TAP + /// /// When overridden by derived class, change current position to specified offset. /// @@ -427,7 +371,7 @@ public Packer Pack( sbyte value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } @@ -458,12 +402,17 @@ public Task PackAsync( sbyte value, CancellationToken cancellationToken ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } #endif // FEATURE_TAP - private void PrivatePackCore( sbyte value ) + /// + /// Packs value to current stream. + /// + /// value. + [CLSCompliant( false )] + protected virtual void PackCore( sbyte value ) { if ( this.TryPackTinySignedInteger( value ) ) { @@ -480,7 +429,14 @@ private void PrivatePackCore( sbyte value ) #if FEATURE_TAP - private async Task PrivatePackAsyncCore( sbyte value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + [CLSCompliant( false )] + protected virtual async Task PackAsyncCore( sbyte value, CancellationToken cancellationToken ) { if ( await this.TryPackTinySignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) { @@ -569,7 +525,7 @@ public Packer Pack( byte value ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } @@ -598,41 +554,33 @@ public Task PackAsync( byte value, CancellationToken cancellationToken ) this.VerifyNotDisposed(); Contract.EndContractBlock(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } #endif // FEATURE_TAP - private void PrivatePackCore( byte value ) - { - if ( this.TryPackTinyUnsignedInteger( value ) ) - { - return; - } -#pragma warning disable 168 - var b = this.TryPackUInt8( value ); -#pragma warning restore 168 -#if DEBUG - Contract.Assert( b, "success" ); -#endif // DEBUG + + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( byte value ) + { + this.WriteByte( value ); } #if FEATURE_TAP - private async Task PrivatePackAsyncCore( byte value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual Task PackAsyncCore( byte value, CancellationToken cancellationToken ) { - if ( await this.TryPackTinyUnsignedIntegerAsync( value, cancellationToken ).ConfigureAwait( false ) ) - { - return; - } - -#pragma warning disable 168 - var b = await this.TryPackUInt8Async( value, cancellationToken ).ConfigureAwait( false ); -#pragma warning restore 168 -#if DEBUG - Contract.Assert( b, "success" ); -#endif // DEBUG + return this.WriteByteAsync( value, cancellationToken ); } #endif // FEATURE_TAP @@ -709,7 +657,7 @@ protected async Task TryPackUInt8Async( ulong value, CancellationToken can public Packer Pack( bool value ) { this.VerifyNotDisposed(); - this.PrivatePackCore( value ); + this.PackCore( value ); return this; } @@ -734,19 +682,29 @@ public Task PackAsync( bool value ) public Task PackAsync( bool value, CancellationToken cancellationToken ) { this.VerifyNotDisposed(); - return this.PrivatePackAsyncCore( value, cancellationToken ); + return this.PackAsyncCore( value, cancellationToken ); } #endif // FEATURE_TAP - private void PrivatePackCore( bool value ) + /// + /// Packs value to current stream. + /// + /// value. + protected virtual void PackCore( bool value ) { this.WriteByte( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue ); } #if FEATURE_TAP - private async Task PrivatePackAsyncCore( bool value, CancellationToken cancellationToken ) + /// + /// Packs value to current stream asynchronously. + /// + /// value. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + protected virtual async Task PackAsyncCore( bool value, CancellationToken cancellationToken ) { await this.WriteByteAsync( value ? ( byte )MessagePackCode.TrueValue : ( byte )MessagePackCode.FalseValue, cancellationToken ).ConfigureAwait( false ); } diff --git a/src/MsgPack/PackerUnpackerExtensions.cs b/src/MsgPack/PackerUnpackerExtensions.cs index 5830332ad..9c363dd1e 100644 --- a/src/MsgPack/PackerUnpackerExtensions.cs +++ b/src/MsgPack/PackerUnpackerExtensions.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -25,11 +25,11 @@ using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; #if FEATURE_TAP using System.Threading; diff --git a/src/MsgPack/PackerUnpackerExtensions.tt b/src/MsgPack/PackerUnpackerExtensions.tt index c29146763..223ac09bf 100644 --- a/src/MsgPack/PackerUnpackerExtensions.tt +++ b/src/MsgPack/PackerUnpackerExtensions.tt @@ -1,4 +1,4 @@ -<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ template debug="true" hostSpecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ include file="..\Core.ttinclude" #> <#@ Assembly Name="System.Core.dll" #> @@ -35,11 +35,11 @@ using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; #if FEATURE_TAP using System.Threading; @@ -722,4 +722,4 @@ private static string ContextArgument( bool withContet ) return withContet ? "context" : "SerializationContext.Default"; } -#> \ No newline at end of file +#> diff --git a/src/MsgPack/PackerUnpackerStreamOptions.cs b/src/MsgPack/PackerUnpackerStreamOptions.cs index 81fda29b3..9500851db 100644 --- a/src/MsgPack/PackerUnpackerStreamOptions.cs +++ b/src/MsgPack/PackerUnpackerStreamOptions.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Collections.Generic; using System.IO; @@ -38,13 +42,65 @@ public sealed class PackerUnpackerStreamOptions "System.IO.FileStream" }; - internal static readonly PackerUnpackerStreamOptions SingletonOwnsStream = +#if DEBUG + private static bool _alwaysWrap = false; + +#if UNITY && DEBUG + public +#else + internal +#endif + static bool AlwaysWrap + { + get { return _alwaysWrap; } + set { _alwaysWrap = value; } + } + +#endif // DEBUG + + private static bool ShouldWrapStream( Stream stream ) + { + return + ( stream != null + && !_knownMemoryOrBufferingStreams.Contains( stream.GetType().FullName ) ) +#if DEBUG + || _alwaysWrap +#endif // DEBUG + ; + } + +#if UNITY && DEBUG + public +#else + internal +#endif + static readonly PackerUnpackerStreamOptions SingletonOwnsStream = new PackerUnpackerStreamOptions { OwnsStream = true }; - internal static readonly PackerUnpackerStreamOptions SingletonForAsync = +#if UNITY && DEBUG + public +#else + internal +#endif + static readonly PackerUnpackerStreamOptions SingletonForAsyncPacking = + // It is OK for serialize to do buffering because we explicitly call FlushAsync for it. new PackerUnpackerStreamOptions { OwnsStream = true, WithBuffering = true }; - internal static readonly PackerUnpackerStreamOptions None = new PackerUnpackerStreamOptions(); + #if UNITY && DEBUG + public +#else + internal +#endif + static readonly PackerUnpackerStreamOptions SingletonForAsyncUnpacking = + // Buffering causes data loss in deserialization because buffered bytes will be gone in a tail of Deserialize(Stream) call. + new PackerUnpackerStreamOptions { OwnsStream = true, WithBuffering = false }; + +#if UNITY && DEBUG + public +#else + internal +#endif + static readonly PackerUnpackerStreamOptions None = new PackerUnpackerStreamOptions(); /// /// Gets or sets a value indicating whether stream should be wrapped with buffering stream. @@ -60,18 +116,18 @@ public sealed class PackerUnpackerStreamOptions /// as long as it has buffered value. /// /// - /// Current built-in implementation uses for buffering, + /// Current built-in implementation uses BufferedStream for buffering, /// and avoid buffering for following in-memory or stream with buffering feature: /// - /// itself. - /// . - /// . - /// which has own internal buffer. + /// System.IO.BufferedStream itself. + /// System.IO.MemoryStream. + /// System.IO.UnmanagedMemoryStream. + /// System.IO.FileStream which has own internal buffer. /// /// /// - /// Logically, it is preferred that you should wrap with yourself for underlying stream - /// for wrapper stream such as , , etc. + /// Logically, it is preferred that you should wrap with System.IO.BufferedStream yourself for underlying stream + /// for wrapper stream such as System.IO.Compression.DeflateStream, System.Security.Cryptography.CryptoStream, etc. /// /// /// @@ -115,7 +171,7 @@ internal Stream WrapStream( Stream stream ) } #if !SILVERLIGHT - if ( stream == null || _knownMemoryOrBufferingStreams.Contains( stream.GetType().FullName ) ) + if ( !ShouldWrapStream( stream ) ) { // They have in-memory based synchronous read/write optimization. return stream; @@ -127,4 +183,4 @@ internal Stream WrapStream( Stream stream ) #endif // !SILVERLIGHT } } -} \ No newline at end of file +} diff --git a/src/MsgPack/PreserveAttribute.cs b/src/MsgPack/PreserveAttribute.cs index ad5440b24..c3329b9f3 100644 --- a/src/MsgPack/PreserveAttribute.cs +++ b/src/MsgPack/PreserveAttribute.cs @@ -22,10 +22,12 @@ namespace MsgPack { +#pragma warning disable 0649 // For Unity and Xamarin internal sealed class PreserveAttribute : Attribute { public bool AllMembers; public bool Conditional; } +#pragma warning restore 0649 } diff --git a/src/MsgPack/Properties/AssemblyInfo.cs b/src/MsgPack/Properties/AssemblyInfo.cs index 89b386ff6..7b60a294f 100644 --- a/src/MsgPack/Properties/AssemblyInfo.cs +++ b/src/MsgPack/Properties/AssemblyInfo.cs @@ -22,18 +22,82 @@ using System.Runtime.CompilerServices; using System.Security; -[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )] -[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library." )] +[assembly: AssemblyTitle( "MessagePack for CLI(" + +#if NET4_5 +".NET Framework 4.5" +#elif NET35 +".NET Framework 3.5" +#elif WINDOWS_UWP +"UWP" +#elif NETSTANDARD1_1 +".NET Standard 1.1" +#elif NETSTANDARD1_3 +".NET Standard 1.3" +#elif NETSTANDARD2_0 +".NET Standard 2.0" +#elif XAMARIN && __ANDROID__ +"Xamarin Android" +#elif XAMARIN && __IOS__ +"Xamarin iOS" +#else +".NET Framework 4.6" +#endif // NET4_5.. ++ ")" )] +[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library for" + +#if NET4_5 +".NET Framework 4.5" +#elif NET35 +".NET Framework 3.5" +#elif WINDOWS_UWP +"UWP" +#elif NETSTANDARD1_1 +".NET Standard 1.1" +#elif NETSTANDARD1_3 +".NET Standard 1.3" +#elif NETSTANDARD2_0 +".NET Standard 2.0" +#elif XAMARIN && __ANDROID__ +"Xamarin Android" +#elif XAMARIN && __IOS__ +"Xamarin iOS" +#else +".NET Framework 4.6" +#endif // NET4_5.. + )] -[assembly: AssemblyFileVersion( "0.7.2259.1047" )] +[assembly: AssemblyFileVersion( "0.9.2259.1047" )] +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NET35 [assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )] +#endif // !NET35 [assembly: AllowPartiallyTrustedCallers] +#endif #if DEBUG || PERFORMANCE_TEST [assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] [assembly: InternalsVisibleTo( "MsgPack.UnitTest.CodeDom, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +#if NET35 +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Net35, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.CodeDom.Net35, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +#endif // NET35 [assembly: InternalsVisibleTo( "MsgPack.UnitTest.BclExtensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] -#endif - - +#if XAMARIN && __ANDROID__ +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Packer.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Unpacker.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Unpacking.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.Timestamp.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.ArraySerialization.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPack.UnitTest.MapSerialization.Xamarin.Android, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +#endif // XAMARIN && __ANDROID__ +#if XAMARIN && __IOS__ +[assembly: InternalsVisibleTo( "MsgPackUnitTestXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPackUnitTestPackerXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPackUnitTestUnpackerXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPackUnitTestUnpackingXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPackUnitTestTimestampXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPackUnitTestArraySerializationXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +[assembly: InternalsVisibleTo( "MsgPackUnitTestMapSerializationXamariniOS, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] +#endif // XAMARIN && __IOS__ +#endif // DEBUG || PERFORMANCE_TEST diff --git a/src/MsgPack/ReadValueResult.cs b/src/MsgPack/ReadValueResult.cs new file mode 100644 index 000000000..7b9a647bf --- /dev/null +++ b/src/MsgPack/ReadValueResult.cs @@ -0,0 +1,120 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// An encoded value reading result. + /// + internal enum ReadValueResult + { + // BitMask: + // +-------+------------+------+-----+ + // | 31-24 | 23 - 16 | 15-8 | 7-0 | + // +-------+------------+------+-----+ + // | Flags | (reserved) | TP-C | V-L | + // +-------+------------+------+-----+ + // Flags: + // 7: failure -- indicates read failure + // 6-2: reserved. + // 1: bool -- indicates this type is boolean + // 0: nil -- indicates this type is nil + // So, + // 0x8000FFFF : failure (Unexpected) + // 0x800000C1 : failure (0xC1) + // 0x80000E0F : failure (EoF) + // 0x02000001 : true + // 0x02000000 : false + // 0x01000000 : nil + // 0x00000000-0x0000FFFF : None(15-0 bits are valid) + // other bits are "reserved" + // TP-C: TypeCode[below] + // VL: Value Or Length + // + // TypeCode: + // 0xFF is Faiulre, 0x00 is Immediate + // +---+-----+-----+ + // | 7 | 6-4 | 3-0 | + // +---+-----+-----+ + // | F | Typ | Len | + // +---+-----+-----+ + // F: indicates failure (effectivery "reserved" bit) + // Typ: + // 0000 uint + // 0001 int + // 0010 real + // 0100 bin + // 0101 raw + // 0110 ext + // 1000 arr + // 1001 map + // Len: Length of sucessor length bytes. + // + UInt8Type = ( 0x00 | 0x1 ) << 8, // 0b00000001 << 8 + UInt16Type = ( 0x00 | 0x2 ) << 8, // 0b00000010 << 8 + UInt32Type = ( 0x00 | 0x4 ) << 8, // 0b00000100 << 8 + UInt64Type = ( 0x00 | 0x8 ) << 8, // 0b00001000 << 8 + Int8Type = ( 0x10 | 0x1 ) << 8, // 0b00010001 << 8 + Int16Type = ( 0x10 | 0x2 ) << 8, // 0b00010010 << 8 + Int32Type = ( 0x10 | 0x4 ) << 8, // 0b00010100 << 8 + Int64Type = ( 0x10 | 0x8 ) << 8, // 0b00011000 << 8 + Real32Type = ( 0x20 | 0x4 ) << 8, // 0b00100100 << 8 + Real64Type = ( 0x20 | 0x8 ) << 8, // 0b00100100 << 8 + Bin8Type = ( 0x40 | 0x1 ) << 8, // 0b01010001 << 8 + Bin16Type = ( 0x40 | 0x2 ) << 8, // 0b01010010 << 8 + Bin32Type = ( 0x40 | 0x4 ) << 8, // 0b01010100 << 8 + FixExtType = ( 0x80 | 0x0 ) << 8, // 0b10000000 << 8 + Ext8Type = ( 0x80 | 0x1 ) << 8, // 0b10000001 << 8 + Ext16Type = ( 0x80 | 0x2 ) << 8, // 0b10000010 << 8 + Ext32Type = ( 0x80 | 0x4 ) << 8, // 0b10000100 << 8 + FixArrayType = ( 0xA0 | 0x0 ) << 8, // 0b10100000 << 8 + Array16Type = ( 0xA0 | 0x2 ) << 8, // 0b10100010 << 8 + Array32Type = ( 0xA0 | 0x4 ) << 8, // 0b10100100 << 8 + FixMapType = ( 0xB0 | 0x0 ) << 8, // 0b10110000 << 8 + Map16Type = ( 0xB0 | 0x2 ) << 8, // 0b10110010 << 8 + Map32Type = ( 0xB0 | 0x4 ) << 8, // 0b10110100 << 8 + FixStrType = ( 0xC0 | 0x0 ) << 8, // 0b11000000 << 8 + Str8Type = ( 0xC0 | 0x1 ) << 8, // 0b11000001 << 8 + Str16Type = ( 0xC0 | 0x2 ) << 8, // 0b11000010 << 8 + Str32Type = ( 0xC0 | 0x4 ) << 8, // 0b11000100 << 8 + Nil = 0x1 << 24, // 0x01000000 + False = 0x2 << 24, // 0x02000000 + True = ( 0x2 << 24 ) | 1, // 0x02000001 + // Error + InvalidCode = ( 0x8 << 24 ) | 0xC1, // 0b1000 << 24 | 0xC1 + EoF = ( 0x8 << 24 ) | 0xE0F, // 0b1000 << 24 | 0xE0F // (EoF) + Unexpected = ( 0x8 << 24 ) | 0xFFFF, // 0b1000 << 24 | 0xFFFF + // Mask + NonScalarBitMask = 0x0000C000, + ArrayTypeMask = 0x0000A000, + MapTypeMask = 0x0000B000, + BinTypeMask = 0x00006000, + RawTypeMask = 0x00004000, + ExtTypeMask = 0x00008000, + LengthOfLengthMask = 0x0F << 8, + ValueOrLengthMask = 0xFF, + TypeCodeMask = 0xFF << 8, + FlagsMask = unchecked( ( int )( 0xFF000000 ) ), + FlagsAndTypeCodeMask = FlagsMask | TypeCodeMask, + FlagsAndLengthOfLengthMask = FlagsMask | LengthOfLengthMask + } +} diff --git a/src/MsgPack/ReadValueResults.cs b/src/MsgPack/ReadValueResults.cs new file mode 100644 index 000000000..65085e85d --- /dev/null +++ b/src/MsgPack/ReadValueResults.cs @@ -0,0 +1,390 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Linq; + +namespace MsgPack +{ + /// + /// Static utilities of . + /// + internal static class ReadValueResults + { + // Index = read_header + public static readonly ReadValueResult[] EncodedTypes = + Enumerable.Range( 0, 0x80 ).Select( i => ( ReadValueResult )i ) + .Concat( + Enumerable.Range( 0x80, 0x10 ).Select( i => ( ReadValueResult )( ( i - 0x80 ) | ( uint )ReadValueResult.FixMapType ) ) + ).Concat( + Enumerable.Range( 0x90, 0x10 ).Select( i => ( ReadValueResult )( ( i - 0x90 ) | ( uint )ReadValueResult.FixArrayType ) ) + ).Concat( + Enumerable.Range( 0xA0, 0x20 ).Select( i => ( ReadValueResult )( ( i - 0xA0 ) | ( uint )ReadValueResult.FixStrType ) ) + ).Concat( + new[] + { + ReadValueResult.Nil, + ReadValueResult.InvalidCode, // reserved + ReadValueResult.False, + ReadValueResult.True + } + ).Concat( + new[] + { + ReadValueResult.Bin8Type, + ReadValueResult.Bin16Type, + ReadValueResult.Bin32Type, + ReadValueResult.Ext8Type, + ReadValueResult.Ext16Type, + ReadValueResult.Ext32Type, + ReadValueResult.Real32Type, + ReadValueResult.Real64Type, + ReadValueResult.UInt8Type, + ReadValueResult.UInt16Type, + ReadValueResult.UInt32Type, + ReadValueResult.UInt64Type, + ReadValueResult.Int8Type, + ReadValueResult.Int16Type, + ReadValueResult.Int32Type, + ReadValueResult.Int64Type, + ( ReadValueResult )( ( int )ReadValueResult.FixExtType | 0x1 ), + ( ReadValueResult )( ( int )ReadValueResult.FixExtType | 0x2 ), + ( ReadValueResult )( ( int )ReadValueResult.FixExtType | 0x4 ), + ( ReadValueResult )( ( int )ReadValueResult.FixExtType | 0x8 ), + ( ReadValueResult )( ( int )ReadValueResult.FixExtType | 0x10 ), + ReadValueResult.Str8Type, + ReadValueResult.Str16Type, + ReadValueResult.Str32Type, + ReadValueResult.Array16Type, + ReadValueResult.Array32Type, + ReadValueResult.Map16Type, + ReadValueResult.Map32Type + } + ).Concat( + Enumerable.Range( 0xE0, 0x20 ).Select( b => ( ReadValueResult )b ) + ).ToArray(); + + public static readonly bool[] HasConstantObject = + Enumerable.Repeat( true, 0x80 ) // Positive fix num + .Concat( + Enumerable.Repeat( true, 0x10 ) // FixMap + ).Concat( + Enumerable.Repeat( true, 0x10 ) // FixArray + ).Concat( + Enumerable.Repeat( false, 0x20 ) // FixRaw + ).Concat( + new[] + { + true, // Nil, + false, // reserved + true, // False, + true, // True + } + ).Concat( + Enumerable.Repeat( false, 28 ) // all false -- variable lengthes + ).Concat( + Enumerable.Repeat( true, 0x20 ) // Negative fix num + ).ToArray(); + + public static readonly MessagePackObject[] ContantObject = + Enumerable.Range( 0, 0x80 ).Select( x => new MessagePackObject( x ) ) // Positive fix num + .Concat( + Enumerable.Range( 0, 0x10 ).Select( x => new MessagePackObject( x ) ) // FixMap + ).Concat( + Enumerable.Range( 0, 0x10 ).Select( x => new MessagePackObject( x ) ) // FixArray + ).Concat( + Enumerable.Repeat( default( MessagePackObject ), 0x20 ) // FixRaw + ).Concat( + new[] + { + MessagePackObject.Nil, // Nil, + default( MessagePackObject ), // reserved + new MessagePackObject( false ), // False, + new MessagePackObject( true ), // True + } + ).Concat( + Enumerable.Repeat( default( MessagePackObject ), 28 ) // all false -- variable lengthes + ).Concat( + Enumerable.Range( -32, 0x20 ).Select( x => new MessagePackObject( x ) ) // Negative fix num + ).ToArray(); + + public static readonly CollectionType[] CollectionType = + Enumerable.Repeat( MsgPack.CollectionType.None, 0x80 ) // Positive fix num + .Concat( + Enumerable.Repeat( MsgPack.CollectionType.Map, 0x10 ) // FixMap + ).Concat( + Enumerable.Repeat( MsgPack.CollectionType.Array, 0x10 ) // FixArray + ).Concat( + Enumerable.Repeat( MsgPack.CollectionType.None, 0x20 ) // FixRaw + ).Concat( + new[] + { + MsgPack.CollectionType.None, // Nil, + MsgPack.CollectionType.None, // reserved + MsgPack.CollectionType.None, // False, + MsgPack.CollectionType.None, // True + } + ).Concat( + new[] + { + MsgPack.CollectionType.None, // Bin8 + MsgPack.CollectionType.None, // Bin16 + MsgPack.CollectionType.None, // Bin32 + MsgPack.CollectionType.None, // Ext8 + MsgPack.CollectionType.None, // Ext16 + MsgPack.CollectionType.None, // Ext32 + MsgPack.CollectionType.None, // Real32 + MsgPack.CollectionType.None, // Real64 + MsgPack.CollectionType.None, // UInt8 + MsgPack.CollectionType.None, // UInt16 + MsgPack.CollectionType.None, // UInt32 + MsgPack.CollectionType.None, // UInt64 + MsgPack.CollectionType.None, // Int8 + MsgPack.CollectionType.None, // Int16 + MsgPack.CollectionType.None, // Int32 + MsgPack.CollectionType.None, // Int64 + MsgPack.CollectionType.None, // FixExt1 + MsgPack.CollectionType.None, // FixExt2 + MsgPack.CollectionType.None, // FixExt4 + MsgPack.CollectionType.None, // FixExt8 + MsgPack.CollectionType.None, // FixExt16 + MsgPack.CollectionType.None, // Str8 + MsgPack.CollectionType.None, // Str16 + MsgPack.CollectionType.None, // Str32 + MsgPack.CollectionType.Array, // Array16 + MsgPack.CollectionType.Array, // Array32 + MsgPack.CollectionType.Map, // Map16 + MsgPack.CollectionType.Map, // Map32 + } + ).Concat( + Enumerable.Repeat( MsgPack.CollectionType.None, 0x20 ) // Negative fix num + ).ToArray(); + + public static byte ToByte( this ReadValueResult source ) + { + switch ( source ) + { + case ReadValueResult.Nil: + { + return ( byte )MessagePackCode.NilValue; + } + case ReadValueResult.True: + { + return ( byte )MessagePackCode.TrueValue; + } + case ReadValueResult.False: + { + return ( byte )MessagePackCode.FalseValue; + } + case ReadValueResult.InvalidCode: + { + return 0xC1; + } + } + + if ( ( source & ReadValueResult.FlagsAndTypeCodeMask ) == 0 ) + { + return ( byte )( ( int )( source & ReadValueResult.ValueOrLengthMask ) ); + } + + if ( ( source & ReadValueResult.ArrayTypeMask ) == ReadValueResult.ArrayTypeMask ) + { + var length = ( int )( source & ReadValueResult.LengthOfLengthMask ) >> 8; + switch ( length ) + { + case 0: + { + return ( byte )( MessagePackCode.MinimumFixedArray | ( int )( source & ReadValueResult.ValueOrLengthMask ) ); + } + case 2: + { + return ( byte )MessagePackCode.Array16; + } + default: + { +#if DEBUG + Contract.Assert( length == 4, length + " == 4" ); +#endif // DEBUG + return ( byte )MessagePackCode.Array32; + } + } + } + + if ( ( source & ReadValueResult.MapTypeMask ) == ReadValueResult.MapTypeMask ) + { + var length = ( int )( source & ReadValueResult.LengthOfLengthMask ) >> 8; + switch ( length ) + { + case 0: + { + return ( byte )( MessagePackCode.MinimumFixedMap | ( int )( source & ReadValueResult.ValueOrLengthMask ) ); + } + case 2: + { + return ( byte )MessagePackCode.Map16; + } + default: + { +#if DEBUG + Contract.Assert( length == 4, length + " == 4" ); +#endif // DEBUG + return ( byte )MessagePackCode.Map32; + } + } + } + + if ( ( source & ReadValueResult.RawTypeMask ) == ReadValueResult.RawTypeMask ) + { + var isBin = ( source & ReadValueResult.BinTypeMask ) == ReadValueResult.BinTypeMask; + var length = ( int )( source & ReadValueResult.LengthOfLengthMask ) >> 8; + switch ( length ) + { + case 0: + { + return ( byte )( MessagePackCode.MinimumFixedRaw | ( int )( source & ReadValueResult.ValueOrLengthMask ) ); + } + case 1: + { + return ( byte )( isBin ? MessagePackCode.Bin8 : MessagePackCode.Str8 ); + } + case 2: + { + return ( byte )( isBin ? MessagePackCode.Bin16 : MessagePackCode.Str16 ); + } + default: + { +#if DEBUG + Contract.Assert( length == 4, length + " == 4" ); +#endif // DEBUG + return ( byte )( isBin ? MessagePackCode.Bin32 : MessagePackCode.Str32 ); + } + } + } + + if ( ( source & ReadValueResult.ExtTypeMask ) == ReadValueResult.ExtTypeMask ) + { + var length = ( int )( source & ReadValueResult.LengthOfLengthMask ) >> 8; + switch ( length ) + { + case 0: + { + switch ( ( int )( source & ReadValueResult.ValueOrLengthMask ) ) + { + case 1: + { + return ( byte )MessagePackCode.FixExt1; + } + case 2: + { + return ( byte )MessagePackCode.FixExt2; + } + case 4: + { + return ( byte )MessagePackCode.FixExt4; + } + case 8: + { + return ( byte )MessagePackCode.FixExt8; + } + default: + { +#if DEBUG + Contract.Assert( ( int )( source & ReadValueResult.ValueOrLengthMask ) == 16, ( int )( source & ReadValueResult.ValueOrLengthMask ) + " == 16" ); +#endif // DEBUG + return ( byte )MessagePackCode.FixExt16; + } + } + } + case 1: + { + return ( byte )MessagePackCode.Ext8; + } + case 2: + { + return ( byte )MessagePackCode.Ext16; + } + default: + { +#if DEBUG + Contract.Assert( length == 4, length + " == 4" ); +#endif // DEBUG + return ( byte )MessagePackCode.Ext32; + } + } + } + + switch ( source & ReadValueResult.TypeCodeMask ) + { + case ReadValueResult.Int8Type: + { + return ( byte )MessagePackCode.SignedInt8; + } + case ReadValueResult.Int16Type: + { + return ( byte )MessagePackCode.SignedInt16; + } + case ReadValueResult.Int32Type: + { + return ( byte )MessagePackCode.SignedInt32; + } + case ReadValueResult.Int64Type: + { + return ( byte )MessagePackCode.SignedInt64; + } + case ReadValueResult.UInt8Type: + { + return ( byte )MessagePackCode.UnsignedInt8; + } + case ReadValueResult.UInt16Type: + { + return ( byte )MessagePackCode.UnsignedInt16; + } + case ReadValueResult.UInt32Type: + { + return ( byte )MessagePackCode.UnsignedInt32; + } + case ReadValueResult.UInt64Type: + { + return ( byte )MessagePackCode.UnsignedInt64; + } + case ReadValueResult.Real32Type: + { + return ( byte )MessagePackCode.Real32; + } + default: + { +#if DEBUG + Contract.Assert( ( source & ReadValueResult.TypeCodeMask ) == ReadValueResult.Real64Type, ( source & ReadValueResult.TypeCodeMask ) + " == ReadValueResult.Real64Type" ); +#endif // DEBUG + return ( byte )MessagePackCode.Real64; + } + } + } + } +} diff --git a/src/MsgPack/ReflectionAbstractions.cs b/src/MsgPack/ReflectionAbstractions.cs index 580e187a2..7bfe82be5 100644 --- a/src/MsgPack/ReflectionAbstractions.cs +++ b/src/MsgPack/ReflectionAbstractions.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,17 +25,22 @@ using System; using System.Collections.Generic; using System.Diagnostics; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; using System.Reflection; namespace MsgPack { - internal static class ReflectionAbstractions +#if UNITY && DEBUG + public +#else + internal +#endif + static class ReflectionAbstractions { [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate", Justification = "Same as FCL" )] public static readonly char TypeDelimiter = '.'; @@ -134,6 +139,16 @@ public static bool GetIsPublic( this Type source ) #endif // NETSTANDARD1_1 || NETSTANDARD1_3 } + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Wrong detection" )] + public static bool GetIsNestedPublic( this Type source ) + { +#if NETSTANDARD1_1 || NETSTANDARD1_3 + return source.GetTypeInfo().IsNestedPublic; +#else + return source.IsNestedPublic; +#endif // NETSTANDARD1_1 || NETSTANDARD1_3 + } + #if DEBUG public static bool GetIsPrimitive( this Type source ) { @@ -198,17 +213,17 @@ public static MethodInfo GetRuntimeMethod( this Type source, string name, Type[] return source.GetRuntimeMethods() .SingleOrDefault( - m => m.Name == name && m.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameters ) + m => m.IsPublic && m.Name == name && m.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameters ) ); } -#else +#else // NETSTANDARD1_1 || NETSTANDARD1_3 public static MethodInfo GetRuntimeMethod( this Type source, string name, Type[] parameters ) { return source.GetMethod( name, - BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, + BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, parameters, null @@ -223,7 +238,6 @@ public static IEnumerable GetRuntimeMethods( this Type source ) ); } -#if DEBUG public static PropertyInfo GetRuntimeProperty( this Type source, string name ) { return @@ -232,8 +246,15 @@ public static PropertyInfo GetRuntimeProperty( this Type source, string name ) BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic ); } -#endif // DEBUG +#if NET35 || SILVERLIGHT + public static IEnumerable GetRuntimeProperties( this Type source ) + { + return source.GetProperties( BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic ); + } +#endif // NET35 || SILVERLIGHT + +#if DEBUG public static FieldInfo GetRuntimeField( this Type source, string name ) { return @@ -242,6 +263,7 @@ public static FieldInfo GetRuntimeField( this Type source, string name ) BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic ); } +#endif // DEBUG #endif // NETSTANDARD1_1 || NETSTANDARD1_3 @@ -254,7 +276,7 @@ public static ConstructorInfo GetRuntimeConstructor( this Type source, Type[] pa #endif // NETSTANDARD1_1 || NETSTANDARD1_3 } -#if NETFX_35 || NETFX_40 || SILVERLIGHT +#if NET35 || NET40 || SILVERLIGHT || UNITY public static Delegate CreateDelegate( this MethodInfo source, Type delegateType ) { return Delegate.CreateDelegate( delegateType, source ); @@ -265,12 +287,12 @@ public static Delegate CreateDelegate( this MethodInfo source, Type delegateType return Delegate.CreateDelegate( delegateType, target, source ); } -#endif // NETFX_35 || NETFX_40 || SILVERLIGHT +#endif // NET35 || NET40 || SILVERLIGHT || UNITY #if NETSTANDARD1_1 || NETSTANDARD1_3 public static MethodInfo GetMethod( this Type source, string name ) { - return source.GetRuntimeMethods().SingleOrDefault( m => m.Name == name && m.DeclaringType == source ); + return source.GetRuntimeMethods().SingleOrDefault( m => m.IsPublic && m.Name == name && m.DeclaringType == source ); } public static MethodInfo GetMethod( this Type source, string name, Type[] parameters ) @@ -389,6 +411,15 @@ public static Type GetAttributeType( this CustomAttributeData source ) public static string GetMemberName( this CustomAttributeNamedArgument source ) { + // This is hack to check null because .NET Standard 1.1 does not expose CustomAttributeNamedArgument.MemberInfo + // but it still throws NullReferenceException when its private MemberInfo type field is null. + // This is caused by default instance of CustomAttributeNamedArgument, so it also should have default CustomAttributeTypedArgument + // which has null ArgumentType. + if ( source.TypedValue.ArgumentType == null ) + { + return null; + } + return source.MemberName; } #else @@ -398,12 +429,12 @@ public static T GetCustomAttribute( this MemberInfo source ) return Attribute.GetCustomAttribute( source, typeof( T ) ) as T; } -#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY +#if NET35 || NET40 || SILVERLIGHT || UNITY public static bool IsDefined( this MemberInfo source, Type attributeType ) { return Attribute.IsDefined( source, attributeType ); } -#endif // NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY +#endif // NET35 || NET40 || SILVERLIGHT || UNITY #if !SILVERLIGHT public static Type GetAttributeType( this CustomAttributeData source ) @@ -413,6 +444,11 @@ public static Type GetAttributeType( this CustomAttributeData source ) public static string GetMemberName( this CustomAttributeNamedArgument source ) { + if ( source.MemberInfo == null ) + { + return null; + } + return source.MemberInfo.Name; } @@ -426,14 +462,14 @@ public static Type GetAttributeType( this Attribute source ) public static string GetCultureName( this AssemblyName source ) { -#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY - return source.CultureInfo.Name; +#if NET35 || NET40 || SILVERLIGHT || UNITY + return source.CultureInfo == null ? null : source.CultureInfo.Name; #else return source.CultureName; #endif } -#if NETFX_35 || UNITY +#if NET35 || UNITY public static IEnumerable GetCustomAttributesData( this MemberInfo source ) { return CustomAttributeData.GetCustomAttributes( source ); @@ -443,7 +479,7 @@ public static IEnumerable GetCustomAttributesData( this Par { return CustomAttributeData.GetCustomAttributes( source ); } -#endif // NETFX_35 || UNITY +#endif // NET35 || UNITY #if NETSTANDARD1_1 || NETSTANDARD1_3 public static IEnumerable GetCustomAttributesData( this ParameterInfo source ) @@ -467,6 +503,11 @@ public static IEnumerable GetNamedArguments( this Attribute attri .Select( m => new NamedArgument( attribute, m ) ); } #else + public static IList GetConstructorArguments( this CustomAttributeData source ) + { + return source.ConstructorArguments; + } + public static IEnumerable GetNamedArguments( this CustomAttributeData source ) { return source.NamedArguments; @@ -522,7 +563,7 @@ public KeyValuePair GetTypedValue() public static bool GetHasDefaultValue( this ParameterInfo source ) { -#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY +#if NET35 || NET40 || SILVERLIGHT || UNITY return source.DefaultValue != DBNull.Value; #else return source.HasDefaultValue; diff --git a/src/MsgPack/Serialization/AbstractSerializers/ActionType.cs b/src/MsgPack/Serialization/AbstractSerializers/ActionType.cs index 11dc36ea5..84f1d1706 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/ActionType.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/ActionType.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ internal enum ActionType PackToMap, UnpackFromArray, UnpackFromMap, - UnpackTo + UnpackTo, + IsNull } } \ No newline at end of file diff --git a/src/MsgPack/Serialization/AbstractSerializers/ConstructorDefinition.cs b/src/MsgPack/Serialization/AbstractSerializers/ConstructorDefinition.cs index edf646e3e..b68f3a0ff 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/ConstructorDefinition.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/ConstructorDefinition.cs @@ -20,11 +20,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; @@ -45,8 +45,7 @@ public ConstructorInfo ResolveRuntimeConstructor() this._runtimeConstructor = this.DeclaringType.ResolveRuntimeType().GetConstructors() .SingleOrDefault( c => - c.GetParameters() - .Select( p => p.ParameterType ) + c.GetParameterTypes() .SequenceEqual( this.ParameterTypes.Select( t => t.ResolveRuntimeType() ) ) ); } diff --git a/src/MsgPack/Serialization/AbstractSerializers/DynamicUnpackingContext.cs b/src/MsgPack/Serialization/AbstractSerializers/DynamicUnpackingContext.cs deleted file mode 100644 index cb1d6197e..000000000 --- a/src/MsgPack/Serialization/AbstractSerializers/DynamicUnpackingContext.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2015 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -#if FEATURE_TAP -using System.Threading; -#endif // FEATURE_TAP - -namespace MsgPack.Serialization.AbstractSerializers -{ - internal class DynamicUnpackingContext - { - private readonly Dictionary _bag; - - public object Get( string key ) - { - object result; - this._bag.TryGetValue( key, out result ); - return result; - } - - public void Set( string key, object value ) - { - this._bag[ key ] = value; - } - -#if FEATURE_TAP - - public CancellationToken CancellationToken - { - get; - private set; - } - -#endif // FEATURE_TAP - - public DynamicUnpackingContext( int capacity ) - { - this._bag = new Dictionary( capacity ); - } - -#if FEATURE_TAP - public DynamicUnpackingContext( int capacity, CancellationToken cancellationToken ) - :this( capacity ) - { - this.CancellationToken = cancellationToken; - } -#endif // FEATURE_TAP - } -} \ No newline at end of file diff --git a/src/MsgPack/Serialization/AbstractSerializers/FieldDefinition.cs b/src/MsgPack/Serialization/AbstractSerializers/FieldDefinition.cs index fa818f0f3..2548ceeb6 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/FieldDefinition.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/FieldDefinition.cs @@ -19,11 +19,11 @@ #endregion -- License Terms -- using System; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Reflection; diff --git a/src/MsgPack/Serialization/AbstractSerializers/FieldName.cs b/src/MsgPack/Serialization/AbstractSerializers/FieldName.cs index c11eb66de..2a62a912c 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/FieldName.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/FieldName.cs @@ -26,6 +26,7 @@ internal static class FieldName { public const string PackOperationList = "_packOperationList"; public const string PackOperationTable = "_packOperationTable"; + public const string NullCheckersTable = "_nullCheckersTable"; public const string UnpackOperationList = "_unpackOperationList"; public const string UnpackOperationTable = "_unpackOperationTable"; public const string UnpackTo = "_unpackTo"; diff --git a/src/MsgPack/Serialization/AbstractSerializers/ISerializerCodeGenerationContext.cs b/src/MsgPack/Serialization/AbstractSerializers/ISerializerCodeGenerationContext.cs index 224feaac1..e3e28c698 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/ISerializerCodeGenerationContext.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/ISerializerCodeGenerationContext.cs @@ -33,9 +33,9 @@ internal interface ISerializerCodeGenerationContext /// Generates codes for this context. /// /// A collection which correspond to genereated codes. -#if !NETFX_35 +#if !NET35 [SecuritySafeCritical] -#endif // !NETFX_35 +#endif // !NET35 IEnumerable Generate(); /// @@ -46,9 +46,9 @@ internal interface ISerializerCodeGenerationContext /// SerializationContext SerializationContext { -#if !NETFX_35 +#if !NET35 [SecuritySafeCritical] -#endif // !NETFX_35 +#endif // !NET35 get; } } diff --git a/src/MsgPack/Serialization/AbstractSerializers/MethodDefinition.cs b/src/MsgPack/Serialization/AbstractSerializers/MethodDefinition.cs index 139500355..735dc8207 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/MethodDefinition.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/MethodDefinition.cs @@ -20,11 +20,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; @@ -91,16 +91,18 @@ private MethodInfo ResolveRuntimeMethodCore( bool throws ) { var foundMethods = this.DeclaringType.ResolveRuntimeType().GetMethods() - .Where( m => m.Name == this.MethodName ) + // This filter is naive but works now. + .Where( m => m.Name == this.MethodName && m.GetParameters().Length == this.ParameterTypes.Length ) .ToArray(); if ( foundMethods.Length != 1 ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, - "Failed to get runtime method of '{0}.{1}'.", + "Failed to get runtime method of '{0}.{1}({2})'.", this.DeclaringType.ResolveRuntimeType(), - this.MethodName + this.MethodName, + String.Join( ", ", this.ParameterTypes.Select( t => t.ToString() ).ToArray() ) ) ); } @@ -108,6 +110,13 @@ private MethodInfo ResolveRuntimeMethodCore( bool throws ) result = foundMethods[ 0 ]; } +#if DEBUG + Contract.Assert( + !result.IsGenericMethodDefinition || result.GetGenericArguments().Length == this._genericArguments.Length, + result + " == <" + String.Join( ", ", this._genericArguments.Select( t => t.ToString() ).ToArray() ) + ">" + ); +#endif // DEBUG + this._resoolvedMethod = result.IsGenericMethodDefinition ? result.MakeGenericMethod( this._genericArguments.Select( t => t.ResolveRuntimeType() ).ToArray() ) @@ -119,11 +128,13 @@ private MethodInfo ResolveRuntimeMethodCore( bool throws ) public readonly TypeDefinition DeclaringType; public readonly TypeDefinition ReturnType; public readonly TypeDefinition[] ParameterTypes; + public readonly bool IsStatic; - public MethodDefinition( string name, TypeDefinition[] genericArguments, TypeDefinition declaringType, TypeDefinition returnType, params TypeDefinition[] parameterTypes ) + public MethodDefinition( string name, TypeDefinition[] genericArguments, TypeDefinition declaringType, bool isStatic, TypeDefinition returnType, params TypeDefinition[] parameterTypes ) { this.MethodName = name; this.DeclaringType = declaringType; + this.IsStatic = isStatic; this._runtimeMethod = null; this._genericArguments = genericArguments; this.ReturnType = returnType; @@ -143,6 +154,7 @@ public MethodDefinition( MethodInfo runtimeMethod, Type @interface, IEnumerable< #endif // DEBUG this.MethodName = runtimeMethod.Name; this.DeclaringType = runtimeMethod.DeclaringType; + this.IsStatic = runtimeMethod.IsStatic; this._runtimeMethod = runtimeMethod; this.ReturnType = runtimeMethod.ReturnType; this.ParameterTypes = parameterTypes.ToArray(); diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Collection.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Collection.cs index a55a72e3a..bb249c913 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Collection.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Collection.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,19 +16,22 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; +using System.Reflection; #if FEATURE_TAP using System.Threading; -using System.Threading.Tasks; #endif // FEATURE_TAP namespace MsgPack.Serialization.AbstractSerializers @@ -39,7 +42,8 @@ partial class SerializerBuilder private void BuildCollectionSerializer( TContext context, Type concreteType, - PolymorphismSchema schema + PolymorphismSchema schema, + out SerializationTarget targetInfo ) { #if DEBUG @@ -47,7 +51,7 @@ PolymorphismSchema schema #endif // DEBUG bool isUnpackFromRequired; bool isAddItemRequired; - this.DetermineSerializationStrategy( out isUnpackFromRequired, out isAddItemRequired ); + this.DetermineSerializationStrategy( context, concreteType, out targetInfo, out isUnpackFromRequired, out isAddItemRequired ); if ( typeof( IPackable ).IsAssignableFrom( this.TargetType ) ) { @@ -65,13 +69,13 @@ PolymorphismSchema schema #endif // FEATURE_TAP - this.BuildCollectionCreateInstance( context, concreteType ); + this.BuildCollectionCreateInstance( context, targetInfo.DeserializationConstructor, targetInfo.CanDeserialize ); var useUnpackable = false; if ( typeof( IUnpackable ).IsAssignableFrom( concreteType ?? this.TargetType ) ) { - this.BuildIUnpackableUnpackFrom( context, this.GetUnpackableCollectionInstantiation( context ) ); + this.BuildIUnpackableUnpackFrom( context, this.GetUnpackableCollectionInstantiation( context ), targetInfo.CanDeserialize ); useUnpackable = true; } @@ -81,7 +85,7 @@ PolymorphismSchema schema { if ( typeof( IAsyncUnpackable ).IsAssignableFrom( concreteType ?? this.TargetType ) ) { - this.BuildIAsyncUnpackableUnpackFrom( context, this.GetUnpackableCollectionInstantiation( context ) ); + this.BuildIAsyncUnpackableUnpackFrom( context, this.GetUnpackableCollectionInstantiation( context ), targetInfo.CanDeserialize ); useUnpackable = true; } } @@ -90,7 +94,7 @@ PolymorphismSchema schema if ( isAddItemRequired ) { - if ( useUnpackable ) + if ( useUnpackable || !targetInfo.CanDeserialize ) { // AddItem should never called because UnpackFromCore calls IUnpackable/IAsyncUnpackable this.BuildCollectionAddItemNotImplemented( context ); @@ -102,18 +106,18 @@ PolymorphismSchema schema context, this.CollectionTraits.AddMethod != null ? this.CollectionTraits // For declared collection. - : ( concreteType ?? this.TargetType ).GetCollectionTraits( CollectionTraitOptions.Full ) // For concrete collection. + : ( concreteType ?? this.TargetType ).GetCollectionTraits( CollectionTraitOptions.Full, context.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) // For concrete collection. ); } } if ( isUnpackFromRequired && !useUnpackable ) { - this.BuildCollectionUnpackFromCore( context, concreteType, schema, false ); + this.BuildCollectionUnpackFromCore( context, concreteType, schema, targetInfo.CanDeserialize, isAsync: false ); #if FEATURE_TAP if ( this.WithAsync( context ) ) { - this.BuildCollectionUnpackFromCore( context, concreteType, schema, true ); + this.BuildCollectionUnpackFromCore( context, concreteType, schema, targetInfo.CanDeserialize, isAsync: true ); } #endif // FEATURE_TAP } @@ -121,8 +125,20 @@ PolymorphismSchema schema this.BuildRestoreSchema( context, schema ); } - private void DetermineSerializationStrategy( out bool isUnpackFromRequired, out bool isAddItemRequired ) + private void DetermineSerializationStrategy( + TContext context, + Type concreteType, + out SerializationTarget targetInfo, + out bool isUnpackFromRequired, + out bool isAddItemRequired + ) { + targetInfo = + UnpackHelpers.DetermineCollectionSerializationStrategy( + concreteType ?? this.TargetType, + context.SerializationContext.CompatibilityOptions.AllowAsymmetricSerializer + ); + switch ( this.CollectionTraits.DetailedCollectionType ) { case CollectionDetailedKind.NonGenericEnumerable: @@ -156,7 +172,7 @@ private void DetermineSerializationStrategy( out bool isUnpackFromRequired, out isAddItemRequired = false; break; } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyDictionary: { isUnpackFromRequired = false; @@ -170,7 +186,7 @@ private void DetermineSerializationStrategy( out bool isUnpackFromRequired, out isAddItemRequired = true; break; } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) default: { isUnpackFromRequired = false; @@ -196,6 +212,7 @@ private TConstruct GetUnpackableCollectionInstantiation( TContext context ) private void BuildCollectionAddItem( TContext context, CollectionTraits traits ) { var addItem = this.BaseClass.GetRuntimeMethod( MethodName.AddItem ); + var addItemParametersTypes = addItem.GetParameterTypes(); context.BeginMethodOverride( MethodName.AddItem ); context.EndMethodOverride( MethodName.AddItem, @@ -204,9 +221,9 @@ private void BuildCollectionAddItem( TContext context, CollectionTraits traits ) context, traits, context.CollectionToBeAdded, - addItem.GetParameters()[ 0 ].ParameterType, + addItemParametersTypes[ 0 ], context.KeyToAdd, - addItem.GetParameters()[ 1 ].ParameterType, + addItemParametersTypes[ 1 ], context.ValueToAdd, false ) @@ -225,7 +242,7 @@ private void BuildCollectionAddItemNotImplemented( TContext context ) context.BeginMethodOverride( MethodName.AddItem ); context.EndMethodOverride( MethodName.AddItem, - this.EmitSequentialStatements( context, typeof( void ) ) // nop + this.EmitSequentialStatements( context, TypeDefinition.VoidType ) // nop ); } @@ -233,7 +250,7 @@ private void BuildCollectionAddItemNotImplemented( TContext context ) #region -- UnpackFromCore -- - private void BuildCollectionUnpackFromCore( TContext context, Type concreteType, PolymorphismSchema schema, bool isAsync ) + private void BuildCollectionUnpackFromCore( TContext context, Type concreteType, PolymorphismSchema schema, bool canDeserialize, bool isAsync ) { var methodName = #if FEATURE_TAP @@ -247,11 +264,12 @@ private void BuildCollectionUnpackFromCore( TContext context, Type concreteType, context.EndMethodOverride( methodName, - this.EmitSequentialStatements( + canDeserialize + ? this.EmitSequentialStatements( context, this.TargetType, this.EmitCollectionUnpackFromStatements( context, instanceType, schema, isAsync ) - ) + ) : this.EmitThrowCannotUnpackFrom( context ) ); } @@ -263,7 +281,7 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con ? this.EmitCheckIsArrayHeaderExpression( context, context.Unpacker ) : this.EmitCheckIsMapHeaderExpression( context, context.Unpacker ); - var itemsCount = this.DeclareLocal( context, typeof( int ), "itemsCount" ); + var itemsCount = this.DeclareLocal( context, TypeDefinition.Int32Type, "itemsCount" ); // Unpack items count and store it yield return itemsCount; @@ -292,15 +310,15 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con if ( this.CollectionTraits.CollectionType == CollectionKind.Array && this.CollectionTraits.AddMethod == null ) { // Try to use concrete collection's Add. - var traitsOfTheCollection = instanceType.GetCollectionTraits( CollectionTraitOptions.Full ); + var traitsOfTheCollection = instanceType.GetCollectionTraits( CollectionTraitOptions.Full, context.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes); bulk = this.MakeNullLiteral( context, #if FEATURE_TAP - isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,> ), typeof( Unpacker ), this.TargetType, typeof( int ), typeof( CancellationToken ), typeof( Task ) ) : + isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type, TypeDefinition.CancellationTokenType, TypeDefinition.TaskType ) : #endif // FEATURE_TAP - TypeDefinition.GenericReferenceType( typeof( Action<,,> ), typeof( Unpacker ), this.TargetType, typeof( int ) ) + TypeDefinition.GenericReferenceType( typeof( Action<,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type ) ); var indexOfItemParameter = context.IndexOfItem; @@ -318,10 +336,11 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con this.ExtractPrivateMethod( context, AdjustName( MethodName.UnpackCollectionItem, isAsync ), + false, // isStatic #if FEATURE_TAP - isAsync ? typeof( Task ) : + isAsync ? TypeDefinition.TaskType : #endif // FEATURE_TAP - typeof( void ), + TypeDefinition.VoidType, () => this.EmitUnpackItemValueStatement( context, traitsOfTheCollection.ElementType, @@ -336,7 +355,8 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con this.ExtractPrivateMethod( context, MethodName.AppendUnpackedItem, - typeof( void ), + false, // isStatic + TypeDefinition.VoidType, () => this.EmitAppendCollectionItem( context, null, @@ -347,7 +367,6 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con appendToTargetParameter, unpackedItemParameter ), - true, // forMap, this method should not be called IDictionary[<,>] isAsync ), unpackItemValueArguments @@ -362,18 +381,42 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con this.MakeNullLiteral( context, #if FEATURE_TAP - isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,,> ), typeof( Unpacker ), this.TargetType, typeof( int ), typeof( int ), typeof( CancellationToken ), typeof( Task ) ) : + isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type, TypeDefinition.Int32Type, TypeDefinition.CancellationTokenType, TypeDefinition.TaskType ) : #endif // FEATURE_TAP - TypeDefinition.GenericReferenceType( typeof( Action<,,,> ), typeof( Unpacker ), this.TargetType, typeof( int ), typeof( int ) ) + TypeDefinition.GenericReferenceType( typeof( Action<,,,> ), TypeDefinition.UnpackerType, this.TargetType, TypeDefinition.Int32Type, TypeDefinition.Int32Type ) ); } - var arguments = - new[] { context.Unpacker, itemsCount, collection, bulk, iterative } + var unpackHelperArguments = + new Dictionary + { + { "Unpacker", context.Unpacker }, + { "ItemsCount", itemsCount }, + { "Collection", collection }, + { "BulkOperation", bulk }, + { "EachOperation", iterative }, + }; #if FEATURE_TAP - .Concat( isAsync ? new[] { this.ReferCancellationToken( context, 2 ) } : NoConstructs ).ToArray() + if ( isAsync ) + { + unpackHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 2 ) ); + } #endif // FEATURE_TAP - ; + + var unpackHelperParametersType = + ( +#if FEATURE_TAP + isAsync ? typeof( UnpackCollectionAsyncParameters<> ) : +#endif // FEATURE_TAP + typeof( UnpackCollectionParameters<> ) + ).MakeGenericType( this.TargetType ); + + var unpackHelperParameters = this.DeclareLocal( context, unpackHelperParametersType, "unpackHelperParameters" ); + yield return unpackHelperParameters; + foreach ( var construct in this.CreatePackUnpackHelperArgumentInitialization( context, unpackHelperParameters, unpackHelperArguments ) ) + { + yield return construct; + } // Call UnpackHelpers yield return @@ -386,7 +429,7 @@ private IEnumerable EmitCollectionUnpackFromStatements( TContext con isAsync ? Metadata._UnpackHelpers.UnpackCollectionAsync_1Method.MakeGenericMethod( this.TargetType ) : #endif // FEATURE_TAP Metadata._UnpackHelpers.UnpackCollection_1Method.MakeGenericMethod( this.TargetType ), - arguments + this.EmitMakeRef( context, unpackHelperParameters ) ) ); } @@ -406,22 +449,21 @@ private TConstruct EmitGetItemsCountExpression( TContext context, TConstruct unp #region -- CreateInstance -- - private void BuildCollectionCreateInstance( TContext context, Type concreteType ) + private void BuildCollectionCreateInstance( TContext context, ConstructorInfo collectionConstructor, bool canDeserialize ) { context.BeginMethodOverride( MethodName.CreateInstance ); - var instanceType = concreteType ?? this.TargetType; var collection = this.DeclareLocal( context, this.TargetType, "collection" ); - var ctor = UnpackHelpers.GetCollectionConstructor( instanceType ); - var ctorArguments = this.DetermineCollectionConstructorArguments( context, ctor ); + context.EndMethodOverride( MethodName.CreateInstance, - this.EmitSequentialStatements( + canDeserialize + ? this.EmitSequentialStatements( context, this.TargetType, collection, @@ -431,15 +473,15 @@ private void BuildCollectionCreateInstance( TContext context, Type concreteType this.EmitCreateNewObjectExpression( context, collection, - ctor, - ctorArguments + collectionConstructor, + this.DetermineCollectionConstructorArguments( context, collectionConstructor ) ) ), this.EmitRetrunStatement( context, this.EmitLoadVariableExpression( context, collection ) ) - ) + ) : this.EmitThrowCannotCreateInstance( context ) ); } @@ -449,19 +491,19 @@ private void BuildCollectionCreateInstance( TContext context, Type concreteType private void BuildRestoreSchema( TContext context, PolymorphismSchema schema ) { - context.BeginPrivateMethod( MethodName.RestoreSchema, true, typeof( PolymorphismSchema ) ); + context.BeginPrivateMethod( MethodName.RestoreSchema, true, TypeDefinition.PolymorphismSchemaType ); var storage = this.DeclareLocal( context, - typeof( PolymorphismSchema ), + TypeDefinition.PolymorphismSchemaType , "schema" ); context.EndPrivateMethod( MethodName.RestoreSchema, this.EmitSequentialStatements( context, - typeof( PolymorphismSchema ), + TypeDefinition.PolymorphismSchemaType, new[] { storage } .Concat( this.EmitConstructPolymorphismSchema( context, storage, schema ) ) .Concat( new[] { this.EmitRetrunStatement( context, this.EmitLoadVariableExpression( context, storage ) ) } ) @@ -484,7 +526,7 @@ protected internal TConstruct EmitUnpackToInitialization( TContext context ) context.GetDeclaredField( FieldName.UnpackTo ), this.EmitNewPrivateMethodDelegateExpression( context, - this.BaseClass.GetRuntimeMethod( MethodName.UnpackToCore, parameterTypes ) + this.BaseClass.GetRuntimeMethods().Single( m => m.Name == MethodName.UnpackToCore && m.GetParameterTypes().SequenceEqual( parameterTypes ) ) ) ); @@ -500,11 +542,11 @@ protected internal TConstruct EmitUnpackToInitialization( TContext context ) context.GetDeclaredField( FieldName.UnpackTo + "Async" ), this.EmitNewPrivateMethodDelegateExpression( context, - this.BaseClass.GetRuntimeMethod( MethodName.UnpackToAsyncCore, asyncParameterTypes ) + this.BaseClass.GetRuntimeMethods().Single( m => m.Name == MethodName.UnpackToAsyncCore && m.GetParameterTypes().SequenceEqual( asyncParameterTypes ) ) ) ); - return this.EmitSequentialStatements( context, typeof( void ), initUnpackTo, initAsyncUnpackTo ); + return this.EmitSequentialStatements( context, TypeDefinition.VoidType, initUnpackTo, initAsyncUnpackTo ); } #endif // FEATURE_TAP diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.CommonConstructs.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.CommonConstructs.cs index 0e59884a1..3e93c4982 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.CommonConstructs.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.CommonConstructs.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and constirbutors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,16 +16,19 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; @@ -332,6 +335,18 @@ private TConstruct MakeDecimalLiteral( TContext context, TConstruct targetVariab /// The generated construct. protected abstract TConstruct EmitUnboxAnyExpression( TContext context, TypeDefinition targetType, TConstruct value ); + private TConstruct BoxIfRequired( TContext context, TConstruct instance ) + { + if ( instance.ContextType.ResolveRuntimeType().GetIsValueType() ) + { + return this.EmitBoxExpression( context, instance.ContextType, instance ); + } + else + { + return instance; + } + } + #endregion -- Boxing/Unboxing/Cast -- #region -- Operations -- @@ -415,6 +430,14 @@ protected virtual TConstruct EmitNotEqualsExpression( TContext context, TConstru /// The generated construct. protected abstract TConstruct EmitFieldOfExpression( TContext context, FieldInfo field ); + /// + /// Emits the 'throw' statement. + /// + /// The generation context. + /// The expression to returns an exception. + /// The generated construct. + protected abstract TConstruct EmitThrowStatement( TContext context, TConstruct exception ); + #endregion -- Operations -- #region -- Aggregation -- @@ -484,6 +507,14 @@ protected TConstruct EmitSequentialStatements( TContext context, TypeDefinition /// The generated construct. protected abstract TConstruct EmitStoreVariableStatement( TContext context, TConstruct variable, TConstruct value ); + /// + /// Emits the make ref instruction. + /// + /// The context. + /// The target to be made its managed reference. + /// The managed reference of the . + protected abstract TConstruct EmitMakeRef( TContext context, TConstruct target ); + #endregion -- Args/Locals -- #region -- New -- @@ -702,6 +733,7 @@ protected TConstruct EmitInvokeMethodExpression( /// /// The generation context. /// The name of the private method. + /// true for static method. /// The type of return value. /// The delegate to the factory which returns body of the private method. /// The parameters of the private method. @@ -709,26 +741,40 @@ protected TConstruct EmitInvokeMethodExpression( /// The generated construct which represents delegate creation instruction to call the private method. /// Note that returned value remains in context. /// - private TConstruct ExtractPrivateMethod( TContext context, string name, TypeDefinition returnType, Func bodyFactory, params TConstruct[] parameters ) + private TConstruct ExtractPrivateMethod( TContext context, string name, bool isStatic, TypeDefinition returnType, Func bodyFactory, params TConstruct[] parameters ) + { + return this.EmitGetPrivateMethodDelegateExpression( context, DefinePrivateMethod( context, name, isStatic, returnType, bodyFactory, parameters ) ); + } + + /// + /// Emits specified body as individual private method and returns its metadata. + /// + /// The generation context. + /// The name of the private method. + /// true for static method. + /// The type of return value. + /// The delegate to the factory which returns body of the private method. + /// The parameters of the private method. + /// + /// The generated metadata of the private method. + /// + private static MethodDefinition DefinePrivateMethod( TContext context, string name, bool isStatic, TypeDefinition returnType, Func bodyFactory, params TConstruct[] parameters ) { - MethodDefinition method; if ( context.IsDeclaredMethod( name ) ) { - method = context.GetDeclaredMethod( name ); + return context.GetDeclaredMethod( name ); } else { context.BeginPrivateMethod( name, - false, + isStatic, returnType, parameters - ); + ); - method = context.EndPrivateMethod( name, bodyFactory() ); + return context.EndPrivateMethod( name, bodyFactory() ); } - - return this.EmitGetPrivateMethodDelegateExpression( context, method ); } protected virtual TConstruct EmitGetPrivateMethodDelegateExpression( TContext context, MethodDefinition method ) @@ -826,7 +872,7 @@ private TConstruct EmitGetProperty( TContext context, TConstruct instance, Prope this.EmitMethodOfExpression( context, property.GetGetMethod( true ) ), Metadata._MethodBase.Invoke_2, instance, - this.MakeNullLiteral( context, typeof( object[] ) ) + this.MakeNullLiteral( context, TypeDefinition.ObjectArrayType ) ) ); } @@ -858,7 +904,7 @@ private TConstruct EmitGetField( TContext context, TConstruct instance, FieldDef context, this.EmitFieldOfExpression( context, field.ResolveRuntimeField() ), Metadata._FieldInfo.GetValue, - instance + this.BoxIfRequired( context, instance ) ) ); } @@ -901,7 +947,7 @@ private TConstruct EmitSetMemberValueStatement( TContext context, TConstruct ins } getCollection = this.EmitGetField( context, instance, asField, !asField.GetHasPublicGetter() ); - traits = asField.FieldType.GetCollectionTraits( CollectionTraitOptions.Full ); + traits = asField.FieldType.GetCollectionTraits( CollectionTraitOptions.Full, context.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); } else { @@ -916,7 +962,7 @@ private TConstruct EmitSetMemberValueStatement( TContext context, TConstruct ins } getCollection = this.EmitGetProperty( context, instance, asProperty, !asProperty.GetHasPublicGetter() ); - traits = asProperty.PropertyType.GetCollectionTraits( CollectionTraitOptions.Full ); + traits = asProperty.PropertyType.GetCollectionTraits( CollectionTraitOptions.Full, context.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); } var existent = this.DeclareLocal( context, member.GetMemberValueType(), "existent" ); @@ -1139,7 +1185,7 @@ bool withReflection instance, this.EmitCreateNewArrayExpression( context, - typeof( object ), + TypeDefinition.ObjectType, 1, new[] { @@ -1185,7 +1231,23 @@ bool withReflection { return this.EmitSetField( context, instance, field, value ); } + else if ( instance.ContextType.ResolveRuntimeType().GetIsValueType() ) + { + return this.EmitSetFieldOnValueType( context, instance, field, value ); + } + else + { + return this.EmitSetFieldOnReferenceType( context, instance, field, value ); + } + } + private TConstruct EmitSetFieldOnReferenceType( + TContext context, + TConstruct instance, + FieldDefinition field, + TConstruct value + ) + { /* * _field_of(f).SetValue( instance, value ); */ @@ -1195,9 +1257,42 @@ bool withReflection this.EmitFieldOfExpression( context, field.ResolveRuntimeField() ), Metadata._FieldInfo.SetValue, instance, - value.ContextType.IsValueType - ? this.EmitBoxExpression( context, value.ContextType, value ) - : value + this.BoxIfRequired( context, value ) + ); + } + + private TConstruct EmitSetFieldOnValueType( + TContext context, + TConstruct instance, + FieldDefinition field, + TConstruct value + ) + { + // SetValue takes in an object for the first parameter, meaning that + // the value gets boxed and, therefore, copied. Since it will set + // the field value on the boxed copy, the changes won't be visible + // after the call, hence the need to box/unbox it. + string boxedName = context.GetUniqueVariableName( "boxed" ); + TConstruct boxed = this.DeclareLocal( context, typeof(object), boxedName ); + return + this.EmitSequentialStatements( + context, + typeof( void ), + + // object boxed = instance; + boxed, + this.EmitStoreVariableStatement( context, boxed, this.EmitBoxExpression( context, instance.ContextType, instance ) ), + + // _field_of(f).SetValue( boxed, value ); + this.EmitInvokeVoidMethod( + context, + this.EmitFieldOfExpression( context, field.ResolveRuntimeField() ), + Metadata._FieldInfo.SetValue, + boxed, + this.BoxIfRequired( context, value )), + + // instance = (T)boxed; + this.EmitStoreVariableStatement( context, instance, this.EmitUnboxAnyExpression( context, instance.ContextType, boxed ) ) ); } @@ -1244,7 +1339,8 @@ private IEnumerable EmitPackItemStatements( TConstruct packer, Type itemType, NilImplication nilImplication, - string memberName, TConstruct item, + string memberName, + TConstruct item, SerializingMember? memberInfo, PolymorphismSchema itemsSchema, bool isAsync @@ -1327,145 +1423,165 @@ private TConstruct EmitUnpackItemValueStatement( TConstruct indexOfItem, TConstruct countOfItem, TConstruct setterDelegate, - bool forMap, bool isAsync ) { - MethodDefinition helperMethod; - IEnumerable helperArguments; - if ( memberType == typeof( MessagePackObject ) ) + var typeKind = + memberType == typeof( MessagePackObject ) + ? TypeKind.MessagePackObject + : !memberType.GetIsValueType() + ? TypeKind.ReferenceType + : Nullable.GetUnderlyingType( memberType ) == null + ? TypeKind.ValueType + : TypeKind.NullableType; + + var unpackHelperParameterTypeDefinition = DetermineUnpackHelperMethodParameterTypeDefinition( typeKind, isAsync ); + var unpackHelperParameterType = + typeKind == TypeKind.MessagePackObject + ? TypeDefinition.GenericValueType( unpackHelperParameterTypeDefinition, unpackingContext.ContextType ) + : typeKind == TypeKind.NullableType + ? TypeDefinition.GenericValueType( unpackHelperParameterTypeDefinition, unpackingContext.ContextType, Nullable.GetUnderlyingType( memberType ) ) + : TypeDefinition.GenericValueType( unpackHelperParameterTypeDefinition, unpackingContext.ContextType, memberType ); + + var helperMethod = + new MethodDefinition( + AdjustName( "Unpack" + typeKind + "Value", isAsync ), + typeKind == TypeKind.MessagePackObject + ? new [] { unpackingContext.ContextType } + : typeKind == TypeKind.NullableType + ? new [] { unpackingContext.ContextType, Nullable.GetUnderlyingType( memberType ) } + : new [] { unpackingContext.ContextType, memberType }, + typeof( UnpackHelpers ),// declaring type + true, // isStatic + unpackingContext.ContextType, // return type + TypeDefinition.ManagedReference( unpackHelperParameterType ) + ); + + IDictionary unpackHelperArguments; + if ( typeKind == TypeKind.MessagePackObject ) { - helperMethod = - new MethodDefinition( - AdjustName( "UnpackMessagePackObjectValueFrom" + ( forMap ? "Map" : "Array" ), isAsync ), - new[] { unpackingContext.ContextType }, // generic type argument - typeof( UnpackHelpers ), // declaring type - unpackingContext.ContextType, // return type - // parameter types - typeof( Unpacker ), - unpackingContext.ContextType, - typeof( int ), - typeof( int ), - typeof( Type ), - typeof( string ), - typeof( NilImplication ), - TypeDefinition.GenericReferenceType( - typeof( Action<,> ), - unpackingContext.ContextType, - typeof( MessagePackObject ) - ) - ); - // Unpacker, TContext, int, int, Type, string, NilImplication, Action[, CancellationToken] - helperArguments = - new [] { unpacker, unpackingContext, countOfItem, indexOfItem, memberName, this.MakeEnumLiteral( context, typeof( NilImplication ), nilImplication ), setterDelegate } + unpackHelperArguments = + new Dictionary + { + { "Unpacker", unpacker }, + { "UnpackingContext", unpackingContext }, + { "ItemsCount", countOfItem }, + { "Unpacked", indexOfItem }, + { "MemberName", memberName }, + { "NilImplication", this.MakeEnumLiteral( context, TypeDefinition.NilImplicationType, nilImplication ) }, + { "Setter", setterDelegate } + }; #if FEATURE_TAP - .Concat( isAsync ? new [] { this.ReferCancellationToken( context, 5 ) } : NoConstructs ) + if ( isAsync ) + { + unpackHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 5 ) ); + } #endif // FEATURE_TAP - ; } else { - var directReadMethod = - Metadata._UnpackHelpers.GetDirectUnpackMethod( memberType, isAsync ); - var directReadDelegateType = -#if FEATURE_TAP - isAsync ? typeof( Func<,,,,> ).MakeGenericType( typeof( Unpacker ), typeof( Type ), typeof( String ), typeof( CancellationToken ), typeof( Task<> ).MakeGenericType( memberType ) ) : -#endif // FEATURE_TAP - typeof( Func<,,,> ).MakeGenericType( typeof( Unpacker ), typeof( Type ), typeof( String ), memberType ); - - var helperMethodParameterTypes = - new[] + unpackHelperArguments = + new Dictionary { - typeof( Unpacker ), - unpackingContext.ContextType, - typeof( MessagePackSerializer<> ).MakeGenericType( memberType ), - typeof( int ), - typeof( int ), - typeof( Type ), - typeof( string ), - typeof( NilImplication ) + { "Unpacker", unpacker }, + { "UnpackingContext", unpackingContext }, + { "Serializer", this.EmitGetSerializerExpression( context, memberType, memberInfo, itemsSchema ) }, + { "ItemsCount", countOfItem }, + { "Unpacked", indexOfItem }, + { "TargetObjectType", this.EmitTypeOfExpression( context, memberType ) }, + { "MemberName", memberName } }; - var typeKind = - !memberType.GetIsValueType() - ? "Reference" - : Nullable.GetUnderlyingType( memberType ) == null - ? "Value" - : "Nullable"; - helperMethod = - new MethodDefinition( - "Unpack" + typeKind + "TypeValue" -#if FEATURE_TAP - + ( isAsync ? "Async" : String.Empty ) -#endif // FEATURE_TAP - , new[] { unpackingContext.ContextType, Nullable.GetUnderlyingType( memberType ) ?? memberType }, // generic type argument - typeof( UnpackHelpers ), // declaring type - unpackingContext.ContextType, // return type - // parameter types - helperMethodParameterTypes.Concat( - new[] - { -#if FEATURE_TAP - isAsync - ? TypeDefinition.GenericReferenceType( - typeof( Func<,,,,> ), - typeof( Unpacker ), - typeof( Type ), - typeof( string ), - typeof( CancellationToken ), - typeof( Task<> ).MakeGenericType( memberType ) - ) - : -#endif // FEATURE_TAP - TypeDefinition.GenericReferenceType( - typeof( Func<,,,> ), - typeof( Unpacker ), - typeof( Type ), - typeof( string ), - memberType - ), - TypeDefinition.GenericReferenceType( - typeof( Action<,> ), - unpackingContext.ContextType, - memberType - ) - } - ) + if ( typeKind != TypeKind.ValueType ) + { + unpackHelperArguments.Add( "NilImplication", this.MakeEnumLiteral( context, TypeDefinition.NilImplicationType, nilImplication ) ); + } + + var directReadMethod = Metadata._UnpackHelpers.GetDirectUnpackMethod( memberType, isAsync ); + var directReadDelegateType = #if FEATURE_TAP - .Concat( isAsync ? new TypeDefinition[] { typeof( CancellationToken ) } : Enumerable.Empty() ) + isAsync + ? typeof( Func<,,,,> ).MakeGenericType( typeof( Unpacker ), typeof( Type ), typeof( String ), typeof( CancellationToken ), typeof( Task<> ).MakeGenericType( memberType ) ) : #endif // FEATURE_TAP - .ToArray() - ); + typeof( Func<,,,> ).MakeGenericType( typeof( Unpacker ), typeof( Type ), typeof( String ), memberType ); + unpackHelperArguments.Add( + "DirectRead", + directReadMethod == null + ? this.MakeNullLiteral( context, directReadDelegateType ) + : this.EmitGetStaticDelegateExpression( context, directReadMethod ) + ); + unpackHelperArguments.Add( "Setter", setterDelegate ); - // Unpacker, TContext, MPS int, int, Type, string, NilImplication, Func, Action[, CancellationToken] - helperArguments = - new [] { unpacker, unpackingContext, this.EmitGetSerializerExpression( context, memberType, memberInfo, itemsSchema ), - countOfItem, indexOfItem, this.EmitTypeOfExpression( context, memberType ), memberName }; - if ( typeKind != "Value" ) +#if FEATURE_TAP + if ( isAsync ) { - helperArguments = helperArguments.Concat( new[] { this.MakeEnumLiteral( context, typeof( NilImplication ), nilImplication ) } ); + unpackHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 5 ) ); } +#endif // FEATURE_TAP + } - helperArguments = - helperArguments.Concat( + var unpackHelperParameters = this.DeclareLocal( context, unpackHelperParameterType, "unpackHelperParameters" ); + + return + this.EmitSequentialStatements( + context, + TypeDefinition.VoidType, + new [] { unpackHelperParameters } + .Concat( + this.CreatePackUnpackHelperArgumentInitialization( context, unpackHelperParameters, unpackHelperArguments ) + ).Concat( new [] { - directReadMethod == null - ? this.MakeNullLiteral( context, directReadDelegateType ) - : this.EmitGetStaticDelegateExpression( context, directReadMethod ), - setterDelegate - } + isAsync + ? this.EmitRetrunStatement( context, this.EmitInvokeMethodExpression( context, null, helperMethod, this.EmitMakeRef( context, unpackHelperParameters ) ) ) + : this.EmitInvokeVoidMethod( context, null, helperMethod, this.EmitMakeRef( context, unpackHelperParameters ) ) + } ) + ); + } + + private static Type DetermineUnpackHelperMethodParameterTypeDefinition( TypeKind typeKind, bool isAsync ) + { + switch ( typeKind ) + { + case TypeKind.MessagePackObject: + { + return +#if FEATURE_TAP + isAsync + ? typeof( UnpackMessagePackObjectValueAsyncParameters<> ) : +#endif // FEATURE_TAP + typeof( UnpackMessagePackObjectValueParameters<> ); + } + case TypeKind.ReferenceType: + { + return +#if FEATURE_TAP + isAsync + ? typeof( UnpackReferenceTypeValueAsyncParameters<,> ) : +#endif // FEATURE_TAP + typeof( UnpackReferenceTypeValueParameters<,> ); + } + case TypeKind.ValueType: + { + return +#if FEATURE_TAP + isAsync + ? typeof( UnpackValueTypeValueAsyncParameters<,> ) : +#endif // FEATURE_TAP + typeof( UnpackValueTypeValueParameters<,> ); + } + default: + { + Contract.Assert( typeKind == TypeKind.NullableType, typeKind + " == TypeKind.NullableType" ); + return #if FEATURE_TAP - .Concat( isAsync ? new [] { this.ReferCancellationToken( context, 5 ) } : NoConstructs ) + isAsync + ? typeof( UnpackNullableTypeValueAsyncParameters<,> ) : #endif // FEATURE_TAP - ; + typeof( UnpackNullableTypeValueParameters<,> ); + } } - - return - isAsync - ? this.EmitRetrunStatement( context, this.EmitInvokeMethodExpression( context, null, helperMethod, helperArguments ) ) - : this.EmitInvokeVoidMethod( context, null, helperMethod, helperArguments.ToArray() ); } /// @@ -1547,6 +1663,34 @@ private TConstruct EmitAppendDictionaryItem( TContext context, CollectionTraits ); } + private TConstruct EmitThrowCannotUnpackFrom( TContext context ) + { + return + this.EmitThrowStatement( + context, + this.EmitInvokeMethodExpression( + context, + null, + SerializationExceptions.NewUnpackFromIsNotSupportedMethod, + this.EmitTypeOfExpression( context, this.TargetType ) + ) + ); + } + + private TConstruct EmitThrowCannotCreateInstance( TContext context ) + { + return + this.EmitThrowStatement( + context, + this.EmitInvokeMethodExpression( + context, + null, + SerializationExceptions.NewCreateInstanceIsNotSupportedMethod, + this.EmitTypeOfExpression( context, this.TargetType ) + ) + ); + } + #endregion -- Unpack Constructs -- #region -- Helper Construcs -- @@ -1569,7 +1713,7 @@ private TConstruct EmitInvariantStringFormat( TContext context, string format, p this.MakeStringLiteral( context, format ), this.EmitCreateNewArrayExpression( context, - typeof( object ), + TypeDefinition.ObjectType, arguments.Length, arguments.Select( a => a.ContextType.IsValueType ? this.EmitBoxExpression( context, a.ContextType, a ) : a ) ) @@ -1587,7 +1731,7 @@ private TConstruct EmitInvariantStringFormat( TContext context, string format, p /// /// The serializer reference methodology is implication specific. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected virtual TConstruct EmitGetSerializerExpression( TContext context, Type targetType, @@ -1604,7 +1748,7 @@ PolymorphismSchema itemsSchema Metadata._SerializationContext.GetSerializer1_Parameter_Method.MakeGenericMethod( targetType ), this.EmitBoxExpression( context, - typeof( EnumSerializationMethod ), + TypeDefinition.EnumSerializationMethodType, this.EmitInvokeMethodExpression( context, null, @@ -1613,7 +1757,7 @@ PolymorphismSchema itemsSchema this.EmitTypeOfExpression( context, targetType ), this.MakeEnumLiteral( context, - typeof( EnumMemberSerializationMethod ), + TypeDefinition.EnumMemberSerializationMethodType, memberInfo.Value.GetEnumMemberSerializationMethod() ) ) @@ -1629,7 +1773,7 @@ PolymorphismSchema itemsSchema Metadata._SerializationContext.GetSerializer1_Parameter_Method.MakeGenericMethod( targetType ), this.EmitBoxExpression( context, - typeof( DateTimeConversionMethod ), + TypeDefinition.DateTimeConversionMethodType, this.EmitInvokeMethodExpression( context, null, @@ -1637,7 +1781,7 @@ PolymorphismSchema itemsSchema context.Context, this.MakeEnumLiteral( context, - typeof( DateTimeMemberConversionMethod ), + TypeDefinition.DateTimeMemberConversionMethodType, memberInfo.Value.GetDateTimeMemberConversionMethod() ) ) @@ -1653,7 +1797,7 @@ PolymorphismSchema itemsSchema : PolymorphismSchema.Default ); context.SerializationContext.GetSerializer( targetType, schemaForMember ); - var schema = this.DeclareLocal( context, typeof( PolymorphismSchema ), "__schema" ); + var schema = this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, "__schema" ); return this.EmitSequentialStatements( context, @@ -1718,9 +1862,37 @@ private ConstructorInfo GetDefaultConstructor( Type instanceType ) return ctor; } - #endregion -- Helper Funcs -- + private IEnumerable CreatePackUnpackHelperArgumentInitialization( TContext context, TConstruct helperArguments, IDictionary arguments ) + { + var parameterType = helperArguments.ContextType; - #region -- Collection Helpers -- +#if DEBUG + Contract.Assert( !parameterType.IsRef, parameterType + " is not ref" ); +#endif // DEBUG + Type parameterTypeDefinition; + if ( ( parameterType.TryGetRuntimeType()?.GetIsGenericType() ).GetValueOrDefault() ) + { + parameterTypeDefinition = parameterType.TryGetRuntimeType().GetGenericTypeDefinition(); + } + else + { + Contract.Assert( parameterType.ElementType.TryGetRuntimeType() != null, parameterType + ".ElementType.ElementType(" + parameterType.ElementType.ElementType + " does not have runtime type" ); + Contract.Assert( parameterType.ElementType.TryGetRuntimeType().GetIsGenericTypeDefinition(), parameterType + ".ElementType.ElementType(" + parameterType.ElementType.ElementType + " is not generic type definition" ); + parameterTypeDefinition = parameterType.ElementType.TryGetRuntimeType(); + + } + + foreach ( var argument in arguments ) + { + var field = parameterTypeDefinition.GetField( argument.Key ); + Contract.Assert( field != null, parameterType + "." + argument.Key + " does not exist" ); + yield return this.EmitSetField( context, helperArguments, new FieldDefinition( parameterType, field.Name, field.FieldType ), argument.Value ); + } + } + +#endregion -- Helper Funcs -- + +#region -- Collection Helpers -- /// /// Determines the collection constructor arguments. @@ -1790,21 +1962,21 @@ private TConstruct EmitGetEqualityComparer( TContext context ) case CollectionDetailedKind.GenericCollection: case CollectionDetailedKind.GenericEnumerable: case CollectionDetailedKind.GenericList: -#if !NETFX_35 +#if !NET35 case CollectionDetailedKind.GenericSet: -#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyCollection: case CollectionDetailedKind.GenericReadOnlyList: -#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#endif // !NETFX_35 +#endif // !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 { comparisonType = this.CollectionTraits.ElementType; break; } case CollectionDetailedKind.GenericDictionary: -#if !NETFX_35 && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyDictionary: -#endif // !NETFX_35 && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) { comparisonType = this.CollectionTraits.ElementType.GetGenericArguments()[ 0 ]; break; @@ -1846,7 +2018,7 @@ PolymorphismSchema schema this.EmitStoreVariableStatement( context, storage, - this.MakeNullLiteral( context, typeof( PolymorphismSchema ) ) + this.MakeNullLiteral( context, TypeDefinition.PolymorphismSchemaType ) ); yield break; } @@ -1868,8 +2040,8 @@ PolymorphismSchema schema var itemsSchemaVariableName = context.GetUniqueVariableName( "itemsSchema" ); var itemsSchema = schema.ItemSchema.UseDefault - ? this.MakeNullLiteral( context, typeof( PolymorphismSchema ) ) - : this.DeclareLocal( context, typeof( PolymorphismSchema ), itemsSchemaVariableName ); + ? this.MakeNullLiteral( context, TypeDefinition.PolymorphismSchemaType ) + : this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, itemsSchemaVariableName ); if ( !schema.ItemSchema.UseDefault ) { yield return itemsSchema; @@ -1918,7 +2090,7 @@ var instruction in var typeMap = this.DeclareLocal( context, - typeof( Dictionary ), + TypeDefinition.DictionaryOfStringAndTypeType, context.GetUniqueVariableName( "typeMap" ) ); @@ -1976,8 +2148,8 @@ var instruction in var keysSchemaVariableName = context.GetUniqueVariableName( "keysSchema" ); var keysSchema = schema.KeySchema.UseDefault - ? this.MakeNullLiteral( context, typeof( PolymorphismSchema ) ) - : this.DeclareLocal( context, typeof( PolymorphismSchema ), keysSchemaVariableName ); + ? this.MakeNullLiteral( context, TypeDefinition.PolymorphismSchemaType ) + : this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, keysSchemaVariableName ); if ( !schema.KeySchema.UseDefault ) { yield return keysSchema; @@ -1993,8 +2165,8 @@ var instruction in var valuesSchemaVariableName = context.GetUniqueVariableName( "valuesSchema" ); var valuesSchema = schema.ItemSchema.UseDefault - ? this.MakeNullLiteral( context, typeof( PolymorphismSchema ) ) - : this.DeclareLocal( context, typeof( PolymorphismSchema ), valuesSchemaVariableName ); + ? this.MakeNullLiteral( context, TypeDefinition.PolymorphismSchemaType ) + : this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, valuesSchemaVariableName ); if ( !schema.ItemSchema.UseDefault ) { yield return valuesSchema; @@ -2044,7 +2216,7 @@ var instruction in var typeMap = this.DeclareLocal( context, - typeof( Dictionary ), + TypeDefinition.DictionaryOfStringAndTypeType, context.GetUniqueVariableName( "typeMap" ) ); @@ -2083,7 +2255,7 @@ var instruction in } break; } -#if !WINDOWS_PHONE && !NETFX_35 +#if !WINDOWS_PHONE && !NET35 case PolymorphismSchemaChildrenType.TupleItems: { if ( schema.ChildSchemaList.Count == 0 ) @@ -2092,7 +2264,7 @@ var instruction in this.EmitStoreVariableStatement( context, storage, - this.MakeNullLiteral( context, typeof( PolymorphismSchema ) ) + this.MakeNullLiteral( context, TypeDefinition.PolymorphismSchemaType ) ); } @@ -2115,7 +2287,7 @@ var instruction in var tupleItemsSchema = this.DeclareLocal( context, - typeof( PolymorphismSchema[] ), + TypeDefinition.PolymorphismSchemaArrayType, context.GetUniqueVariableName( "tupleItemsSchema" ) ); @@ -2125,12 +2297,12 @@ var instruction in this.EmitStoreVariableStatement( context, tupleItemsSchema, - this.EmitCreateNewArrayExpression( context, typeof( PolymorphismSchema ), tupleItems.Count ) + this.EmitCreateNewArrayExpression( context, TypeDefinition.PolymorphismSchemaType, tupleItems.Count ) ); for ( var i = 0; i < tupleItems.Count; i++ ) { var variableName = context.GetUniqueVariableName( "tupleItemSchema" ); - var itemSchema = this.DeclareLocal( context, typeof( PolymorphismSchema ), variableName ); + var itemSchema = this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, variableName ); yield return itemSchema; foreach ( var statement in this.EmitConstructLeafPolymorphismSchema( context, itemSchema, schema.ChildSchemaList[ i ], variableName ) ) { @@ -2154,7 +2326,7 @@ var instruction in ); break; } -#endif // !WINDOWS_PHONE && !NETFX_35 +#endif // !WINDOWS_PHONE && !NET35 default: { foreach ( var instruction in @@ -2186,7 +2358,7 @@ private IEnumerable EmitConstructLeafPolymorphismSchema( TContext co this.EmitStoreVariableStatement( context, storage, - this.MakeNullLiteral( context, typeof( PolymorphismSchema ) ) + this.MakeNullLiteral( context, TypeDefinition.PolymorphismSchemaType ) ); } else if ( currentSchema.UseTypeEmbedding ) @@ -2208,7 +2380,7 @@ private IEnumerable EmitConstructLeafPolymorphismSchema( TContext co var typeMap = this.DeclareLocal( context, - typeof( Dictionary ), + TypeDefinition.DictionaryOfStringAndTypeType, context.GetUniqueVariableName( String.IsNullOrEmpty( prefix ) ? "typeMap" : ( prefix + "TypeMap" ) ) ); @@ -2302,9 +2474,9 @@ private TConstruct EmitCheckIsMapHeaderExpression( TContext context, TConstruct ); } - #endregion -- Collection Helpers -- +#endregion -- Collection Helpers -- - #region -- Async Helpers -- +#region -- Async Helpers -- private static string AdjustName( string methodName, bool isAsync ) { @@ -2326,13 +2498,20 @@ protected virtual bool WithAsync( TContext context ) private TConstruct ReferCancellationToken( TContext context, int index ) { - return this.ReferArgument( context, typeof( CancellationToken ), "cancellationToken", index ); + return this.ReferArgument( context, TypeDefinition.CancellationTokenType, "cancellationToken", index ); } #endif // !FEATURE_TAP - #endregion -- Async Helpers -- +#endregion -- Async Helpers -- + private enum TypeKind + { + MessagePackObject = 0, + ValueType, + ReferenceType, + NullableType + } private sealed class UnpackingContextInfo { diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Enum.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Enum.cs index 5a33acfc5..7e3424194 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Enum.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Enum.cs @@ -19,11 +19,11 @@ #endregion -- License Terms -- using System; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 #if FEATURE_TAP using System.Threading; #endif // FEATURE_TAP @@ -70,16 +70,16 @@ private void BuildPackUnderlyingValueTo( TContext context, Type underlyingType, context, this.EmitInvokeMethodExpression( context, - this.ReferArgument( context, typeof( Packer ), "packer", 1 ), + this.ReferArgument( context, TypeDefinition.PackerType, "packer", 1 ), typeof( Packer ).GetMethod( "PackAsync", new[] { underlyingType, typeof( CancellationToken) } ), this.EmitEnumToUnderlyingCastExpression( context, underlyingType, this.ReferArgument( context, this.TargetType, "enumValue", 2 ) ), - this.ReferArgument( context, typeof( CancellationToken ), "cancellationToken", 3 ) + this.ReferArgument( context,TypeDefinition.CancellationTokenType, "cancellationToken", 3 ) ) ) : #endif // FEATURE_TAP this.EmitInvokeVoidMethod( context, - this.ReferArgument( context, typeof( Packer ), "packer", 1 ), + this.ReferArgument( context, TypeDefinition.PackerType, "packer", 1 ), typeof( Packer ).GetMethod( "Pack", new[] { underlyingType } ), this.EmitEnumToUnderlyingCastExpression( context, underlyingType, this.ReferArgument( context, this.TargetType, "enumValue", 2 ) ) ); @@ -100,7 +100,7 @@ private void BuildUnpackFromUnderlyingValue( TContext context, Type underlyingTy this.TargetType, this.EmitInvokeMethodExpression( context, - this.ReferArgument( context, typeof( MessagePackObject ), "messagePackObject", 1 ), + this.ReferArgument( context, TypeDefinition.MessagePackObjectType, "messagePackObject", 1 ), typeof( MessagePackObject ).GetMethod( "As" + underlyingType.Name, ReflectionAbstractions.EmptyTypes ) ) ) diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Nullable.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Nullable.cs index d3d3eac95..6500885ff 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Nullable.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Nullable.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -20,6 +20,9 @@ using System; using System.Linq; +#if FEATURE_TAP +using System.Threading.Tasks; +#endif // FEATURE_TAP namespace MsgPack.Serialization.AbstractSerializers { @@ -77,7 +80,11 @@ private void BuildNullableUnpackFrom( TContext context, Type underlyingType, boo #if FEATURE_TAP isAsync ? MethodName.UnpackFromAsyncCore : #endif // FEATURE_TAP - MethodName.UnpackFromCore; + MethodName.UnpackFromCore; +#if FEATURE_TAP + var asyncMethodReturnType = typeof( Task<> ).MakeGenericType( underlyingType ); +#endif // FEATURE_TAP + context.BeginMethodOverride( methodName ); var result = this.DeclareLocal( context, this.TargetType, "result" ); @@ -87,12 +94,15 @@ private void BuildNullableUnpackFrom( TContext context, Type underlyingType, boo context, this.EmitGetSerializerExpression( context, underlyingType, null, null ), #if FEATURE_TAP - isAsync ? typeof( MessagePackSerializer<> ).MakeGenericType( underlyingType ).GetMethod( "UnpackFromAsync", SerializerBuilderHelper.UnpackFromAsyncParameterTypes ) : + isAsync + ? typeof( MessagePackSerializer<> ).MakeGenericType( underlyingType ).GetMethods() + .Single( m => m.IsPublic && m.Name == "UnpackFromAsync" && m.ReturnType == asyncMethodReturnType && m.GetParameterTypes().SequenceEqual( SerializerBuilderHelper.UnpackFromAsyncParameterTypes ) ) : #endif // FEATURE_TAP typeof( MessagePackSerializer<> ).MakeGenericType( underlyingType ).GetMethod( "UnpackFrom" ), context.Unpacker ); + context.EndMethodOverride( methodName, this.EmitRetrunStatement( diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Object.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Object.cs index 70cbaea01..c58d9e452 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Object.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Object.cs @@ -20,14 +20,15 @@ using System; using System.Collections.Generic; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; @@ -38,10 +39,10 @@ namespace MsgPack.Serialization.AbstractSerializers { partial class SerializerBuilder { - private void BuildObjectSerializer( TContext context, out SerializationTarget targetInfo ) + private SerializationTarget BuildObjectSerializer( TContext context ) { SerializationTarget.VerifyType( this.TargetType ); - targetInfo = SerializationTarget.Prepare( context.SerializationContext, this.TargetType ); + var targetInfo = SerializationTarget.Prepare( context.SerializationContext, this.TargetType ); if ( typeof( IPackable ).IsAssignableFrom( this.TargetType ) ) { @@ -70,7 +71,7 @@ private void BuildObjectSerializer( TContext context, out SerializationTarget ta if ( typeof( IUnpackable ).IsAssignableFrom( this.TargetType ) ) { - this.BuildIUnpackableUnpackFrom( context, this.GetUnpackableObjectInstantiation( context ) ); + this.BuildIUnpackableUnpackFrom( context, this.GetUnpackableObjectInstantiation( context ), targetInfo.CanDeserialize ); } else { @@ -83,7 +84,7 @@ private void BuildObjectSerializer( TContext context, out SerializationTarget ta { if ( typeof( IAsyncUnpackable ).IsAssignableFrom( this.TargetType ) ) { - this.BuildIAsyncUnpackableUnpackFrom( context, this.GetUnpackableObjectInstantiation( context ) ); + this.BuildIAsyncUnpackableUnpackFrom( context, this.GetUnpackableObjectInstantiation( context ), targetInfo.CanDeserialize ); } else { @@ -92,6 +93,8 @@ private void BuildObjectSerializer( TContext context, out SerializationTarget ta } #endif // FEATURE_TAP + + return targetInfo; } #region -- IPackable -- @@ -134,9 +137,9 @@ private TConstruct BuildIPackablePackToCore( TContext context, Type @interface ) this.EmitInvokeVoidMethod( context, context.PackToTarget, - new MethodDefinition( packTo, @interface ), + new MethodDefinition( packTo, @interface ), context.Packer, - this.MakeNullLiteral( context, typeof( PackingOptions ) ) + this.MakeNullLiteral( context, TypeDefinition.PackingOptionsType ) ); } else @@ -151,7 +154,7 @@ private TConstruct BuildIPackablePackToCore( TContext context, Type @interface ) context.PackToTarget, new MethodDefinition( packTo, @interface ), context.Packer, - this.MakeNullLiteral( context, typeof( PackingOptions ) ), + this.MakeNullLiteral( context, TypeDefinition.PackingOptionsType ), this.ReferCancellationToken( context, 3 ) ) ); @@ -166,6 +169,19 @@ private TConstruct BuildIPackablePackToCore( TContext context, Type @interface ) private void BuildObjectPackTo( TContext context, SerializationTarget targetInfo, bool isAsync ) { + if ( targetInfo.Members.Count == 0 ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + isAsync + ? "At least one serializable member is required because type '{0}' does not implement IAsyncPackable interface." + : "At least one serializable member is required because type '{0}' does not implement IPackable interface.", + this.TargetType + ) + ); + } + var methodName = #if FEATURE_TAP isAsync ? MethodName.PackToAsyncCore : @@ -176,7 +192,7 @@ private void BuildObjectPackTo( TContext context, SerializationTarget targetInfo methodName, this.EmitSequentialStatements( context, - typeof( void ), + TypeDefinition.VoidType, this.BuildObjectPackToCore( context, targetInfo.Members, isAsync ) ) ); @@ -194,6 +210,7 @@ private IEnumerable BuildObjectPackToCore( TContext context, IList BuildObjectPackToCore( TContext context, IList BuildObjectPackToCore( TContext context, IList isAsync ? this.EmitRetrunStatement( context, this.EmitInvokeMethodExpression( context, context.Packer, methodForNull, argumentsForNull ) ) : this.EmitInvokeVoidMethod( context, context.Packer, methodForNull, argumentsForNull ), @@ -232,20 +250,23 @@ private IEnumerable BuildObjectPackToCore( TContext context, IList this.EmitSequentialStatements( context, - typeof( void ), + TypeDefinition.VoidType, this.EmitPackItemStatements( context, context.Packer, - entries[ count ].Member.GetMemberValueType(), + itemType, entries[ count ].Contract.NilImplication, entries[ count ].Member.ToString(), this.EmitGetMemberValueExpression( context, context.PackToTarget, entries[ count ].Member ), @@ -256,43 +277,121 @@ entries[ count ].Member.ToString(), ), parameters ); + + if ( ( !itemType.GetIsValueType() || Nullable.GetUnderlyingType( itemType ) != null ) +#if DEBUG + && !SerializerDebugging.UseLegacyNullMapEntryHandling +#endif // DEBUG + ) + { + var nullCheckTarget = this.EmitGetMemberValueExpression( context, context.NullCheckTarget, entries[ count ].Member ); + // Trying uses nullCheckTarget.ContextType because it may be Object when using reflection. + var nullCheckTargetType = nullCheckTarget.ContextType.TryGetRuntimeType() ?? itemType; + // CheckNull + DefinePrivateMethod( + context, + GetCheckNullMethodName( entries[ i ] ), + false, // isStatic + TypeDefinition.BooleanType, + () => + nullCheckTargetType.GetIsValueType() // Is Nullable ? + ? this.EmitSequentialStatements( + context, + TypeDefinition.BooleanType, + this.EmitHasValueCore( context, nullCheckTarget, nullCheckTargetType ) + ) : this.EmitRetrunStatement( + context, + this.EmitEqualsExpression( context, nullCheckTarget, this.MakeNullLiteral( context, nullCheckTargetType ) ) + ), + nullCheckParameters + ); + } } } var packHelperArguments = - new[] + new Dictionary { - context.Packer, - context.PackToTarget, - this.EmitGetActionsExpression( - context, - method == SerializationMethod.Array - ? ActionType.PackToArray - : ActionType.PackToMap, - isAsync - ) - } + { "Packer", context.Packer }, + { "Target", context.PackToTarget }, + { + "Operations", + this.EmitGetActionsExpression( + context, + method == SerializationMethod.Array + ? ActionType.PackToArray + : ActionType.PackToMap, + isAsync + ) + } + }; + + if ( method == SerializationMethod.Map +#if DEBUG + && !SerializerDebugging.UseLegacyNullMapEntryHandling +#endif // DEBUG + ) + { + packHelperArguments.Add( + "SerializationContext", + this.EmitGetPropertyExpression( context, this.EmitThisReferenceExpression( context ), Metadata._MessagePackSerializer.OwnerContext ) + ); + // isAsync is always false to prevent _nullCheckersTableAsync creation. + packHelperArguments.Add( "NullCheckers", this.EmitGetActionsExpression( context, ActionType.IsNull, isAsync: false ) ); + } + #if FEATURE_TAP - .Concat( isAsync ? new[] { this.ReferCancellationToken( context, 3 ) } : NoConstructs ).ToArray() + if ( isAsync ) + { + packHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 3 ) ); + } #endif // FEATURE_TAP - ; - var methodInvocation = - this.EmitInvokeMethodExpression( - context, - null, + var packHelperParameterTypeDefinition = + ( method == SerializationMethod.Array + ? ( +#if FEATURE_TAP + isAsync ? typeof( PackToArrayAsyncParameters<> ) : +#endif // FEATURE_TAP + typeof( PackToArrayParameters<> ) + ) : ( +#if FEATURE_TAP + isAsync ? typeof( PackToMapAsyncParameters<> ) : +#endif // FEATURE_TAP + typeof( PackToMapParameters<> ) + ) + ); + + var packHelperMethodName = AdjustName( "PackTo" + method, isAsync ); + var packHelperParameterType = + TypeDefinition.GenericValueType( packHelperParameterTypeDefinition, this.TargetType ); + var packHelperMethod = new MethodDefinition( - AdjustName( "PackTo" + method, isAsync ), - new[] { TypeDefinition.Object( this.TargetType ), }, - typeof( PackHelpers ), + packHelperMethodName, + new TypeDefinition[] { this.TargetType }, + TypeDefinition.PackHelpersType, + true, // isStatic #if FEATURE_TAP - isAsync ? typeof( Task ) : + isAsync ? TypeDefinition.TaskType : #endif // FEATURE_TAP - typeof( void ), - packHelperArguments.Select( a => a.ContextType ).ToArray() - ), - packHelperArguments - ); + TypeDefinition.VoidType, + packHelperParameterType + ); + + var packHelperParameters = this.DeclareLocal( context, packHelperParameterType, "packHelperParameters" ); + yield return packHelperParameters; + foreach ( var construct in this.CreatePackUnpackHelperArgumentInitialization( context, packHelperParameters, packHelperArguments ) ) + { + yield return construct; + } + + var methodInvocation = + this.EmitInvokeMethodExpression( + context, + null, + packHelperMethod, + this.EmitMakeRef( context, packHelperParameters ) + ); if ( isAsync ) { @@ -324,16 +423,32 @@ entries[ count ].Member.ToString(), ), Metadata._SerializationContext.SerializationMethod ), - this.MakeEnumLiteral( context, typeof( SerializationMethod ), SerializationMethod.Array ) + this.MakeEnumLiteral( context, TypeDefinition.SerializationMethodType, SerializationMethod.Array ) ), forArray, forMap ); } - #endregion -- IPackable -- + private IEnumerable EmitHasValueCore( TContext context, TConstruct nullCheckTarget, Type itemType ) + { + var nullable = this.DeclareLocal( context, itemType, "nullable" ); + yield return nullable; + yield return this.EmitStoreVariableStatement( context, nullable, nullCheckTarget ); + yield return + this.EmitRetrunStatement( + context, + this.EmitEqualsExpression( + context, + this.EmitGetPropertyExpression( context, nullable, itemType.GetProperty( "HasValue" ) ), + this.MakeBooleanLiteral( context, false ) + ) + ); + } - #region -- Pack Operation Initialization -- +#endregion -- IPackable -- + +#region -- Pack Operation Initialization -- protected internal TConstruct EmitPackOperationListInitialization( TContext context, SerializationTarget targetInfo, bool isAsync ) { @@ -357,7 +472,7 @@ protected internal TConstruct EmitPackOperationListInitialization( TContext cont protected internal TConstruct EmitPackOperationTableInitialization( TContext context, SerializationTarget targetInfo, bool isAsync ) { var actionType = this.GetPackOperationType( context, isAsync ); - var listType = TypeDefinition.GenericReferenceType( typeof( Dictionary<,> ), typeof( string ), actionType ); + var listType = TypeDefinition.GenericReferenceType( typeof( Dictionary<,> ), TypeDefinition.StringType, actionType ); return this.EmitSequentialStatements( context, @@ -417,7 +532,7 @@ private IEnumerable EmitPackActionCollectionCore( TContext context, : this.EmitCreateNewObjectExpression( context, actionCollection, - new ConstructorDefinition( actionCollection.ContextType, typeof( int ) ), + new ConstructorDefinition( actionCollection.ContextType, TypeDefinition.Int32Type ), this.MakeInt32Literal( context, knownActions.Length ) ) ); @@ -456,7 +571,8 @@ knownActions[ i ].Value actionCollection, actionCollection.ContextType, "Item", - this.MakeStringLiteral( context, knownActions[ i ].Key ), + // Set key as transformed. + this.MakeStringLiteral( context, context.SerializationContext.DictionarySerializationOptions.SafeKeyTransformer( knownActions[ i ].Key ) ), packItemBody ); } @@ -465,7 +581,7 @@ knownActions[ i ].Value yield return this.EmitFinishFieldInitializationStatement( context, - AdjustName( + AdjustName( method == SerializationMethod.Array ? FieldName.PackOperationList : FieldName.PackOperationTable, @@ -475,6 +591,64 @@ knownActions[ i ].Value ); } + protected internal TConstruct EmitPackNullCheckerTableInitialization( TContext context, SerializationTarget targetInfo ) + { + var listType = typeof( Dictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,> ).MakeGenericType( this.TargetType, typeof( bool ) ) ); + return + this.EmitSequentialStatements( + context, + listType, + this.EmitPackNullCheckerTableInitializationCore( + context, + targetInfo, + this.DeclareLocal( context, listType, "nullCheckerTable" ) + ) + ); + } + + private IEnumerable EmitPackNullCheckerTableInitializationCore( TContext context, SerializationTarget targetInfo, TConstruct actionCollection ) + { + yield return actionCollection; + + var knownActions = GetDeclaredKnownActions( context, targetInfo, m => GetCheckNullMethodName( m ) ); + + yield return + this.EmitStoreVariableStatement( + context, + actionCollection, + this.EmitCreateNewObjectExpression( + context, + actionCollection, + new ConstructorDefinition( actionCollection.ContextType, TypeDefinition.Int32Type ), + this.MakeInt32Literal( context, knownActions.Length ) + ) + ); + + for ( int i = 0; i < knownActions.Length; i++ ) + { + yield return + this.EmitSetIndexedProperty( + context, + actionCollection, + actionCollection.ContextType, + "Item", + // Set key as transformed. + this.MakeStringLiteral( context, context.SerializationContext.DictionarySerializationOptions.SafeKeyTransformer( knownActions[ i ].Key ) ), + this.EmitNewPrivateMethodDelegateExpression( + context, + knownActions[ i ].Value + ) + ); + } + + yield return + this.EmitFinishFieldInitializationStatement( + context, + FieldName.NullCheckersTable, + actionCollection + ); + } + private static string GetPackValueMethodName( SerializingMember member, bool isAsync ) { return @@ -486,20 +660,26 @@ private static string GetPackValueMethodName( SerializingMember member, bool isA ); } - #endregion -- Pack Operation Initialization -- + private static string GetCheckNullMethodName( SerializingMember member ) + { + return "Is" + member.MemberName + "Null"; + } + +#endregion -- Pack Operation Initialization -- - #region -- IUnpackable -- +#region -- IUnpackable -- - private void BuildIUnpackableUnpackFrom( TContext context, TConstruct objectCreation ) + private void BuildIUnpackableUnpackFrom( TContext context, TConstruct objectCreation, bool canDeserialize ) { context.BeginMethodOverride( MethodName.UnpackFromCore ); context.EndMethodOverride( MethodName.UnpackFromCore, - this.EmitSequentialStatements( + canDeserialize + ? this.EmitSequentialStatements( context, this.TargetType, this.BuildIUnpackableUnpackFromCore( context, typeof( IUnpackable ), objectCreation ) - ) + ) : this.EmitThrowCannotUnpackFrom( context ) ); } @@ -514,31 +694,31 @@ private TConstruct GetUnpackableObjectInstantiation( TContext context ) ); } - #endregion -- IUnpackable -- +#endregion -- IUnpackable -- #if FEATURE_TAP - #region -- IAsyncUnpackable -- +#region -- IAsyncUnpackable -- - private void BuildIAsyncUnpackableUnpackFrom( TContext context, TConstruct objectCreation ) + private void BuildIAsyncUnpackableUnpackFrom( TContext context, TConstruct objectCreation, bool canDeserialize ) { - context.BeginMethodOverride( MethodName.UnpackFromAsyncCore ); context.EndMethodOverride( MethodName.UnpackFromAsyncCore, - this.EmitSequentialStatements( + canDeserialize + ? this.EmitSequentialStatements( context, this.TargetType, this.BuildIUnpackableUnpackFromCore( context, typeof( IAsyncUnpackable ), objectCreation ) - ) + ) : this.EmitThrowCannotUnpackFrom( context ) ); } - #endregion -- IAsyncUnpackable -- +#endregion -- IAsyncUnpackable -- #endif // FEATURE_TAP - #region -- UnpackFrom -- +#region -- UnpackFrom -- private IEnumerable BuildIUnpackableUnpackFromCore( TContext context, Type @interface, TConstruct objectCreation ) { @@ -592,6 +772,19 @@ private IEnumerable BuildIUnpackableUnpackFromCore( TContext context private void BuildObjectUnpackFrom( TContext context, SerializationTarget targetInfo, bool isAsync ) { + if ( targetInfo.Members.Count == 0 ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + isAsync + ? "At least one serializable member is required because type '{0}' does not implement IAsyncUnpackable interface." + : "At least one serializable member is required because type '{0}' does not implement IUnpackable interface.", + this.TargetType + ) + ); + } + /* * #if T is IUnpackable * result.UnpackFromMessage( unpacker ); @@ -615,11 +808,12 @@ private void BuildObjectUnpackFrom( TContext context, SerializationTarget target context.BeginMethodOverride( methodName ); context.EndMethodOverride( methodName, - this.EmitSequentialStatements( + targetInfo.CanDeserialize + ? this.EmitSequentialStatements( context, this.TargetType, this.EmitObjectUnpackFromCore( context, targetInfo, isAsync ) - ) + ) : this.EmitThrowCannotUnpackFrom( context ) ); } @@ -651,12 +845,6 @@ private TConstruct EmitObjectUnpackFromCore( TContext context, SerializationTarg #endif // FEATURE_TAP ; - int constructorParameterIndex = 0; - var fieldNames = - targetInfo.IsConstructorDeserialization - ? targetInfo.DeserializationConstructor.GetParameters().Select( p => p.Name ).ToArray() - : targetInfo.Members.Where( m => m.MemberName != null ).Select( m => m.MemberName ).ToArray(); - for ( int i = 0; i < targetInfo.Members.Count; i++ ) { var count = i; @@ -687,33 +875,16 @@ private TConstruct EmitObjectUnpackFromCore( TContext context, SerializationTarg } else { + var name = targetInfo.Members[ count ].MemberName; + Contract.Assert( !String.IsNullOrEmpty( name ), targetInfo.Members[ count ] + "@" + i + " does not have member name."); var unpackedItem = context.DefineUnpackedItemParameterInSetValueMethods( targetInfo.Members[ count ].Member.GetMemberValueType() ); Func storeValueStatementEmitter; - if ( unpackingContext.VariableType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) ) + if ( targetInfo.IsConstructorDeserialization || this.TargetType.GetIsValueType() ) { - storeValueStatementEmitter = - () => - this.EmitInvokeVoidMethod( - context, - context.UnpackingContextInSetValueMethods, - Metadata._DynamicUnpackingContext.Set, - this.MakeStringLiteral( context, fieldNames[ count ] ), - targetInfo.Members[ count ].Member.GetMemberValueType().GetIsValueType() - ? this.EmitBoxExpression( - context, - unpackedItem.ContextType, - unpackedItem - ) : unpackedItem - ); - } - else if ( targetInfo.IsConstructorDeserialization || this.TargetType.GetIsValueType() ) - { - var name = fieldNames[ constructorParameterIndex ]; storeValueStatementEmitter = () => this.EmitSetField( context, context.UnpackingContextInSetValueMethods, unpackingContext.Type, name, unpackedItem ); - constructorParameterIndex++; } else { @@ -740,7 +911,8 @@ targetInfo.Members[ count ].Member.GetMemberValueType(), MethodNamePrefix.SetUnpackedValueOf + targetInfo.Members[ count ].Member.Name, null, null, - typeof( void ), + false, // isStatic + TypeDefinition.VoidType, unpackingContext.VariableType, targetInfo.Members[ count ].Member.GetMemberValueType() ), @@ -748,18 +920,18 @@ targetInfo.Members[ count ].Member.GetMemberValueType() context.UnpackingContextInSetValueMethods, unpackedItem ), - method == SerializationMethod.Map, // forMap isAsync ); } - this.ExtractPrivateMethod( + DefinePrivateMethod( context, GetUnpackValueMethodName( targetInfo.Members[ i ], isAsync ), + false, // isStatic #if FEATURE_TAP - isAsync ? typeof( Task ) : + isAsync ? TypeDefinition.TaskType : #endif // FEATURE_TAP - typeof( void ), + TypeDefinition.VoidType, () => privateMethodBody, unpackOperationParameters ); @@ -798,7 +970,8 @@ targetInfo.Members[ count ].Member.GetMemberValueType() new MethodDefinition( AdjustName( MethodNamePrefix.UnpackFrom + method, isAsync ), new[] { unpackingContext.Type, this.TargetType }, - typeof( UnpackHelpers ), + TypeDefinition.UnpackHelpersType, + true, // isStatic this.TargetType, unpackHelperArguments.Select( a => a.ContextType ).ToArray() ), @@ -807,9 +980,9 @@ targetInfo.Members[ count ].Member.GetMemberValueType() ); } - #endregion -- UnpackFrom -- +#endregion -- UnpackFrom -- - #region -- UnpackingContext Initialization -- +#region -- UnpackingContext Initialization -- private UnpackingContextInfo EmitObjectUnpackingContextInitialization( TContext context, SerializationTarget targetInfo ) { @@ -817,7 +990,7 @@ private UnpackingContextInfo EmitObjectUnpackingContextInitialization( TContext { var constructorParameters = targetInfo.DeserializationConstructor.GetParameters(); var contextFields = - constructorParameters.Select( p => new KeyValuePair( p.Name, p.ParameterType ) ).ToArray(); + constructorParameters.Select( ( p, i ) => new KeyValuePair( targetInfo.GetCorrespondingMemberName( i ) ?? ( "__OrphanParameter" + i.ToString( CultureInfo.InvariantCulture ) ), p.ParameterType ) ).ToArray(); var constructorArguments = new List( constructorParameters.Length ); var mappableConstructorArguments = new HashSet(); var initializationStatements = @@ -952,39 +1125,7 @@ IEnumerable argumentInitializers unpackingContext.Statements.AddRange( argumentInitializers ); unpackingContext.Statements.Add( - unpackingContext.VariableType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) - ? this.EmitSequentialStatements( - context, - typeof( void ), - new[] - { - this.EmitStoreVariableStatement( - context, - unpackingContext.Variable, - this.EmitCreateNewObjectExpression( - context, - unpackingContext.Variable, - unpackingContext.Constructor, - this.MakeInt32Literal( context, constructorArguments.Count ) - ) - ) - }.Concat( - constructorArguments.Select( ( a, i ) => - this.EmitInvokeVoidMethod( - context, - unpackingContext.Variable, - Metadata._DynamicUnpackingContext.Set, - this.MakeStringLiteral( context, contextFields[ i ].Key ), - a.ContextType.ResolveRuntimeType().GetIsValueType() - ? this.EmitBoxExpression( - context, - a.ContextType, - a - ) : a - ) - ) - ) - ) : this.EmitStoreVariableStatement( + this.EmitStoreVariableStatement( context, unpackingContext.Variable, this.EmitCreateNewObjectExpression( @@ -999,9 +1140,9 @@ IEnumerable argumentInitializers return unpackingContext; } - #endregion -- UnpackingContext Initialization -- +#endregion -- UnpackingContext Initialization -- - #region -- CreateObjectFromContext -- +#region -- CreateObjectFromContext -- private IEnumerable EmitCreateObjectFromContextCore( TContext context, SerializationTarget targetInfo, UnpackingContextInfo unpackingContext, KeyValuePair[] fields @@ -1028,26 +1169,15 @@ private IEnumerable EmitCreateObjectFromContextCore( context, result, member, - unpackingContext.VariableType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) - ? this.EmitUnboxAnyExpression( - context, - field.Value, - this.EmitInvokeMethodExpression( - context, - context.UnpackingContextInCreateObjectFromContext, - Metadata._DynamicUnpackingContext.Get, - this.MakeStringLiteral( context, field.Key ) - ) - ) - : this.EmitGetFieldExpression( - context, - context.UnpackingContextInCreateObjectFromContext, - new FieldDefinition( - unpackingContext.Type, - field.Key, - field.Value - ) + this.EmitGetFieldExpression( + context, + context.UnpackingContextInCreateObjectFromContext, + new FieldDefinition( + unpackingContext.Type, + field.Key, + field.Value ) + ) ); } @@ -1065,14 +1195,15 @@ private MethodDefinition GetCreateObjectFromContextMethod( UnpackingContextInfo MethodName.CreateObjectFromContext, null, null, + true, // isStatic this.TargetType, unpackingContext.Type ); } - #endregion -- CreateObjectFromContext -- +#endregion -- CreateObjectFromContext -- - #region -- Unpack Operation Initialization -- +#region -- Unpack Operation Initialization -- protected internal TConstruct EmitUnpackOperationListInitialization( TContext context, SerializationTarget targetInfo, bool isAsync ) { @@ -1096,7 +1227,7 @@ protected internal TConstruct EmitUnpackOperationListInitialization( TContext co protected internal TConstruct EmitUnpackOperationTableInitialization( TContext context, SerializationTarget targetInfo, bool isAsync ) { var actionType = this.GetUnpackOperationType( context, isAsync ); - var dictionaryType = TypeDefinition.GenericReferenceType( typeof( Dictionary<,> ), typeof( string ), actionType ); + var dictionaryType = TypeDefinition.GenericReferenceType( typeof( Dictionary<,> ), TypeDefinition.StringType, actionType ); return this.EmitSequentialStatements( context, @@ -1119,20 +1250,20 @@ protected virtual TypeDefinition GetUnpackOperationType( TContext context, bool isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,,> ), - typeof( Unpacker ), + TypeDefinition.UnpackerType, context.UnpackingContextType ?? this.TargetType, - typeof( int ), - typeof( int ), - typeof( CancellationToken ), - typeof( Task ) + TypeDefinition.Int32Type, + TypeDefinition.Int32Type, + TypeDefinition.CancellationTokenType, + TypeDefinition.TaskType ) : #endif // FEATURE_TAP TypeDefinition.GenericReferenceType( typeof( Action<,,,> ), - typeof( Unpacker ), + TypeDefinition.UnpackerType, context.UnpackingContextType ?? this.TargetType, - typeof( int ), - typeof( int ) + TypeDefinition.Int32Type, + TypeDefinition.Int32Type ); } @@ -1156,6 +1287,11 @@ private IEnumerable EmitUnpackActionCollectionInitializationCore( bool isAsync ) { + if ( !targetInfo.CanDeserialize ) + { + yield break; + } + yield return actionCollection; #if DEBUG @@ -1175,7 +1311,7 @@ bool isAsync : this.EmitCreateNewObjectExpression( context, actionCollection, - new ConstructorDefinition( actionCollection.ContextType, typeof( int ) ), + new ConstructorDefinition( actionCollection.ContextType, TypeDefinition.Int32Type ), this.MakeInt32Literal( context, knownActions.Length ) ) ); @@ -1214,7 +1350,8 @@ knownActions[ i ].Value actionCollection, actionCollection.ContextType, "Item", - this.MakeStringLiteral( context, knownActions[ i ].Key ), + // Set key as transformed. + this.MakeStringLiteral( context, context.SerializationContext.DictionarySerializationOptions.SafeKeyTransformer( knownActions[ i ].Key ) ), unpackItemBody ); } @@ -1223,7 +1360,7 @@ knownActions[ i ].Value yield return this.EmitFinishFieldInitializationStatement( context, - AdjustName( + AdjustName( method == SerializationMethod.Array ? FieldName.UnpackOperationList : FieldName.UnpackOperationTable, @@ -1250,7 +1387,7 @@ private IEnumerable InitializeConstructorArgumentInitializationState yield return argument; constructorArguments.Add( argument ); - var correspondingMemberName = target.FindCorrespondingMemberName( constructorParameters[ i ] ); + var correspondingMemberName = target.GetCorrespondingMemberName( i ); if ( correspondingMemberName != null ) { mappableConstructorArguments.Add( correspondingMemberName ); @@ -1320,18 +1457,7 @@ private IEnumerable EmitInvokeDeserializationConstructorStatementsCo constructor, fields.Select( f => - unpackingContext.ContextType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) - ? this.EmitUnboxAnyExpression( - context, - f.Value, - this.EmitInvokeMethodExpression( - context, - unpackingContext, - Metadata._DynamicUnpackingContext.Get, - this.MakeStringLiteral( context, f.Key ) - ) - ) - : this.EmitGetFieldExpression( context, unpackingContext, new FieldDefinition( unpackingContext.ContextType, f.Key, f.Value ) ) + this.EmitGetFieldExpression( context, unpackingContext, new FieldDefinition( unpackingContext.ContextType, f.Key, f.Value ) ) ).ToArray() ) ); @@ -1350,12 +1476,12 @@ protected internal TConstruct EmitMemberListInitialization( TContext context, Se FieldName.MemberNames, this.EmitCreateNewArrayExpression( context, - typeof( string ), + TypeDefinition.StringType, targetInfo.Members.Count, targetInfo.Members.Select( m => m.MemberName == null - ? this.MakeNullLiteral( context, typeof( string ) ) + ? this.MakeNullLiteral( context, TypeDefinition.StringType ) : this.MakeStringLiteral( context, m.MemberName ) ).ToArray() ) @@ -1364,9 +1490,9 @@ protected internal TConstruct EmitMemberListInitialization( TContext context, Se protected abstract TConstruct EmitGetMemberNamesExpression( TContext context ); - #endregion -- Unpack Operation Initialization -- +#endregion -- Unpack Operation Initialization -- - #region -- Operation Helpers -- +#region -- Operation Helpers -- protected abstract TConstruct EmitGetActionsExpression( TContext context, ActionType actionType, bool isAsync ); @@ -1379,6 +1505,7 @@ private TConstruct EmitNewPrivateMethodDelegateExpressionWithCreation( TContext this.ExtractPrivateMethod( context, method.MethodName, + false, // isStatic method.ReturnType, bodyFactory, privateMethodParameters @@ -1401,6 +1528,22 @@ private static KeyValuePair[] GetKnownActions( TContex } - #endregion -- Operation Helpers -- + private static KeyValuePair[] GetDeclaredKnownActions( TContext context, SerializationTarget targetInfo, Func nameFactory ) + { + return + targetInfo.Members + .Where( m => m.MemberName != null ) + .Select( m => + new KeyValuePair( + m.MemberName, + context.TryGetDeclaredMethod( nameFactory( m ) ) + ) + ).Where( kv => kv.Value != null ) + .ToArray(); + + } + +#endregion -- Operation Helpers -- } } + diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Tuple.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Tuple.cs index 6802bd27f..1670cc661 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Tuple.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.Tuple.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Linq; using System.Reflection; #if FEATURE_TAP @@ -41,29 +41,30 @@ private void BuildTupleSerializer( TContext context, IList i { var itemTypes = TupleItems.GetTupleItemTypes( this.TargetType ); targetInfo = SerializationTarget.CreateForTuple( itemTypes ); + var isValueTuple = this.TargetType.GetIsValueType(); - this.BuildTuplePackTo( context, itemTypes, itemSchemaList, false ); + this.BuildTuplePackTo( context, itemTypes, itemSchemaList, isValueTuple, false ); #if FEATURE_TAP if ( this.WithAsync( context ) ) { - this.BuildTuplePackTo( context, itemTypes, itemSchemaList, true ); + this.BuildTuplePackTo( context, itemTypes, itemSchemaList, isValueTuple, true ); } #endif // FEATURE_TAP - this.BuildTupleUnpackFrom( context, itemTypes, itemSchemaList, false ); + this.BuildTupleUnpackFrom( context, itemTypes, itemSchemaList, isValueTuple, false ); #if FEATURE_TAP if ( this.WithAsync( context ) ) { - this.BuildTupleUnpackFrom( context, itemTypes, itemSchemaList, true ); + this.BuildTupleUnpackFrom( context, itemTypes, itemSchemaList, isValueTuple, true ); } #endif // FEATURE_TAP } #region -- PackTo -- - private void BuildTuplePackTo( TContext context, IList itemTypes, IList itemSchemaList, bool isAsync ) + private void BuildTuplePackTo( TContext context, IList itemTypes, IList itemSchemaList, bool isValueTuple, bool isAsync ) { /* packer.PackArrayHeader( cardinarity ); @@ -83,18 +84,26 @@ private void BuildTuplePackTo( TContext context, IList itemTypes, IList BuildTuplePackToCore( TContext context, IList itemTypes, IList itemSchemaList, bool isAsync ) + private IEnumerable BuildTuplePackToCore( TContext context, IList itemTypes, IList itemSchemaList, bool isValueTuple, bool isAsync ) + { + return + isValueTuple + ? BuildTuplePackToCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetField( n ), ( c, s, m ) => this.EmitGetFieldExpression( c, s, m ), isAsync ) + : BuildTuplePackToCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetProperty( n ), ( c, s, m )=> this.EmitGetPropertyExpression( c, s, m ), isAsync ); + } + + private IEnumerable BuildTuplePackToCore( TContext context, IList itemTypes, IList itemSchemaList, Func memberFactory, Func chainConstructFactory, bool isAsync ) { // Note: cardinality is put as array length by PackHelper. var depth = -1; - var tupleTypeList = TupleItems.CreateTupleTypeList( itemTypes ); - var propertyInvocationChain = new List( itemTypes.Count % 7 + 1 ); + var tupleTypeList = TupleItems.CreateTupleTypeList( this.TargetType ); + var memberInvocationChain = new List( itemTypes.Count % 7 + 1 ); var packValueArguments = new[] { context.Packer, context.PackToTarget } #if FEATURE_TAP @@ -102,103 +111,128 @@ private IEnumerable BuildTuplePackToCore( TContext context, IList this.EmitSequentialStatements( context, - typeof( void ), + TypeDefinition.VoidType, this.EmitPackTupleItemStatements( context, itemTypes[ count ], context.Packer, context.PackToTarget, - propertyInvocationChain, + memberInvocationChain, itemSchemaList.Count == 0 ? null : itemSchemaList[ count ], + chainConstructFactory, isAsync ) ), packValueArguments ); - propertyInvocationChain.Clear(); + memberInvocationChain.Clear(); } var packHelperArguments = - new[] - { - context.Packer, - context.PackToTarget, - this.EmitGetActionsExpression( context, ActionType.PackToArray, isAsync ) - } + new Dictionary + { + { "Packer", context.Packer }, + { "Target", context.PackToTarget }, + { "Operations", this.EmitGetActionsExpression( context, ActionType.PackToArray, isAsync ) } + }; + #if FEATURE_TAP - .Concat( isAsync ? new[] { this.ReferCancellationToken( context, 3 ) } : NoConstructs ).ToArray() + if ( isAsync ) + { + packHelperArguments.Add( "CancellationToken", this.ReferCancellationToken( context, 3 ) ); + } #endif // FEATURE_TAP - ; - var packToArray = - this.EmitInvokeMethodExpression( - context, - null, + var packHelperParameterTypeDefinition = +#if FEATURE_TAP + isAsync ? typeof( PackToArrayAsyncParameters<> ) : +#endif // FEATURE_TAP + typeof( PackToArrayParameters<> ); + + var packHelperParameterType = + TypeDefinition.GenericValueType( packHelperParameterTypeDefinition, this.TargetType ); + var packHelperMethod = new MethodDefinition( AdjustName( MethodName.PackToArray, isAsync ), new [] { TypeDefinition.Object( this.TargetType ) }, - typeof( PackHelpers ), + TypeDefinition.PackHelpersType, + true, // isStatic #if FEATURE_TAP - isAsync ? typeof( Task ) : + isAsync ? TypeDefinition.TaskType : #endif // FEATURE_TAP - typeof( void ), - packHelperArguments.Select( a => a.ContextType ).ToArray() - ), - packHelperArguments - ); + TypeDefinition.VoidType, + packHelperParameterType + ); + + var packHelperParameters = this.DeclareLocal( context, packHelperParameterType, "packHelperParameters" ); + yield return packHelperParameters; + foreach ( var construct in this.CreatePackUnpackHelperArgumentInitialization( context, packHelperParameters, packHelperArguments ) ) + { + yield return construct; + } + + var methodInvocation = + this.EmitInvokeMethodExpression( + context, + null, + packHelperMethod, + this.EmitMakeRef( context, packHelperParameters ) + ); if ( isAsync ) { // Wrap with return to return Task - packToArray = this.EmitRetrunStatement( context, packToArray ); + methodInvocation = this.EmitRetrunStatement( context, methodInvocation ); } - yield return packToArray; + yield return methodInvocation; } - private IEnumerable EmitPackTupleItemStatements( + private IEnumerable EmitPackTupleItemStatements( TContext context, Type itemType, TConstruct currentPacker, TConstruct tuple, - IEnumerable propertyInvocationChain, + IEnumerable memberInvocationChain, PolymorphismSchema itemsSchema, + Func chainConstructFactory, bool isAsync ) { @@ -209,8 +243,8 @@ bool isAsync itemType, NilImplication.Null, null, - propertyInvocationChain.Aggregate( - tuple, ( propertySource, property ) => this.EmitGetPropertyExpression( context, propertySource, property ) + memberInvocationChain.Aggregate( + tuple, ( memberSource, member ) => chainConstructFactory( context, memberSource, member ) ), null, itemsSchema, @@ -222,7 +256,7 @@ bool isAsync #region -- UnpackFrom -- - private void BuildTupleUnpackFrom( TContext context, IList itemTypes, IList itemSchemaList, bool isAsync ) + private void BuildTupleUnpackFrom( TContext context, IList itemTypes, IList itemSchemaList, bool isValueTuple, bool isAsync ) { /* * checked @@ -260,14 +294,22 @@ private void BuildTupleUnpackFrom( TContext context, IList itemTypes, ILis this.EmitSequentialStatements( context, this.TargetType, - this.BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, isAsync ) + this.BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, isValueTuple, isAsync ) ) ); } - private IEnumerable BuildTupleUnpackFromCore( TContext context, IList itemTypes, IList itemSchemaList, bool isAsync ) + private IEnumerable BuildTupleUnpackFromCore( TContext context, IList itemTypes, IList itemSchemaList, bool isValueTuple, bool isAsync ) + { + return + isValueTuple + ? BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetField( n ), isAsync ) + : BuildTupleUnpackFromCore( context, itemTypes, itemSchemaList, ( t, n ) => t.GetProperty( n ), isAsync ); + } + + private IEnumerable BuildTupleUnpackFromCore( TContext context, IList itemTypes, IList itemSchemaList, Func memberFactory, bool isAsync ) { - var tupleTypeList = TupleItems.CreateTupleTypeList( itemTypes ); + var tupleTypeList = TupleItems.CreateTupleTypeList( this.TargetType ); yield return this.EmitCheckIsArrayHeaderExpression( context, context.Unpacker ); @@ -293,22 +335,23 @@ private IEnumerable BuildTupleUnpackFromCore( TContext context, ILis ; for ( var i = 0; i < itemTypes.Count; i++ ) { - var propertyName = SerializationTarget.GetTupleItemNameFromIndex( i ); + var memberName = SerializationTarget.GetTupleItemNameFromIndex( i ); var unpackedItem = context.DefineUnpackedItemParameterInSetValueMethods( itemTypes[ i ] ); - var setUnpackValueOfMethodName = MethodNamePrefix.SetUnpackedValueOf + propertyName; + var setUnpackValueOfMethodName = MethodNamePrefix.SetUnpackedValueOf + memberName; var index = i; this.ExtractPrivateMethod( context, - AdjustName( MethodNamePrefix.UnpackValue + propertyName, isAsync ), + AdjustName( MethodNamePrefix.UnpackValue + memberName, isAsync ), + false, // isStatic #if FEATURE_TAP - isAsync ? typeof( Task ) : + isAsync ? TypeDefinition.TaskType : #endif // FEATURE_TAP - typeof( void ), + TypeDefinition.VoidType, () => this.EmitUnpackItemValueStatement( context, itemTypes[ index ], - this.MakeStringLiteral( context, propertyName ), + this.MakeStringLiteral( context, memberName ), context.TupleItemNilImplication, null, // memberInfo itemSchemaList.Count == 0 ? null : itemSchemaList[ index ], @@ -324,29 +367,19 @@ private IEnumerable BuildTupleUnpackFromCore( TContext context, ILis : this.ExtractPrivateMethod( context, setUnpackValueOfMethodName, - typeof( void ), - () => unpackingContext.VariableType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) - ? this.EmitInvokeVoidMethod( - context, - context.UnpackingContextInSetValueMethods, - Metadata._DynamicUnpackingContext.Set, - this.MakeStringLiteral( context, propertyName ), - this.EmitBoxExpression( - context, - itemTypes[ index ], - unpackedItem - ) - ) : this.EmitSetField( + false, // isStatic + TypeDefinition.VoidType, + () => + this.EmitSetField( context, context.UnpackingContextInSetValueMethods, unpackingContext.VariableType, - propertyName, + memberName, unpackedItem ), context.UnpackingContextInSetValueMethods, unpackedItem ), - false, // forMap, Tuple must be array isAsync ), unpackValueArguments @@ -354,43 +387,53 @@ private IEnumerable BuildTupleUnpackFromCore( TContext context, ILis } TConstruct currentTuple = null; - for ( int nest = tupleTypeList.Count - 1; nest >= 0; nest-- ) + for ( var nest = tupleTypeList.Count - 1; nest >= 0; nest-- ) { var gets = Enumerable.Range( nest * 7, Math.Min( itemTypes.Count - nest * 7, 7 ) ) .Select( i => - unpackingContext.VariableType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) - ? this.EmitUnboxAnyExpression( - context, - itemTypes[ i ], - this.EmitInvokeMethodExpression( - context, - context.UnpackingContextInCreateObjectFromContext, - Metadata._DynamicUnpackingContext.Get, - this.MakeStringLiteral( context, SerializationTarget.GetTupleItemNameFromIndex( i ) ) - ) - ) : this.EmitGetFieldExpression( - context, - context.UnpackingContextInCreateObjectFromContext, - new FieldDefinition( - unpackingContext.VariableType, - SerializationTarget.GetTupleItemNameFromIndex( i ), - itemTypes[ i ] - ) + this.EmitGetFieldExpression( + context, + context.UnpackingContextInCreateObjectFromContext, + new FieldDefinition( + unpackingContext.VariableType, + SerializationTarget.GetTupleItemNameFromIndex( i ), + itemTypes[ i ] ) + ) ); if ( currentTuple != null ) { gets = gets.Concat( new[] { currentTuple } ); } - currentTuple = - this.EmitCreateNewObjectExpression( - context, - null, // Tuple is reference contextType. - tupleTypeList[ nest ].GetConstructors().Single(), - gets.ToArray() - ); + var constructor = tupleTypeList[ nest ].GetConstructors().SingleOrDefault(); + if ( constructor == null ) + { + // arity 0 value tuple +#if DEBUG + Contract.Assert( tupleTypeList[ nest ].GetFullName() == "System.ValueTuple", tupleTypeList[ nest ].GetFullName() + " == System.ValueTuple"); +#endif + currentTuple = this.MakeDefaultLiteral( context, tupleTypeList[ nest ] ); + } + else + { + var tempVariable = default( TConstruct ); + + if ( tupleTypeList[ nest ].GetIsValueType() ) + { + // Temp var is required for value type (that is, ValueTuple) + tempVariable = this.DeclareLocal( context, tupleTypeList[ nest ], context.GetUniqueVariableName( "tuple" ) ); + } + + currentTuple = + this.EmitCreateNewObjectExpression( + context, + tempVariable, // Tuple is reference contextType. + constructor, + gets.ToArray() + ); + } } #if DEBUG @@ -403,6 +446,7 @@ tupleTypeList[ nest ].GetConstructors().Single(), MethodName.CreateObjectFromContext, null, null, + true, // isStatic this.TargetType, unpackingContext.Type ), @@ -437,7 +481,8 @@ tupleTypeList[ nest ].GetConstructors().Single(), new MethodDefinition( AdjustName( MethodName.UnpackFromArray, isAsync ), new [] { unpackingContext.Type, this.TargetType }, - typeof( UnpackHelpers ), + TypeDefinition.UnpackHelpersType, + true, // isStatic #if FEATURE_TAP isAsync ? typeof( Task<> ).MakeGenericType( this.TargetType ) : #endif // FEATURE_TAP @@ -473,9 +518,7 @@ out constructor context, unpackingContext.Variable, unpackingContext.Constructor, - unpackingContext.VariableType.TryGetRuntimeType() == typeof( DynamicUnpackingContext ) - ? new[] { this.MakeInt32Literal( context, itemTypes.Count ) } - : itemTypes.Select( t => this.MakeDefaultLiteral( context, t ) ).ToArray() + itemTypes.Select( t => this.MakeDefaultLiteral( context, t ) ).ToArray() ) ) ); diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.cs index 0554a3a01..26c4498a6 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerBuilder`2.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -19,11 +19,11 @@ #endregion -- License Terms -- using System; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using MsgPack.Serialization.CollectionSerializers; @@ -35,9 +35,9 @@ namespace MsgPack.Serialization.AbstractSerializers /// The type of the context which holds global information for generating serializer. /// The type of the construct which abstracts code constructs. internal abstract partial class SerializerBuilder : -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if FEATURE_CODEGEN ISerializerCodeGenerator, -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // FEATURE_CODEGEN ISerializerBuilder where TContext : SerializerGenerationContext where TConstruct : class, ICodeConstruct @@ -84,20 +84,20 @@ private static Type DetermineBaseClass( Type targetType, CollectionTraits traits return typeof( EnumerableMessagePackSerializer<,> ).MakeGenericType( targetType, traits.ElementType ); } case CollectionDetailedKind.GenericCollection: -#if !NETFX_35 +#if !NET35 case CollectionDetailedKind.GenericSet: -#endif // !NETFX_35 +#endif // !NET35 case CollectionDetailedKind.GenericList: { return typeof( CollectionMessagePackSerializer<,> ).MakeGenericType( targetType, traits.ElementType ); } -#if !NETFX_35 && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyCollection: case CollectionDetailedKind.GenericReadOnlyList: { return typeof( ReadOnlyCollectionMessagePackSerializer<,> ).MakeGenericType( targetType, traits.ElementType ); } -#endif // !NETFX_35 && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericDictionary: { var keyValuePairGenericArguments = traits.ElementType.GetGenericArguments(); @@ -108,7 +108,7 @@ private static Type DetermineBaseClass( Type targetType, CollectionTraits traits keyValuePairGenericArguments[ 1 ] ); } -#if !NETFX_35 && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyDictionary: { var keyValuePairGenericArguments = traits.ElementType.GetGenericArguments(); @@ -119,7 +119,7 @@ keyValuePairGenericArguments[ 1 ] keyValuePairGenericArguments[ 1 ] ); } -#endif // !NETFX_35 && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.NonGenericEnumerable: { return typeof( NonGenericEnumerableMessagePackSerializer<> ).MakeGenericType( targetType ); @@ -184,7 +184,7 @@ protected SerializerBuilder( Type targetType, CollectionTraits collectionTraits /// Newly created serializer object. /// This value will not be null. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] public MessagePackSerializer BuildSerializerInstance( SerializationContext context, Type concreteType, PolymorphismSchema schema ) { #if DEBUG @@ -205,7 +205,13 @@ public MessagePackSerializer BuildSerializerInstance( SerializationContext conte { SerializationTarget targetInfo; this.BuildSerializer( codeGenerationContext, concreteType, schema, out targetInfo ); - constructor = this.CreateSerializerConstructor( codeGenerationContext, targetInfo, schema ); + constructor = + this.CreateSerializerConstructor( + codeGenerationContext, + targetInfo, + schema, + targetInfo == null ? default( SerializerCapabilities? ) : targetInfo.GetCapabilitiesForObject() + ); } if ( constructor != null ) @@ -237,10 +243,6 @@ public MessagePackSerializer BuildSerializerInstance( SerializationContext conte /// The substitution type if is abstract type. null when is not abstract type. /// The schema which contains schema for collection items, dictionary keys, or tuple items. This value may be null. /// The parsed serialization target information. - /// - /// Newly created serializer object. - /// This value will not be null. - /// protected void BuildSerializer( TContext context, Type concreteType, PolymorphismSchema schema, out SerializationTarget targetInfo ) { #if DEBUG @@ -253,8 +255,7 @@ protected void BuildSerializer( TContext context, Type concreteType, Polymorphis case CollectionKind.Array: case CollectionKind.Map: { - targetInfo = null; - this.BuildCollectionSerializer( context, concreteType, schema ); + this.BuildCollectionSerializer( context, concreteType, schema, out targetInfo ); break; } case CollectionKind.NotCollection: @@ -265,7 +266,7 @@ protected void BuildSerializer( TContext context, Type concreteType, Polymorphis targetInfo = null; this.BuildNullableSerializer( context, nullableUnderlyingType ); } -#if !NETFX_35 +#if !NET35 else if ( TupleItems.IsTuple( this.TargetType ) ) { this.BuildTupleSerializer( context, ( schema ?? PolymorphismSchema.Default ).ChildSchemaList, out targetInfo ); @@ -276,7 +277,7 @@ protected void BuildSerializer( TContext context, Type concreteType, Polymorphis #if DEBUG Contract.Assert( schema == null || schema.UseDefault ); #endif // DEBUG - this.BuildObjectSerializer( context, out targetInfo ); + targetInfo = this.BuildObjectSerializer( context ); } break; } @@ -293,6 +294,7 @@ protected void BuildSerializer( TContext context, Type concreteType, Polymorphis /// The code generation context. /// The parsed serialization target information. /// The polymorphism schema of this. + /// The capabilities of the generating serializer. /// /// which refers newly created constructor. /// This value will not be null. @@ -300,7 +302,8 @@ protected void BuildSerializer( TContext context, Type concreteType, Polymorphis protected abstract Func CreateSerializerConstructor( TContext codeGenerationContext, SerializationTarget targetInfo, - PolymorphismSchema schema + PolymorphismSchema schema, + SerializerCapabilities? capabilities ); /// @@ -316,7 +319,7 @@ TContext codeGenerationContext ); -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if FEATURE_CODEGEN /// /// Builds the serializer code using specified code generation context. /// @@ -358,7 +361,7 @@ protected virtual void BuildSerializerCodeCore( ISerializerCodeGenerationContext throw new NotSupportedException(); } -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // FEATURE_CODEGEN internal class SerializerBuilderNilImplicationHandler : NilImplicationHandler @@ -529,4 +532,4 @@ TConstruct store } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerGenerationContext.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerGenerationContext.cs index f3015112e..103252f1e 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerGenerationContext.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerGenerationContext.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; @@ -75,6 +75,15 @@ public virtual TConstruct Context /// public TConstruct PackToTarget { get; protected set; } + /// + /// Gets the code construct which represents the argument for the single argument for null checking. + /// + /// + /// The code construct which represents the argument for the single argument for null checking. + /// This value will not be null. + /// + public TConstruct NullCheckTarget { get; protected set; } + /// /// Gets the code construct which represents the argument for the unpacker. /// @@ -221,8 +230,8 @@ public virtual TConstruct Context /// The specified method has not been declared yet. public MethodDefinition GetDeclaredMethod( string name ) { - MethodDefinition method; - if ( !this._declaredMethods.TryGetValue( name, out method ) ) + var method = this.TryGetDeclaredMethod( name ); + if ( method == null ) { throw new InvalidOperationException( String.Format( @@ -235,6 +244,24 @@ public MethodDefinition GetDeclaredMethod( string name ) return method; } + /// + /// Gets the declared method. + /// + /// The name of the method. + /// + /// The . This value will be null when the specified method is not declared. + /// + /// The specified method has not been declared yet. + public MethodDefinition TryGetDeclaredMethod( string name ) + { + MethodDefinition method; + if ( !this._declaredMethods.TryGetValue( name, out method ) ) + { + return null; + } + return method; + } + /// /// Determines whether specified named private method is already declared or not. /// @@ -345,6 +372,21 @@ protected SerializerGenerationContext( SerializationContext context ) /// Type of base class of the target. public void Reset( Type targetType, Type baseClass ) { + this.Packer = default( TConstruct ); + this.PackToTarget = default( TConstruct ); + this.NullCheckTarget = default ( TConstruct ); + this.Unpacker = default( TConstruct ); + this.UnpackToTarget = default( TConstruct ); + this.CollectionToBeAdded = default( TConstruct ); + this.ItemToAdd = default( TConstruct ); + this.KeyToAdd = default( TConstruct ); + this.ValueToAdd = default( TConstruct ); + this.InitialCapacity = default( TConstruct ); + this.UnpackingContextInUnpackValueMethods = default( TConstruct ); + this.UnpackingContextInSetValueMethods = default( TConstruct ); + this.UnpackingContextInCreateObjectFromContext = default( TConstruct ); + this.IndexOfItem = default( TConstruct ); + this.ItemsCount = default( TConstruct ); this.ResetCore( targetType, baseClass ); this._declaredMethods.Clear(); this._declaredFields.Clear(); diff --git a/src/MsgPack/Serialization/AbstractSerializers/SerializerSpecification.cs b/src/MsgPack/Serialization/AbstractSerializers/SerializerSpecification.cs index 047f6a620..1e4bcbc70 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/SerializerSpecification.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/SerializerSpecification.cs @@ -20,11 +20,11 @@ using System; #if DEBUG -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 #endif // DEBUG namespace MsgPack.Serialization.AbstractSerializers diff --git a/src/MsgPack/Serialization/AbstractSerializers/TypeDefinition.cs b/src/MsgPack/Serialization/AbstractSerializers/TypeDefinition.cs index c84f1005f..5a84773c3 100644 --- a/src/MsgPack/Serialization/AbstractSerializers/TypeDefinition.cs +++ b/src/MsgPack/Serialization/AbstractSerializers/TypeDefinition.cs @@ -19,13 +19,19 @@ #endregion -- License Terms -- using System; -#if CORE_CLR +using System.Collections.Generic; +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; +using System.Reflection; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP using MsgPack.Serialization.Reflection; @@ -38,6 +44,47 @@ internal class TypeDefinition { private static readonly TypeDefinition[] EmptyArray = new TypeDefinition[ 0 ]; + public static readonly TypeDefinition ObjectType = Object( typeof( object ) ); + public static readonly TypeDefinition ByteType = Object( typeof( byte ) ); + public static readonly TypeDefinition SByteType = Object( typeof( sbyte ) ); + public static readonly TypeDefinition Int16Type = Object( typeof( short ) ); + public static readonly TypeDefinition UInt16Type = Object( typeof( ushort ) ); + public static readonly TypeDefinition Int32Type = Object( typeof( int ) ); + public static readonly TypeDefinition UInt32Type = Object( typeof( uint ) ); + public static readonly TypeDefinition Int64Type = Object( typeof( long ) ); + public static readonly TypeDefinition UInt64Type = Object( typeof( ulong ) ); + public static readonly TypeDefinition SingleType = Object( typeof( float ) ); + public static readonly TypeDefinition DoubleType = Object( typeof( double ) ); + public static readonly TypeDefinition BooleanType = Object( typeof( bool ) ); + public static readonly TypeDefinition CharType = Object( typeof( char ) ); + public static readonly TypeDefinition StringType = Object( typeof( string ) ); + public static readonly TypeDefinition VoidType = Object( typeof( void ) ); + public static readonly TypeDefinition ObjectArrayType = Array( ObjectType ); + public static readonly TypeDefinition TypeType = Object( typeof( Type ) ); + public static readonly TypeDefinition MethodBaseType = Object( typeof( MethodBase ) ); + public static readonly TypeDefinition FieldInfoType = Object( typeof( FieldInfo ) ); + // ReSharper disable once InconsistentNaming + public static readonly TypeDefinition IListOfStringType = Object( typeof( IList ) ); + public static readonly TypeDefinition DictionaryOfStringAndTypeType = Object( typeof( Dictionary ) ); + public static readonly TypeDefinition MessagePackObjectType = Object( typeof( MessagePackObject ) ); + public static readonly TypeDefinition PackerType = Object( typeof( Packer ) ); + public static readonly TypeDefinition UnpackerType = Object( typeof( Unpacker ) ); + public static readonly TypeDefinition PackHelpersType = Object( typeof( PackHelpers ) ); + public static readonly TypeDefinition UnpackHelpersType = Object( typeof( UnpackHelpers ) ); + public static readonly TypeDefinition NilImplicationType = Object( typeof( NilImplication ) ); + public static readonly TypeDefinition SerializationMethodType = Object( typeof( SerializationMethod ) ); + public static readonly TypeDefinition EnumSerializationMethodType = Object( typeof( EnumSerializationMethod ) ); + public static readonly TypeDefinition EnumMemberSerializationMethodType = Object( typeof( EnumMemberSerializationMethod ) ); + public static readonly TypeDefinition DateTimeConversionMethodType = Object( typeof( DateTimeConversionMethod ) ); + public static readonly TypeDefinition DateTimeMemberConversionMethodType = Object( typeof( DateTimeMemberConversionMethod ) ); + public static readonly TypeDefinition PackingOptionsType = Object( typeof( PackingOptions ) ); + public static readonly TypeDefinition PolymorphismSchemaType = Object( typeof( PolymorphismSchema ) ); + public static readonly TypeDefinition PolymorphismSchemaArrayType = Array( PolymorphismSchemaType ); +#if FEATURE_TAP + public static readonly TypeDefinition CancellationTokenType = Object( typeof( CancellationToken ) ); + public static readonly TypeDefinition TaskType = Object( typeof( Task ) ); +#endif // FEATURE_TAP + private readonly Flags _flags; public bool IsArray @@ -50,6 +97,13 @@ public bool IsValueType get { return ( this._runtimeType != null && this._runtimeType.GetIsValueType() ) || ( this._flags & Flags.ValueType ) != 0; } } +#if DEBUG + public bool IsRef + { + get { return ( this._runtimeType != null && this._runtimeType.IsByRef ) || ( this._flags & Flags.Ref ) != 0; } + } +#endif // DEBUG + public readonly string TypeName; private readonly Type _runtimeType; @@ -74,7 +128,7 @@ public Type ResolveRuntimeType() private Type ResolveRuntimeType( bool throws ) { - if ( this._runtimeType == null ) + if ( this._runtimeType == null && this.ElementType == null ) { if ( throws ) { @@ -88,7 +142,13 @@ private Type ResolveRuntimeType( bool throws ) } } - if ( this._runtimeType.GetIsGenericTypeDefinition() ) + var resolvingType = this._runtimeType ?? this.ElementType.TryGetRuntimeType() ?? this.ElementType.ResolveRuntimeType( false ); + if ( resolvingType == null ) + { + return null; + } + + if ( resolvingType.GetIsGenericTypeDefinition() ) { var arguments = this.GenericArguments.Select( t => t.ResolveRuntimeType( throws ) ).ToArray(); if ( arguments.Any( a => a == null ) ) @@ -109,14 +169,21 @@ private Type ResolveRuntimeType( bool throws ) } } - this._resolvedType = this._runtimeType.MakeGenericType( arguments ); + resolvingType = resolvingType.MakeGenericType( arguments ); + } + + if ( ( this._flags & Flags.Array ) != 0 ) + { + resolvingType = resolvingType.MakeArrayType(); } - else + + if ( ( this._flags & Flags.Ref ) != 0 ) { - this._resolvedType = this._runtimeType; + resolvingType = resolvingType.MakeByRefType(); } - return this._resolvedType; + this._resolvedType = resolvingType; + return resolvingType; } @@ -126,6 +193,13 @@ private Type ResolveRuntimeType( bool throws ) private TypeDefinition( Type runtimeType, string name, TypeDefinition elementType, Flags flags, params TypeDefinition[] genericArguments ) { +#if DEBUG + Contract.Assert( + runtimeType == null || !runtimeType.GetIsGenericTypeDefinition() || runtimeType.GetGenericTypeParameters().Length == genericArguments.Length, + runtimeType?.GetFullName() + " == <" + String.Join( ", ", genericArguments.Select( t => t.ToString() ).ToArray() ) + ">" + ); +#endif // DEBUG + this.TypeName = name; this._runtimeType = runtimeType; this._flags = flags; @@ -143,6 +217,11 @@ public static TypeDefinition Object( string name ) return new TypeDefinition( null, name, null, Flags.None ); } + public static TypeDefinition GenericValueType( Type definition, params TypeDefinition[] arguments ) + { + return Generic( true, definition, arguments ); + } + public static TypeDefinition GenericReferenceType( Type definition, params TypeDefinition[] arguments ) { return Generic( false, definition, arguments ); @@ -168,18 +247,28 @@ public static TypeDefinition Array( TypeDefinition elementType ) { return elementType.HasRuntimeTypeFully() - ? new TypeDefinition( elementType.ResolveRuntimeType().MakeArrayType(), elementType.ResolveRuntimeType().FullName, elementType, Flags.HasRuntimeType ) + ? new TypeDefinition( elementType.ResolveRuntimeType().MakeArrayType(), elementType.ResolveRuntimeType().FullName + "[]", elementType, Flags.HasRuntimeType ) : new TypeDefinition( null, elementType.TypeName, elementType, Flags.Array ); } + public static TypeDefinition ManagedReference( TypeDefinition elementType ) + { + return + elementType.HasRuntimeTypeFully() + ? new TypeDefinition( elementType.ResolveRuntimeType().MakeByRefType(), elementType.ResolveRuntimeType().FullName, elementType, Flags.HasRuntimeType ) + : new TypeDefinition( null, elementType.TypeName, elementType, Flags.Ref ); + } + public override string ToString() { return this._runtimeType != null ? ( ( this.ResolveRuntimeType( false ) ?? this._runtimeType ) ).GetFullName() : ( this._flags & Flags.Array ) != 0 - ? ( this.TypeName + "[]" ) - : this.TypeName; + ? ( this.TypeName + "[]" ) + : ( this._flags & Flags.Ref ) != 0 + ? ( this.TypeName + "&" ) + : this.TypeName; } public static implicit operator TypeDefinition( Type type ) @@ -193,6 +282,7 @@ private enum Flags None = 0, Array = 0x1, ValueType = 0x2, + Ref = 0x4, HasRuntimeType = unchecked( ( int )0x80000000 ) } } diff --git a/src/MsgPack/Serialization/BindingOptions.cs b/src/MsgPack/Serialization/BindingOptions.cs new file mode 100644 index 000000000..29090576d --- /dev/null +++ b/src/MsgPack/Serialization/BindingOptions.cs @@ -0,0 +1,92 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke and contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Contributors: +// Shrenik Jhaveri (ShrenikOne) +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MsgPack.Serialization +{ + /// + /// The Binding Options provide serializer clue on including property/field as part of packing. + /// + public class BindingOptions + { + /// + /// Private mapping of types & their member skip list, which needs to ignore as part of serialization. + /// + private readonly IDictionary> _typeIgnoringMembersMap = new Dictionary>(); + + /// + /// Sets the member skip list for a specific target type. + /// + /// Type of the target. + /// The member skip list. + public void SetIgnoringMembers( Type targetType, IEnumerable memberSkipList ) + { + lock ( this._typeIgnoringMembersMap ) + { + if ( this._typeIgnoringMembersMap.ContainsKey( targetType ) ) + { + this._typeIgnoringMembersMap[ targetType ] = memberSkipList; + } + else + { + this._typeIgnoringMembersMap.Add( targetType, memberSkipList ); + } + } + } + + /// + /// Gets the member skip list for a specific target type. + /// + /// Type of the target. + /// Returns member skip list for a specific target type. + public IEnumerable GetIgnoringMembers( Type targetType ) + { + lock ( this._typeIgnoringMembersMap ) + { + if ( this._typeIgnoringMembersMap.ContainsKey( targetType ) ) + { + return this._typeIgnoringMembersMap[ targetType ]; + } + else + { + return Enumerable.Empty(); + } + } + } + + /// + /// Gets all registered types specific ignoring members. + /// + /// Returns all registered types specific ignoring members. + public IDictionary> GetAllIgnoringMembers() + { + lock ( this._typeIgnoringMembersMap ) + { + return this._typeIgnoringMembersMap.ToDictionary( item => item.Key, item => ( IEnumerable )item.Value.ToArray() ); + } + } + } +} diff --git a/src/MsgPack/Serialization/CodeDomSerializers/CodeDomContext.cs b/src/MsgPack/Serialization/CodeDomSerializers/CodeDomContext.cs index 68c4ae0b5..46a3a1478 100644 --- a/src/MsgPack/Serialization/CodeDomSerializers/CodeDomContext.cs +++ b/src/MsgPack/Serialization/CodeDomSerializers/CodeDomContext.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; @@ -29,7 +32,6 @@ using System.Linq; using System.Reflection; using System.Security; -using System.Text; #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; @@ -50,7 +52,7 @@ internal class CodeDomContext : SerializerGenerationContext, I public const string ConditionalExpressionHelperWhenFalseParameterName = "whenFalse"; private readonly Dictionary _dependentSerializers = new Dictionary(); - private readonly Dictionary _cachedTargetFields = + private readonly Dictionary _cachedTargetFields = new Dictionary(); private readonly Dictionary _cachedPropertyAccessors = new Dictionary(); @@ -59,6 +61,13 @@ internal class CodeDomContext : SerializerGenerationContext, I private readonly SerializerCodeGenerationConfiguration _configuration; +#if DEBUG + internal string Namespace + { + get { return this._configuration.Namespace; } + } +#endif // DEBUG + private Type _targetType; private bool IsDictionary @@ -97,14 +106,14 @@ public string RegisterSerializer( Type targetType, EnumMemberSerializationMethod { fieldName = "_serializer" + this._dependentSerializers.Count.ToString( CultureInfo.InvariantCulture ); this._dependentSerializers.Add( key, fieldName ); - this._buildingType.Members.Add( - new CodeMemberField( - typeof( MessagePackSerializer<> ).MakeGenericType( Type.GetTypeFromHandle( key.TypeHandle ) ), + this._buildingType.Members.Add( + new CodeMemberField( + typeof( MessagePackSerializer<> ).MakeGenericType( Type.GetTypeFromHandle( key.TypeHandle ) ), fieldName ) { Attributes = MemberAttributes.Private - } + } ); } @@ -124,7 +133,7 @@ public string RegisterCachedFieldInfo( FieldInfo field ) { Contract.Assert( field.DeclaringType != null, "field.DeclaringType != null" ); - cachedField = + cachedField = new CachedFieldInfo( field, "_field" + field.DeclaringType.Name.Replace( '`', '_' ) + "_" + field.Name + this._cachedTargetFields.Count.ToString( CultureInfo.InvariantCulture ) @@ -262,21 +271,23 @@ protected override void ResetCore( Type targetType, Type baseClass ) this._cachedPropertyAccessors.Clear(); this._buildingType = declaringType; - this.Packer = CodeDomConstruct.Parameter( typeof( Packer ), "packer" ); - this.PackToTarget = CodeDomConstruct.Parameter( targetType, "objectTree" ); - this.Unpacker = CodeDomConstruct.Parameter( typeof( Unpacker ), "unpacker" ); - this.IndexOfItem = CodeDomConstruct.Parameter( typeof( int ), "indexOfItem" ); - this.ItemsCount = CodeDomConstruct.Parameter( typeof( int ), "itemsCount" ); - this.UnpackToTarget = CodeDomConstruct.Parameter( targetType, "collection" ); - var traits = targetType.GetCollectionTraits( CollectionTraitOptions.Full ); + var targetTypeDefinition = TypeDefinition.Object( targetType ); + this.Packer = CodeDomConstruct.Parameter( TypeDefinition.PackerType, "packer" ); + this.PackToTarget = CodeDomConstruct.Parameter( targetTypeDefinition, "objectTree" ); + this.NullCheckTarget = CodeDomConstruct.Parameter( targetTypeDefinition, "objectTree" ); + this.Unpacker = CodeDomConstruct.Parameter( TypeDefinition.UnpackerType, "unpacker" ); + this.IndexOfItem = CodeDomConstruct.Parameter( TypeDefinition.Int32Type, "indexOfItem" ); + this.ItemsCount = CodeDomConstruct.Parameter( TypeDefinition.Int32Type, "itemsCount" ); + this.UnpackToTarget = CodeDomConstruct.Parameter( targetTypeDefinition, "collection" ); + var traits = targetType.GetCollectionTraits( CollectionTraitOptions.Full, this.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); if ( traits.ElementType != null ) { - this.CollectionToBeAdded = CodeDomConstruct.Parameter( targetType, "collection" ); + this.CollectionToBeAdded = CodeDomConstruct.Parameter( targetTypeDefinition, "collection" ); this.ItemToAdd = CodeDomConstruct.Parameter( traits.ElementType, "item" ); if ( traits.DetailedCollectionType == CollectionDetailedKind.GenericDictionary -#if !NETFX_35 && !NETFX_40 +#if !NET35 && !NET40 || traits.DetailedCollectionType == CollectionDetailedKind.GenericReadOnlyDictionary -#endif // !NETFX_35 && !NETFX_40 +#endif // !NET35 && !NET40 ) { this.KeyToAdd = CodeDomConstruct.Parameter( traits.ElementType.GetGenericArguments()[ 0 ], "key" ); @@ -287,13 +298,13 @@ protected override void ResetCore( Type targetType, Type baseClass ) this.KeyToAdd = null; this.ValueToAdd = null; } - this.InitialCapacity = CodeDomConstruct.Parameter( typeof( int ), "initialCapacity" ); + this.InitialCapacity = CodeDomConstruct.Parameter( TypeDefinition.Int32Type, "initialCapacity" ); } } public override void BeginMethodOverride( string name ) { - this._methodContextStack.Push( new MethodContext( name, false, typeof( object ), SerializerBuilderHelper.EmptyParameters ) ); + this._methodContextStack.Push( new MethodContext( name, false, TypeDefinition.ObjectType, SerializerBuilderHelper.EmptyParameters ) ); } public override void BeginPrivateMethod( string name, bool isStatic, TypeDefinition returnType, params CodeDomConstruct[] parameters ) @@ -306,7 +317,7 @@ public override void BeginPrivateMethod( string name, bool isStatic, TypeDefinit parameters .Select( p => new KeyValuePair( p.AsParameter().Name, p.ContextType ) ) .ToArray() - ) + ) ); } @@ -350,7 +361,7 @@ protected override MethodDefinition EndMethodOverrideCore( string name, CodeDomC codeMethod.Parameters.Add( this.Unpacker.AsParameter() ); codeMethod.Parameters.Add( this.UnpackToTarget.AsParameter() ); // ReSharper disable BitwiseOperatorOnEnumWithoutFlags - codeMethod.Attributes = ( this.IsInternalToMsgPackLibrary? MemberAttributes.FamilyOrAssembly : MemberAttributes.Family ) | MemberAttributes.Override; + codeMethod.Attributes = ( this.IsInternalToMsgPackLibrary ? MemberAttributes.FamilyOrAssembly : MemberAttributes.Family ) | MemberAttributes.Override; // ReSharper restore BitwiseOperatorOnEnumWithoutFlags break; @@ -381,24 +392,24 @@ protected override MethodDefinition EndMethodOverrideCore( string name, CodeDomC if ( this.IsDictionary ) { codeMethod.Parameters.Add( - new CodeParameterDeclarationExpression( - CodeDomSerializerBuilder.ToCodeTypeReference( this.KeyToAdd.ContextType ), + new CodeParameterDeclarationExpression( + CodeDomSerializerBuilder.ToCodeTypeReference( this.KeyToAdd.ContextType ), "key" ) ); codeMethod.Parameters.Add( - new CodeParameterDeclarationExpression( + new CodeParameterDeclarationExpression( CodeDomSerializerBuilder.ToCodeTypeReference( this.ValueToAdd.ContextType ), - "value" + "value" ) ); } else { - codeMethod.Parameters.Add( - new CodeParameterDeclarationExpression( + codeMethod.Parameters.Add( + new CodeParameterDeclarationExpression( CodeDomSerializerBuilder.ToCodeTypeReference( this.ItemToAdd.ContextType ), - "item" + "item" ) ); } @@ -480,6 +491,7 @@ protected override MethodDefinition EndMethodOverrideCore( string name, CodeDomC context.Name, null, null, + context.IsStatic, context.ReturnType, context.Parameters.Select( kv => kv.Value ).ToArray() ); @@ -515,7 +527,7 @@ protected override MethodDefinition EndPrivateMethodCore( string name, CodeDomCo codeMethod.Parameters.AddRange( context.Parameters.Select( kv => - new CodeParameterDeclarationExpression(CodeDomSerializerBuilder.ToCodeTypeReference( kv.Value ), kv.Key ) + new CodeParameterDeclarationExpression( CodeDomSerializerBuilder.ToCodeTypeReference( kv.Value ), kv.Key ) ).ToArray() ); @@ -527,6 +539,7 @@ protected override MethodDefinition EndPrivateMethodCore( string name, CodeDomCo context.Name, null, null, + context.IsStatic, context.ReturnType, context.Parameters.Select( kv => kv.Value ).ToArray() ); @@ -535,7 +548,7 @@ protected override MethodDefinition EndPrivateMethodCore( string name, CodeDomCo // For stack public void BeginConstructor() { - this._methodContextStack.Push( new MethodContext( ".ctor", false, typeof( object ), SerializerBuilderHelper.EmptyParameters ) ); + this._methodContextStack.Push( new MethodContext( ".ctor", false, TypeDefinition.ObjectType, SerializerBuilderHelper.EmptyParameters ) ); } public void EndConstructor() @@ -543,7 +556,7 @@ public void EndConstructor() this._methodContextStack.Pop(); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override void DefineUnpackingContextCore( IList> fields, out TypeDefinition type, @@ -616,9 +629,9 @@ public override CodeDomConstruct DefineUnpackedItemParameterInSetValueMethods( T /// Generates codes for this context. /// /// A collection which correspond to genereated codes. -#if !NETFX_35 +#if !NET35 [SecuritySafeCritical] -#endif // !NETFX_35 +#endif // !NET35 public IEnumerable Generate() { Contract.Assert( this._declaringTypes != null, "_declaringTypes != null" ); @@ -638,42 +651,63 @@ public IEnumerable Generate() Path.Combine( this._configuration.OutputDirectory, this._configuration.Namespace.Replace( Type.Delimiter, Path.DirectorySeparatorChar ) - ); - Directory.CreateDirectory( directory ); + ); + + var sink = this._configuration.CodeGenerationSink ?? CodeGenerationSink.ForIndividualFile(); var result = new List( this._declaringTypes.Count ); + var extension = "." + provider.FileExtension; foreach ( var declaringType in this._declaringTypes ) { - var typeFileName = declaringType.Value.Name; - if ( declaringType.Value.TypeParameters.Count > 0 ) - { - typeFileName += "`" + declaringType.Value.TypeParameters.Count.ToString( CultureInfo.InvariantCulture ); - } - - typeFileName += "." + provider.FileExtension; + Contract.Assert( declaringType.Value.TypeParameters.Count == 0, declaringType.Value.TypeParameters.Count + "!= 0" ); var cn = new CodeNamespace( this._configuration.Namespace ); cn.Types.Add( declaringType.Value ); var cu = new CodeCompileUnit(); cu.Namespaces.Add( cn ); - var filePath = Path.Combine( directory, typeFileName ); - result.Add( - new SerializerCodeGenerationResult( - declaringType.Key, - filePath, + var codeInfo = new SerializerCodeInformation( declaringType.Value.Name, directory, extension ); + sink.AssignTextWriter( codeInfo ); + + result.Add( + new SerializerCodeGenerationResult( + declaringType.Key, + codeInfo.FilePath, String.IsNullOrEmpty( cn.Name ) ? declaringType.Value.Name - : cn.Name + "." + declaringType.Value.Name, - cn.Name, + : cn.Name + "." + declaringType.Value.Name, + cn.Name, declaringType.Value.Name ) ); - using ( var writer = new StreamWriter( filePath, false, Encoding.UTF8 ) ) +#if DEBUG + if ( SerializerDebugging.DumpEnabled ) + { + SerializerDebugging.TraceEmitEvent( "Compile {0}", declaringType.Value.Name ); + } +#endif // DEBUG + + using ( var writer = +#if DEBUG + SerializerDebugging.DumpEnabled + ? new TeeTextWriter( codeInfo.TextWriter ?? NullTextWriter.Instance, SerializerDebugging.ILTraceWriter ) : +#endif // DEBUG + codeInfo.TextWriter ?? NullTextWriter.Instance + ) { provider.GenerateCodeFromCompileUnit( cu, writer, options ); + writer.WriteLine(); + writer.Flush(); + +#if DEBUG + if ( SerializerDebugging.DumpEnabled ) + { + SerializerDebugging.TraceEmitEvent( "Compile {0}", declaringType.Value.Name ); + SerializerDebugging.FlushTraceData(); + } +#endif // DEBUG } } @@ -681,21 +715,6 @@ public IEnumerable Generate() } } - /// - /// Creates the for on-the-fly code generation for execution. - /// - /// - /// The newly created for on-the-fly code generation for execution. - /// - public CodeCompileUnit CreateCodeCompileUnit() - { - var cn = new CodeNamespace( this._configuration.Namespace ); - cn.Types.Add( this._buildingType ); - var cu = new CodeCompileUnit(); - cu.Namespaces.Add( cn ); - return cu; - } - public struct CachedFieldInfo { public readonly string StorageFieldName; diff --git a/src/MsgPack/Serialization/CodeDomSerializers/CodeDomSerializerBuilder.cs b/src/MsgPack/Serialization/CodeDomSerializers/CodeDomSerializerBuilder.cs index 72812244d..7aa3f6aec 100644 --- a/src/MsgPack/Serialization/CodeDomSerializers/CodeDomSerializerBuilder.cs +++ b/src/MsgPack/Serialization/CodeDomSerializers/CodeDomSerializerBuilder.cs @@ -20,13 +20,11 @@ using System; using System.CodeDom; -using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; -using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Security; @@ -37,6 +35,7 @@ using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.CollectionSerializers; +using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.CodeDomSerializers { @@ -112,65 +111,65 @@ protected override CodeDomConstruct MakeNullLiteral( CodeDomContext context, Typ protected override CodeDomConstruct MakeByteLiteral( CodeDomContext context, byte constant ) { - return CodeDomConstruct.Expression( typeof( byte ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.ByteType, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeSByteLiteral( CodeDomContext context, sbyte constant ) { - return CodeDomConstruct.Expression( typeof( sbyte ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.SByteType, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeInt16Literal( CodeDomContext context, short constant ) { - return CodeDomConstruct.Expression( typeof( short ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.Int16Type, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeUInt16Literal( CodeDomContext context, ushort constant ) { - return CodeDomConstruct.Expression( typeof( ushort ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.UInt16Type, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeInt32Literal( CodeDomContext context, int constant ) { - return CodeDomConstruct.Expression( typeof( int ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.Int32Type, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeUInt32Literal( CodeDomContext context, uint constant ) { - return CodeDomConstruct.Expression( typeof( uint ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.UInt32Type, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeInt64Literal( CodeDomContext context, long constant ) { - return CodeDomConstruct.Expression( typeof( long ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.Int64Type, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeUInt64Literal( CodeDomContext context, ulong constant ) { - return CodeDomConstruct.Expression( typeof( ulong ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.UInt64Type, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeReal32Literal( CodeDomContext context, float constant ) { - return CodeDomConstruct.Expression( typeof( float ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.SingleType, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeReal64Literal( CodeDomContext context, double constant ) { - return CodeDomConstruct.Expression( typeof( double ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.DoubleType, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeBooleanLiteral( CodeDomContext context, bool constant ) { - return CodeDomConstruct.Expression( typeof( bool ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.BooleanType, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct MakeCharLiteral( CodeDomContext context, char constant ) { - return CodeDomConstruct.Expression( typeof( char ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.CharType, new CodePrimitiveExpression( constant ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct MakeEnumLiteral( CodeDomContext context, TypeDefinition type, object constant ) { var asString = constant.ToString(); @@ -208,7 +207,7 @@ protected override CodeDomConstruct MakeDefaultLiteral( CodeDomContext context, protected override CodeDomConstruct MakeStringLiteral( CodeDomContext context, string constant ) { - return CodeDomConstruct.Expression( typeof( string ), new CodePrimitiveExpression( constant ) ); + return CodeDomConstruct.Expression( TypeDefinition.StringType, new CodePrimitiveExpression( constant ) ); } protected override CodeDomConstruct EmitThisReferenceExpression( CodeDomContext context ) @@ -216,13 +215,13 @@ protected override CodeDomConstruct EmitThisReferenceExpression( CodeDomContext return CodeDomConstruct.Expression( typeof( MessagePackSerializer<> ).MakeGenericType( this.TargetType ), new CodeThisReferenceExpression() ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitBoxExpression( CodeDomContext context, TypeDefinition valueType, CodeDomConstruct value ) { - return CodeDomConstruct.Expression( typeof( object ), new CodeCastExpression( typeof( object ), value.AsExpression() ) ); + return CodeDomConstruct.Expression( TypeDefinition.ObjectType, new CodeCastExpression( typeof( object ), value.AsExpression() ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitUnboxAnyExpression( CodeDomContext context, TypeDefinition targetType, CodeDomConstruct value ) { return @@ -232,12 +231,12 @@ protected override CodeDomConstruct EmitUnboxAnyExpression( CodeDomContext conte ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitNotExpression( CodeDomContext context, CodeDomConstruct booleanExpression ) { return CodeDomConstruct.Expression( - typeof( bool ), + TypeDefinition.BooleanType, new CodeBinaryOperatorExpression( booleanExpression.AsExpression(), CodeBinaryOperatorType.ValueEquality, @@ -246,13 +245,13 @@ protected override CodeDomConstruct EmitNotExpression( CodeDomContext context, C ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitEqualsExpression( CodeDomContext context, CodeDomConstruct left, CodeDomConstruct right ) { return CodeDomConstruct.Expression( - typeof( bool ), + TypeDefinition.BooleanType, new CodeBinaryOperatorExpression( left.AsExpression(), CodeBinaryOperatorType.ValueEquality, @@ -261,13 +260,13 @@ protected override CodeDomConstruct EmitEqualsExpression( CodeDomContext context ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGreaterThanExpression( CodeDomContext context, CodeDomConstruct left, CodeDomConstruct right ) { return CodeDomConstruct.Expression( - typeof( bool ), + TypeDefinition.BooleanType, new CodeBinaryOperatorExpression( left.AsExpression(), CodeBinaryOperatorType.GreaterThan, @@ -276,13 +275,13 @@ protected override CodeDomConstruct EmitGreaterThanExpression( CodeDomContext co ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitLessThanExpression( CodeDomContext context, CodeDomConstruct left, CodeDomConstruct right ) { return CodeDomConstruct.Expression( - typeof( bool ), + TypeDefinition.BooleanType, new CodeBinaryOperatorExpression( left.AsExpression(), CodeBinaryOperatorType.LessThan, @@ -291,7 +290,7 @@ protected override CodeDomConstruct EmitLessThanExpression( CodeDomContext conte ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitIncrement( CodeDomContext context, CodeDomConstruct int32Value ) { return @@ -309,15 +308,15 @@ protected override CodeDomConstruct EmitIncrement( CodeDomContext context, CodeD protected override CodeDomConstruct EmitTypeOfExpression( CodeDomContext context, TypeDefinition type ) { - return CodeDomConstruct.Expression( typeof( Type ), new CodeTypeOfExpression( ToCodeTypeReference( type ) ) ); + return CodeDomConstruct.Expression( TypeDefinition.TypeType, new CodeTypeOfExpression( ToCodeTypeReference( type ) ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override CodeDomConstruct EmitFieldOfExpression( CodeDomContext context, FieldInfo field ) { return CodeDomConstruct.Expression( - typeof( FieldInfo ), + TypeDefinition.FieldInfoType, new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), context.RegisterCachedFieldInfo( @@ -327,12 +326,12 @@ protected override CodeDomConstruct EmitFieldOfExpression( CodeDomContext contex ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override CodeDomConstruct EmitMethodOfExpression( CodeDomContext context, MethodBase method ) { return CodeDomConstruct.Expression( - typeof( MethodBase ), + TypeDefinition.MethodBaseType, new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), context.RegisterCachedMethodBase( @@ -342,16 +341,23 @@ protected override CodeDomConstruct EmitMethodOfExpression( CodeDomContext conte ); } + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + protected override CodeDomConstruct EmitThrowStatement( CodeDomContext context, CodeDomConstruct exception ) + { + return CodeDomConstruct.Statement( new CodeThrowExceptionStatement( exception.AsExpression() ) ); + } + protected override CodeDomConstruct EmitSequentialStatements( CodeDomContext context, TypeDefinition contextType, IEnumerable statements ) { #if DEBUG statements = statements.ToArray(); Contract.Assert( statements.All( c => c.IsStatement ) ); #endif - return CodeDomConstruct.Statement( statements.SelectMany( s => s.AsStatements() ) ); + return CodeDomConstruct.Statement( statements.SelectMany( s => s.AsStatements().ToArray() ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override CodeDomConstruct DeclareLocal( CodeDomContext context, TypeDefinition nestedType, string name ) { #if DEBUG @@ -368,11 +374,11 @@ protected override CodeDomConstruct ReferArgument( CodeDomContext context, TypeD return CodeDomConstruct.Parameter( type, name ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitCreateNewObjectExpression( CodeDomContext context, CodeDomConstruct variable, ConstructorDefinition constructor, params CodeDomConstruct[] arguments ) { #if DEBUG - Contract.Assert( constructor.DeclaringType != null ); + Contract.Assert( constructor?.DeclaringType != null ); Contract.Assert( arguments.All( c => c.IsExpression ), String.Join( ",", arguments.Select( c => c.ToString() ).ToArray() ) ); #endif return @@ -385,7 +391,13 @@ protected override CodeDomConstruct EmitCreateNewObjectExpression( CodeDomContex ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated" )] + protected override CodeDomConstruct EmitMakeRef( CodeDomContext context, CodeDomConstruct target ) + { + return CodeDomConstruct.Expression( target.ContextType, new CodeDirectionExpression( FieldDirection.Ref, target.AsExpression() ) ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitInvokeVoidMethod( CodeDomContext context, CodeDomConstruct instance, MethodDefinition method, params CodeDomConstruct[] arguments ) { #if DEBUG @@ -402,7 +414,7 @@ protected override CodeDomConstruct EmitInvokeVoidMethod( CodeDomContext context ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitInvokeMethodExpression( CodeDomContext context, CodeDomConstruct instance, MethodDefinition method, IEnumerable arguments ) { #if DEBUG @@ -460,7 +472,7 @@ private static CodeMethodInvokeExpression CreateMethodInvocation( MethodDefiniti ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitInvokeDelegateExpression( CodeDomContext context, TypeDefinition delegateReturnType, CodeDomConstruct @delegate, params CodeDomConstruct[] arguments ) { #if DEBUG @@ -482,7 +494,7 @@ protected override CodeDomConstruct EmitInvokeDelegateExpression( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGetPropertyExpression( CodeDomContext context, CodeDomConstruct instance, PropertyInfo property ) { #if DEBUG @@ -501,7 +513,7 @@ protected override CodeDomConstruct EmitGetPropertyExpression( CodeDomContext co ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGetFieldExpression( CodeDomContext context, CodeDomConstruct instance, FieldDefinition field ) { #if DEBUG @@ -520,8 +532,8 @@ protected override CodeDomConstruct EmitGetFieldExpression( CodeDomContext conte ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override CodeDomConstruct EmitSetProperty( CodeDomContext context, CodeDomConstruct instance, PropertyInfo property, CodeDomConstruct value ) { #if DEBUG @@ -543,9 +555,9 @@ protected override CodeDomConstruct EmitSetProperty( CodeDomContext context, Cod ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "5", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "5", Justification = "Validated internally" )] protected override CodeDomConstruct EmitSetIndexedProperty( CodeDomContext context, CodeDomConstruct instance, TypeDefinition declaringType, string proeprtyName, CodeDomConstruct key, CodeDomConstruct value ) { #if DEBUG @@ -568,8 +580,8 @@ protected override CodeDomConstruct EmitSetIndexedProperty( CodeDomContext conte ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override CodeDomConstruct EmitSetField( CodeDomContext context, CodeDomConstruct instance, FieldDefinition field, CodeDomConstruct value ) { #if DEBUG @@ -591,7 +603,7 @@ protected override CodeDomConstruct EmitSetField( CodeDomContext context, CodeDo ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "Validated internally" )] protected override CodeDomConstruct EmitSetField( CodeDomContext context, CodeDomConstruct instance, TypeDefinition nestedType, string fieldName, CodeDomConstruct value ) { #if DEBUG @@ -612,14 +624,14 @@ protected override CodeDomConstruct EmitSetField( CodeDomContext context, CodeDo ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitLoadVariableExpression( CodeDomContext context, CodeDomConstruct variable ) { return CodeDomConstruct.Expression( variable.ContextType, variable.AsExpression() ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitStoreVariableStatement( CodeDomContext context, CodeDomConstruct variable, CodeDomConstruct value ) { #if DEBUG @@ -635,8 +647,8 @@ protected override CodeDomConstruct EmitStoreVariableStatement( CodeDomContext c ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitTryFinally( CodeDomContext context, CodeDomConstruct tryStatement, CodeDomConstruct finallyStatement ) { #if DEBUG @@ -653,7 +665,7 @@ protected override CodeDomConstruct EmitTryFinally( CodeDomContext context, Code ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitCreateNewArrayExpression( CodeDomContext context, TypeDefinition elementType, int length ) { return @@ -666,7 +678,7 @@ protected override CodeDomConstruct EmitCreateNewArrayExpression( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitCreateNewArrayExpression( CodeDomContext context, TypeDefinition elementType, int length, IEnumerable initialElements ) { #if DEBUG @@ -686,8 +698,8 @@ protected override CodeDomConstruct EmitCreateNewArrayExpression( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGetArrayElementExpression( CodeDomContext context, CodeDomConstruct array, CodeDomConstruct index ) { return @@ -697,9 +709,9 @@ protected override CodeDomConstruct EmitGetArrayElementExpression( CodeDomContex ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override CodeDomConstruct EmitSetArrayElementStatement( CodeDomContext context, CodeDomConstruct array, CodeDomConstruct index, CodeDomConstruct value ) { return @@ -711,7 +723,7 @@ protected override CodeDomConstruct EmitSetArrayElementStatement( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGetSerializerExpression( CodeDomContext context, Type targetType, SerializingMember? memberInfo, PolymorphismSchema itemsSchema ) { return @@ -733,7 +745,7 @@ protected override CodeDomConstruct EmitGetSerializerExpression( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGetActionsExpression( CodeDomContext context, ActionType actionType, bool isAsync ) { TypeDefinition type; @@ -752,7 +764,7 @@ protected override CodeDomConstruct EmitGetActionsExpression( CodeDomContext con } case ActionType.PackToMap: { - type = + type = #if FEATURE_TAP isAsync ? typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,,,> ).MakeGenericType( typeof( Packer ), this.TargetType, typeof( CancellationToken ), typeof( Task ) ) ) : #endif // FEATURE_TAP @@ -760,6 +772,12 @@ protected override CodeDomConstruct EmitGetActionsExpression( CodeDomContext con name = FieldName.PackOperationTable; break; } + case ActionType.IsNull: + { + type = typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,> ).MakeGenericType( this.TargetType, typeof( bool ) ) ); + name = FieldName.NullCheckersTable; + break; + } case ActionType.UnpackFromArray: { type = @@ -769,20 +787,20 @@ protected override CodeDomConstruct EmitGetActionsExpression( CodeDomContext con isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,,> ), - typeof( Unpacker ), + TypeDefinition.UnpackerType, context.UnpackingContextType ?? this.TargetType, - typeof( int ), - typeof( int ), - typeof( CancellationToken ), - typeof( Task ) + TypeDefinition.Int32Type, + TypeDefinition.Int32Type, + TypeDefinition.CancellationTokenType, + TypeDefinition.TaskType ) : #endif // FEATURE_TAP TypeDefinition.GenericReferenceType( typeof( Action<,,,> ), - typeof( Unpacker ), + TypeDefinition.UnpackerType, context.UnpackingContextType ?? this.TargetType, - typeof( int ), - typeof( int ) + TypeDefinition.Int32Type, + TypeDefinition.Int32Type ) ); name = FieldName.UnpackOperationList; @@ -793,25 +811,25 @@ protected override CodeDomConstruct EmitGetActionsExpression( CodeDomContext con type = TypeDefinition.GenericReferenceType( typeof( IDictionary<,> ), - typeof( string ), + TypeDefinition.StringType, #if FEATURE_TAP isAsync ? TypeDefinition.GenericReferenceType( typeof( Func<,,,,,> ), - typeof( Unpacker ), + TypeDefinition.UnpackerType, context.UnpackingContextType ?? this.TargetType, - typeof( int ), - typeof( int ), - typeof( CancellationToken ), - typeof( Task ) + TypeDefinition.Int32Type, + TypeDefinition.Int32Type, + TypeDefinition.CancellationTokenType, + TypeDefinition.TaskType ) : #endif // FEATURE_TAP TypeDefinition.GenericReferenceType( typeof( Action<,,,> ), - typeof( Unpacker ), + TypeDefinition.UnpackerType, context.UnpackingContextType ?? this.TargetType, - typeof( int ), - typeof( int ) + TypeDefinition.Int32Type, + TypeDefinition.Int32Type ) ); name = FieldName.UnpackOperationTable; @@ -850,14 +868,14 @@ protected override CodeDomConstruct EmitGetActionsExpression( CodeDomContext con ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override CodeDomConstruct EmitGetMemberNamesExpression( CodeDomContext context ) { - var field = context.DeclarePrivateField( FieldName.MemberNames, typeof( IList ) ); + var field = context.DeclarePrivateField( FieldName.MemberNames, TypeDefinition.IListOfStringType ); return CodeDomConstruct.Expression( - typeof( IList ), + TypeDefinition.IListOfStringType, new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), field.FieldName @@ -865,7 +883,7 @@ protected override CodeDomConstruct EmitGetMemberNamesExpression( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitFinishFieldInitializationStatement( CodeDomContext context, string name, CodeDomConstruct value ) { return @@ -880,8 +898,8 @@ protected override CodeDomConstruct EmitFinishFieldInitializationStatement( Code ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitConditionalExpression( CodeDomContext context, CodeDomConstruct conditionExpression, CodeDomConstruct thenExpression, CodeDomConstruct elseExpression ) { #if DEBUG @@ -941,8 +959,8 @@ private static CodeDomConstruct CreateConditionalExpression( CodeDomContext cont ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override CodeDomConstruct EmitAndConditionalExpression( CodeDomContext context, IList conditionExpressions, CodeDomConstruct thenExpression, CodeDomConstruct elseExpression ) { #if DEBUG @@ -969,7 +987,7 @@ protected override CodeDomConstruct EmitAndConditionalExpression( CodeDomContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitRetrunStatement( CodeDomContext context, CodeDomConstruct expression ) { #if DEBUG @@ -981,10 +999,10 @@ protected override CodeDomConstruct EmitRetrunStatement( CodeDomContext context, ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override CodeDomConstruct EmitForEachLoop( CodeDomContext context, CollectionTraits collectionTraits, CodeDomConstruct collection, Func loopBodyEmitter ) { #if DEBUG @@ -1072,12 +1090,12 @@ protected override CodeDomConstruct EmitForEachLoop( CodeDomContext context, Col return this.EmitSequentialStatements( context, - typeof( void ), + TypeDefinition.VoidType, statements.ToArray() ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitEnumFromUnderlyingCastExpression( CodeDomContext context, Type enumType, @@ -1086,7 +1104,7 @@ protected override CodeDomConstruct EmitEnumFromUnderlyingCastExpression( return CodeDomConstruct.Expression( enumType, new CodeCastExpression( enumType, underlyingValue.AsExpression() ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override CodeDomConstruct EmitEnumToUnderlyingCastExpression( CodeDomContext context, Type underlyingType, @@ -1095,7 +1113,8 @@ protected override CodeDomConstruct EmitEnumToUnderlyingCastExpression( return CodeDomConstruct.Expression( underlyingType, new CodeCastExpression( underlyingType, enumValue.AsExpression() ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override CodeDomConstruct EmitNewPrivateMethodDelegateExpression( CodeDomContext context, MethodDefinition method ) { var delegateBaseType = SerializerBuilderHelper.FindDelegateType( method.ReturnType, method.ParameterTypes ); @@ -1115,7 +1134,7 @@ protected override CodeDomConstruct EmitNewPrivateMethodDelegateExpression( Code delegateType, new CodeDelegateCreateExpression( ToCodeTypeReference( delegateType ), - new CodeThisReferenceExpression(), + method.IsStatic ? new CodeTypeReferenceExpression( context.DeclaringType.Name ) as CodeExpression : new CodeThisReferenceExpression(), method.MethodName ) ); @@ -1134,116 +1153,111 @@ protected override void BuildSerializerCodeCore( ISerializerCodeGenerationContex asCodeDomContext.Reset( this.TargetType, this.BaseClass ); - SerializationTarget targetInfo; if ( !this.TargetType.GetIsEnum() ) { + SerializationTarget targetInfo; this.BuildSerializer( asCodeDomContext, concreteType, itemSchema, out targetInfo ); + this.Finish( + asCodeDomContext, + targetInfo, + false, + targetInfo == null + ? default( SerializerCapabilities? ) + : this.CollectionTraits.CollectionType == CollectionKind.NotCollection + ? targetInfo.GetCapabilitiesForObject() + : targetInfo.GetCapabilitiesForCollection( this.CollectionTraits ) + ); } else { - targetInfo = null; this.BuildEnumSerializer( asCodeDomContext ); + this.Finish( asCodeDomContext, null, true, ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) ); } - - this.Finish( asCodeDomContext, targetInfo, this.TargetType.GetIsEnum() ); } - protected override Func CreateSerializerConstructor( CodeDomContext codeGenerationContext, SerializationTarget targetInfo, PolymorphismSchema schema ) + protected override Func CreateSerializerConstructor( CodeDomContext codeGenerationContext, SerializationTarget targetInfo, PolymorphismSchema schema, SerializerCapabilities? capabilities ) { - this.Finish( codeGenerationContext, targetInfo, false ); +#if DEBUG + this.Finish( codeGenerationContext, targetInfo, false, capabilities ); var targetType = PrepareSerializerConstructorCreation( codeGenerationContext ); - - var contextParameter = Expression.Parameter( typeof( SerializationContext ), "context" ); - return - Expression.Lambda>( - Expression.New( targetType.GetConstructors().Single(), contextParameter ), - contextParameter - ).Compile(); + return targetType.GetConstructors().Single().CreateConstructorDelegate>(); +#else + throw new NotSupportedException(); +#endif // DEBUG } protected override Func CreateEnumSerializerConstructor( CodeDomContext codeGenerationContext ) { - this.Finish( codeGenerationContext, null, true ); +#if DEBUG + this.Finish( codeGenerationContext, null, true, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ); var targetType = PrepareSerializerConstructorCreation( codeGenerationContext ); - - var contextParameter = Expression.Parameter( typeof( SerializationContext ), "context" ); - return - Expression.Lambda>( - Expression.New( targetType.GetConstructors().Single( c => c.GetParameters().Length == 1 ), contextParameter ), - contextParameter - ).Compile(); + return targetType.GetConstructors().Single( c => c.GetParameters().Length == 1 ).CreateConstructorDelegate>(); +#else + throw new NotSupportedException(); +#endif // DEBUG } -#if !NETFX_35 +#if DEBUG +#if !NET35 [SecuritySafeCritical] -#endif // !NETFX_35 +#endif // !NET35 private static Type PrepareSerializerConstructorCreation( CodeDomContext codeGenerationContext ) { - if ( !SerializerDebugging.OnTheFlyCodeDomEnabled ) + if ( !SerializerDebugging.OnTheFlyCodeGenerationEnabled ) { throw new NotSupportedException(); } - var cu = codeGenerationContext.CreateCodeCompileUnit(); - CompilerResults cr; - using ( var codeProvider = CodeDomProvider.CreateProvider( "cs" ) ) + codeGenerationContext.Generate(); + Assembly assembly; + IList errors; + IList warnings; + + SerializerDebugging.CompileAssembly( +#if PERFORMANCE_TEST + false, +#else + true, +#endif // PERFORMANCE_TEST + out assembly, + out errors, + out warnings + ); + + SerializerDebugging.ClearCodeBuffer(); + + if ( errors.Any() ) { - if ( SerializerDebugging.DumpEnabled ) + if ( SerializerDebugging.TraceEnabled && !SerializerDebugging.DumpEnabled ) { - SerializerDebugging.TraceEvent( "Compile {0}", codeGenerationContext.DeclaringType.Name ); - codeProvider.GenerateCodeFromCompileUnit( cu, SerializerDebugging.ILTraceWriter, new CodeGeneratorOptions() ); + SerializerDebugging.ILTraceWriter.WriteLine( SerializerDebugging.CodeWriter.ToString() ); SerializerDebugging.FlushTraceData(); } - cr = - codeProvider.CompileAssemblyFromDom( - new CompilerParameters( SerializerDebugging.CodeDomSerializerDependentAssemblies.ToArray() ) -#if PERFORMANCE_TEST - { - IncludeDebugInformation = false, - CompilerOptions = "/optimize+" - } -#endif - , - cu - ); - var errors = cr.Errors.OfType().Where( e => !e.IsWarning ).ToArray(); - if ( errors.Length > 0 ) - { - if ( SerializerDebugging.TraceEnabled && !SerializerDebugging.DumpEnabled ) - { - codeProvider.GenerateCodeFromCompileUnit( cu, SerializerDebugging.ILTraceWriter, new CodeGeneratorOptions() ); - SerializerDebugging.FlushTraceData(); - } - - throw new SerializationException( - String.Format( - CultureInfo.CurrentCulture, - "Failed to compile assembly. Details:{0}{1}", - Environment.NewLine, - BuildCompilationError( cr ) - ) - ); - } + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Failed to compile assembly. Details:{0}{1}", + Environment.NewLine, + String.Join( Environment.NewLine, errors.ToArray() ) + ) + ); } #if DEBUG // Check warning except ambigious type reference. - var warnings = cr.Errors.OfType().Where( e => e.ErrorNumber != "CS0436" ).ToArray(); - Contract.Assert( !warnings.Any(), BuildCompilationError( cr ) ); + Contract.Assert( !warnings.Any(), String.Join( Environment.NewLine, warnings.ToArray() ) ); #endif if ( SerializerDebugging.TraceEnabled ) { - SerializerDebugging.TraceEvent( "Build assembly '{0}' from dom.", cr.PathToAssembly ); + SerializerDebugging.TraceEmitEvent( "Build assembly '{0}' from dom.", assembly.ManifestModule.FullyQualifiedName ); } - SerializerDebugging.AddCompiledCodeDomAssembly( cr.PathToAssembly ); - var targetType = - cr.CompiledAssembly.GetTypes() + assembly.GetTypes() .SingleOrDefault( t => - t.Namespace == cu.Namespaces[ 0 ].Name + t.Namespace == codeGenerationContext.Namespace && t.Name == codeGenerationContext.DeclaringType.Name ); @@ -1251,42 +1265,15 @@ private static Type PrepareSerializerConstructorCreation( CodeDomContext codeGen targetType != null, String.Join( Environment.NewLine, - cr.CompiledAssembly.GetTypes() - .Where( - // ReSharper disable once ImplicitlyCapturedClosure - t => t.Namespace == cu.Namespaces[ 0 ].Name - ).Select( t => t.FullName ).ToArray() + assembly.GetTypes().Select( t => t.GetFullName() ).ToArray() ) ); return targetType; - - } - - private static string BuildCompilationError( CompilerResults cr ) - { - return - String.Join( - Environment.NewLine, - cr.Errors.OfType() - .Select( - ( error, i ) => - String.Format( - CultureInfo.InvariantCulture, - "[{0}]{1}:{2}:(File:{3}, Line:{4}, Column:{5}):{6}", - i, - error.IsWarning ? "Warning" : "Error ", - error.ErrorNumber, - error.FileName, - error.Line, - error.Column, - error.ErrorText - ) - ).ToArray() - ); } +#endif // DEBUG [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "CodeDOM" )] - private void Finish( CodeDomContext context, SerializationTarget targetInfo, bool isEnum ) + private void Finish( CodeDomContext context, SerializationTarget targetInfo, bool isEnum, SerializerCapabilities? capabilities ) { // ctor if ( isEnum ) @@ -1354,6 +1341,18 @@ private void Finish( CodeDomContext context, SerializationTarget targetInfo, boo ); } + if ( capabilities.HasValue ) + { + var capabilitiesExpression = BuildCapabilitiesExpression( null, capabilities.Value, SerializerCapabilities.PackTo ); + capabilitiesExpression = BuildCapabilitiesExpression( capabilitiesExpression, capabilities.Value, SerializerCapabilities.UnpackFrom ); + capabilitiesExpression = BuildCapabilitiesExpression( capabilitiesExpression, capabilities.Value, SerializerCapabilities.UnpackTo ); + + ctor.BaseConstructorArgs.Add( + capabilitiesExpression + ?? new CodeFieldReferenceExpression( new CodeTypeReferenceExpression( typeof( SerializerCapabilities ) ), "None" ) + ); + } + int schemaNumber = -1; foreach ( var dependentSerializer in context.GetDependentSerializers() ) { @@ -1419,14 +1418,17 @@ private void Finish( CodeDomContext context, SerializationTarget targetInfo, boo { schemaNumber++; var variableName = "schema" + schemaNumber; - var schema = this.DeclareLocal( context, typeof( PolymorphismSchema ), variableName ); + var schema = this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, variableName ); ctor.Statements.AddRange( schema.AsStatements().ToArray() ); ctor.Statements.AddRange( this.EmitConstructPolymorphismSchema( context, schema, dependentSerializer.Key.PolymorphismSchema - ).SelectMany( st => st.AsStatements() ).ToArray() + ) + // inner ToArray() is required for .net core app 2.0 LINQ + .SelectMany( st => st.AsStatements().ToArray() ) + .ToArray() ); schemaExpression = new CodeVariableReferenceExpression( variableName ); @@ -1495,11 +1497,10 @@ private void Finish( CodeDomContext context, SerializationTarget targetInfo, boo ); } // foreach ( in context.GetCachedMethodBases() ) - if ( targetInfo != null ) + if ( targetInfo != null && this.CollectionTraits.CollectionType == CollectionKind.NotCollection ) { // For object only. - if ( - !typeof( IPackable ).IsAssignableFrom( this.TargetType ) + if ( !typeof( IPackable ).IsAssignableFrom( this.TargetType ) #if FEATURE_TAP || !typeof( IAsyncPackable ).IsAssignableFrom( this.TargetType ) #endif // FEATURE_TAP @@ -1536,14 +1537,32 @@ private void Finish( CodeDomContext context, SerializationTarget targetInfo, boo ); } #endif // FEATURE_TAP + + if ( ( !typeof( IPackable ).IsAssignableFrom( this.TargetType ) +#if FEATURE_TAP + || ( !typeof( IAsyncPackable ).IsAssignableFrom( this.TargetType ) && this.WithAsync( context ) ) +#endif // FEATURE_TAP + ) +#if DEBUG + && !SerializerDebugging.UseLegacyNullMapEntryHandling +#endif // DEBUG + ) + { + ctor.Statements.AddRange( + this.EmitPackNullCheckerTableInitialization( context, targetInfo ).AsStatements().ToArray() + ); + } } } if ( - !typeof( IUnpackable ).IsAssignableFrom( this.TargetType ) + targetInfo.CanDeserialize + && ( + !typeof( IUnpackable ).IsAssignableFrom( this.TargetType ) #if FEATURE_TAP - || !typeof( IAsyncUnpackable ).IsAssignableFrom( this.TargetType ) + || !typeof( IAsyncUnpackable ).IsAssignableFrom( this.TargetType ) #endif // FEATURE_TAP + ) ) { if ( !typeof( IUnpackable ).IsAssignableFrom( this.TargetType ) ) @@ -1580,9 +1599,16 @@ private void Finish( CodeDomContext context, SerializationTarget targetInfo, boo #endif // FEATURE_TAP } - ctor.Statements.AddRange( - this.EmitMemberListInitialization( context, targetInfo ).AsStatements().ToArray() - ); + if ( !typeof( IUnpackable ).IsAssignableFrom( this.TargetType ) +#if FEATURE_TAP + || ( !typeof( IAsyncUnpackable ).IsAssignableFrom( this.TargetType ) && this.WithAsync( context ) ) +#endif // FEATURE_TAP + ) + { + ctor.Statements.AddRange( + this.EmitMemberListInitialization( context, targetInfo ).AsStatements().ToArray() + ); + } } } // if( targetInfo != null ) @@ -1647,11 +1673,49 @@ private void Finish( CodeDomContext context, SerializationTarget targetInfo, boo } } + private static CodeExpression BuildCapabilitiesExpression( CodeExpression expression, SerializerCapabilities capabilities, SerializerCapabilities value ) + { + if ( ( capabilities & value ) != 0 ) + { + var capabilityExpression = + new CodeFieldReferenceExpression( new CodeTypeReferenceExpression( typeof( SerializerCapabilities ) ), value.ToString() ); + if ( expression == null ) + { + return capabilityExpression; + } + else + { + return + new CodeBinaryOperatorExpression( + expression, + CodeBinaryOperatorType.BitwiseOr, + capabilityExpression + ); + } + } + else + { + return expression; + } + } + protected override CodeDomContext CreateCodeGenerationContextForSerializerCreation( SerializationContext context ) { - var result = new CodeDomContext( context, new SerializerCodeGenerationConfiguration() ); +#if DEBUG + var result = + new CodeDomContext( + context, + new SerializerCodeGenerationConfiguration + { + OutputDirectory = SerializerDebugging.DumpDirectory, + CodeGenerationSink = CodeGenerationSink.ForSpecifiedTextWriter( SerializerDebugging.CodeWriter ) + } + ); result.Reset( this.TargetType, this.BaseClass ); return result; +#else + throw new NotSupportedException(); +#endif // DEBUG } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CodeDomSerializers/StatementCodeDomConstruct.cs b/src/MsgPack/Serialization/CodeDomSerializers/StatementCodeDomConstruct.cs index 52d48f916..1bcb73638 100644 --- a/src/MsgPack/Serialization/CodeDomSerializers/StatementCodeDomConstruct.cs +++ b/src/MsgPack/Serialization/CodeDomSerializers/StatementCodeDomConstruct.cs @@ -23,6 +23,8 @@ using System.Collections.Generic; using System.Linq; +using MsgPack.Serialization.AbstractSerializers; + namespace MsgPack.Serialization.CodeDomSerializers { internal class StatementCodeDomConstruct : CodeDomConstruct @@ -45,7 +47,7 @@ public override void AddStatements( CodeStatementCollection collection ) } public StatementCodeDomConstruct( IEnumerable statements ) - : base( typeof( void ) ) + : base( TypeDefinition.VoidType ) { this._statements = statements.ToArray(); } diff --git a/src/MsgPack/Serialization/CodeGenerationSink.cs b/src/MsgPack/Serialization/CodeGenerationSink.cs new file mode 100644 index 000000000..2ce9815b2 --- /dev/null +++ b/src/MsgPack/Serialization/CodeGenerationSink.cs @@ -0,0 +1,85 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; + +namespace MsgPack.Serialization +{ + /// + /// Represents code generation sink which is responsible to emitting target. + /// + public abstract class CodeGenerationSink + { + /// + /// Initializes a new instance of the class. + /// + protected CodeGenerationSink() { } + + /// + /// Assigns the appropriate to the specified + /// based on the argument and the method of this object. + /// + /// + /// The object which holds informations to determine output and output themselves. + /// + /// is null. + public void AssignTextWriter( SerializerCodeInformation codeInformation ) + { + if ( codeInformation == null ) + { + throw new ArgumentNullException( "codeInformation" ); + } + + this.AssignTextWriterCore( codeInformation ); + } + + /// + /// Assigns the appropriate to the specified + /// based on the argument and the method of this object. + /// + /// + /// The object which holds informations to determine output and output themselves. + /// The override implementation must set its property via Set* method. + /// This value will not be null. + /// + protected abstract void AssignTextWriterCore( SerializerCodeInformation codeInformation ); + + /// + /// Gets a pre-defined object which assigns individual for files toward each codes. + /// + /// The pre-defined . This value will not be null. + public static CodeGenerationSink ForIndividualFile() + { + return IndividualFileCodeGenerationSink.Instance; + } + + /// + /// Gets a pre-defined object which assigns specified toward all codes. + /// + /// The to be used for all codes. + /// The pre-defined . This value will not be null. + /// The is null. + public static CodeGenerationSink ForSpecifiedTextWriter( TextWriter writer ) + { + return new SingleTextWriterCodeGenerationSink( writer ); + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/CollectionDetailedKind.cs b/src/MsgPack/Serialization/CollectionDetailedKind.cs index 7442c1f73..d35962f82 100644 --- a/src/MsgPack/Serialization/CollectionDetailedKind.cs +++ b/src/MsgPack/Serialization/CollectionDetailedKind.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014 FUJIWARA, Yusuke +// Copyright (C) 2014-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,7 +26,12 @@ namespace MsgPack.Serialization { - internal enum CollectionDetailedKind +#if UNITY && DEBUG + public +#else + internal +#endif + enum CollectionDetailedKind { NotCollection = 0, Array, @@ -34,18 +39,18 @@ internal enum CollectionDetailedKind NonGenericList, GenericDictionary, NonGenericDictionary, -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY GenericSet, -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY GenericCollection, NonGenericCollection, GenericEnumerable, NonGenericEnumerable, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) GenericReadOnlyList, GenericReadOnlyCollection, GenericReadOnlyDictionary, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) Unserializable } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CollectionKind.cs b/src/MsgPack/Serialization/CollectionKind.cs index f607b0ecc..4072c364b 100644 --- a/src/MsgPack/Serialization/CollectionKind.cs +++ b/src/MsgPack/Serialization/CollectionKind.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,11 +18,20 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; namespace MsgPack.Serialization { - internal enum CollectionKind +#if UNITY && DEBUG + public +#else + internal +#endif + enum CollectionKind { NotCollection = 0, Array, diff --git a/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializerBase`2.cs b/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializerBase`2.cs index 89ab7f20d..6f4737d42 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializerBase`2.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializerBase`2.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -55,6 +55,21 @@ public abstract class CollectionMessagePackSerializerBase : protected CollectionMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected CollectionMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Serializes specified object with specified . /// @@ -68,7 +83,7 @@ protected CollectionMessagePackSerializerBase( SerializationContext ownerContext protected internal override void PackToCore( Packer packer, TCollection objectTree ) { packer.PackArrayHeader( this.GetCount( objectTree ) ); -#if ( !UNITY ) || AOT_CHECK +#if ( !UNITY && !AOT ) || AOT_CHECK var itemSerializer = this.ItemSerializer; foreach ( var item in objectTree ) { @@ -106,7 +121,7 @@ protected internal override void PackToCore( Packer packer, TCollection objectTr protected internal override async Task PackToAsyncCore( Packer packer, TCollection objectTree, CancellationToken cancellationToken ) { await packer.PackArrayHeaderAsync( this.GetCount( objectTree ), cancellationToken ).ConfigureAwait( false ); -#if ( !UNITY ) || AOT_CHECK +#if ( !UNITY && !AOT ) || AOT_CHECK var itemSerializer = this.ItemSerializer; foreach ( var item in objectTree ) { @@ -152,7 +167,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, TCollecti /// /// This method invokes , and then fill deserialized items to resultong collection. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override TCollection UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -215,4 +230,4 @@ internal virtual Task InternalUnpackFromAsyncCore( Unpacker unpacke #endif // FEATURE_TAP } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializer`2.cs b/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializer`2.cs index 79965bfca..6f097486d 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/CollectionMessagePackSerializer`2.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -54,6 +54,21 @@ public abstract class CollectionMessagePackSerializer : Coll protected CollectionMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected CollectionMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Returns count of the collection. /// @@ -61,7 +76,7 @@ protected CollectionMessagePackSerializer( SerializationContext ownerContext, Po /// The count of the . protected override int GetCount( TCollection collection ) { -#if ( !UNITY ) || AOT_CHECK +#if ( !UNITY && !AOT ) || AOT_CHECK return collection.Count; #else // .constraind call for TCollection.get_Count/TCollection.GetEnumerator() causes AOT error. @@ -79,7 +94,7 @@ protected override int GetCount( TCollection collection ) [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected override void AddItem( TCollection collection, TItem item ) { -#if ( !UNITY ) || AOT_CHECK +#if ( !UNITY && !AOT ) || AOT_CHECK collection.Add( item ); #else // .constraind call for TCollection.Add causes AOT error. @@ -100,9 +115,10 @@ protected UnityCollectionMessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits traits, - PolymorphismSchema schema + PolymorphismSchema schema, + SerializerCapabilities capabilities ) - : base( ownerContext, targetType, traits.ElementType, schema ) + : base( ownerContext, targetType, traits.ElementType, schema, capabilities ) { this._getCount = traits.CountPropertyGetter; this._add = traits.AddMethod; @@ -144,4 +160,4 @@ protected override void AddItem( object collection, object item ) } } #endif // UNITY -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializerBase`3.cs b/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializerBase`3.cs index 9cd8cdf23..c45a822c7 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializerBase`3.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializerBase`3.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -69,6 +69,27 @@ protected DictionaryMessagePackSerializerBase( SerializationContext ownerContext this._valueSerializer = ownerContext.GetSerializer( safeSchema.ItemSchema ); } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] + protected DictionaryMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, capabilities ) + { + var safeSchema = schema ?? PolymorphismSchema.Default; + this._keySerializer = ownerContext.GetSerializer( safeSchema.KeySchema ); + this._valueSerializer = ownerContext.GetSerializer( safeSchema.ItemSchema ); + } + /// /// Serializes specified object with specified . /// @@ -81,7 +102,7 @@ protected DictionaryMessagePackSerializerBase( SerializationContext ownerContext [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, TDictionary objectTree ) { -#if ( !UNITY ) || AOT_CHECK +#if ( !UNITY && !AOT ) || AOT_CHECK packer.PackMapHeader( this.GetCount( objectTree ) ); foreach ( var item in objectTree ) { @@ -120,7 +141,7 @@ protected internal override void PackToCore( Packer packer, TDictionary objectTr /// protected internal override async Task PackToAsyncCore( Packer packer, TDictionary objectTree, CancellationToken cancellationToken ) { -#if ( !UNITY ) || AOT_CHECK +#if ( !UNITY && !AOT ) || AOT_CHECK await packer.PackMapHeaderAsync( this.GetCount( objectTree ), cancellationToken ).ConfigureAwait( false ); foreach ( var item in objectTree ) { @@ -166,7 +187,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, TDictiona /// is abstract type. /// /// - /// This method invokes , and then fill deserialized items to resultong collection. + /// This method invokes , and then fill deserialized items to resultong collection. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override TDictionary UnpackFromCore( Unpacker unpacker ) @@ -423,4 +444,4 @@ protected virtual void AddItem( TDictionary dictionary, TKey key, TValue value ) throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TDictionary ), null ); } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializer`3.cs b/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializer`3.cs index c8161f2ea..65ab92a24 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializer`3.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/DictionaryMessagePackSerializer`3.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -61,6 +61,21 @@ public abstract class DictionaryMessagePackSerializer protected DictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected DictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Returns count of the dictionary. /// @@ -68,13 +83,13 @@ protected DictionaryMessagePackSerializer( SerializationContext ownerContext, Po /// The count of the . protected override int GetCount( TDictionary dictionary ) { -#if ( !UNITY ) || AOT_CHECK +#if !AOT return dictionary.Count; -#else +#else // !AOT // .constraind call for TDictionary.get_Count/TDictionary.GetEnumerator() causes AOT error. // So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type). return ( dictionary as IDictionary ).Count; -#endif // ( !UNITY ) || AOT_CHECK +#endif // !AOT } /// @@ -89,13 +104,13 @@ protected override int GetCount( TDictionary dictionary ) /// protected override void AddItem( TDictionary dictionary, TKey key, TValue value ) { -#if ( !UNITY && !XAMARIN ) || AOT_CHECK +#if !AOT dictionary.Add( key, value ); -#else +#else // !AOT // .constraind call for TDictionary.Add causes AOT error. // So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type). ( dictionary as IDictionary ).Add( key, value ); -#endif // ( !UNITY && !XAMARIN ) || AOT_CHECK +#endif // !AOT } } @@ -117,9 +132,10 @@ protected UnityDictionaryMessagePackSerializer( Type keyType, Type valueType, CollectionTraits traits, - PolymorphismSchema schema + PolymorphismSchema schema, + SerializerCapabilities capabilities ) - : base( ownerContext, targetType ) + : base( ownerContext, targetType, capabilities ) { var safeSchema = schema ?? PolymorphismSchema.Default; this._keySerializer = ownerContext.GetSerializer( keyType, safeSchema.KeySchema ); @@ -222,4 +238,4 @@ private void UnpackToCore( Unpacker unpacker, object collection, int itemsCount } } #endif // UNITY -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializerBase`2.cs b/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializerBase`2.cs index fac3518e1..8af125091 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializerBase`2.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializerBase`2.cs @@ -53,7 +53,7 @@ public abstract class EnumerableMessagePackSerializerBase : /// /// A which owns this serializer. /// - /// The schema for collection itself or its items for the member this instance will be used to. + /// The schema for collection itself or its items for the member this instMPCONTRACTance will be used to. /// null will be considered as . /// /// @@ -66,6 +66,25 @@ protected EnumerableMessagePackSerializerBase( SerializationContext ownerContext this._itemSerializer = ownerContext.GetSerializer( ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] + protected EnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, capabilities ) + { + this._itemSerializer = ownerContext.GetSerializer( ( schema ?? PolymorphismSchema.Default ).ItemSchema ); + } + /// /// Creates a new collection instance with specified initial capacity. /// @@ -255,8 +274,8 @@ internal abstract class UnityEnumerableMessagePackSerializerBase : NonGenericMes internal MessagePackSerializer ItemSerializer { get { return this._itemSerializer; } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] - protected UnityEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, Type itemType, PolymorphismSchema schema ) - : base( ownerContext, targetType ) + protected UnityEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, Type itemType, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, targetType, capabilities ) { this._itemSerializer = ownerContext.GetSerializer( itemType, ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } @@ -312,4 +331,4 @@ protected virtual void AddItem( object collection, object item ) } } #endif // UNITY -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializer`2.cs b/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializer`2.cs index 70fc448ea..b9f898790 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/EnumerableMessagePackSerializer`2.cs @@ -62,6 +62,21 @@ public abstract class EnumerableMessagePackSerializer : Enum protected EnumerableMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected EnumerableMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Serializes specified object with specified . /// @@ -135,9 +150,10 @@ protected UnityEnumerableMessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits traits, - PolymorphismSchema schema + PolymorphismSchema schema, + SerializerCapabilities capabilities ) - : base( ownerContext, targetType, traits.ElementType, schema ) + : base( ownerContext, targetType, traits.ElementType, schema, capabilities ) { this._getCount = traits.CountPropertyGetter; } diff --git a/src/MsgPack/Serialization/CollectionSerializers/NonGenericCollectionMessagePackSerializer`1.cs b/src/MsgPack/Serialization/CollectionSerializers/NonGenericCollectionMessagePackSerializer`1.cs index 57ba0d232..2696cca91 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/NonGenericCollectionMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/NonGenericCollectionMessagePackSerializer`1.cs @@ -54,6 +54,21 @@ public abstract class NonGenericCollectionMessagePackSerializer : N protected NonGenericCollectionMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected NonGenericCollectionMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Serializes specified object with specified . /// @@ -110,8 +125,8 @@ protected internal override async Task PackToAsyncCore( Packer packer, TCollecti #warning TODO: Remove if possible for maintenancibility. internal abstract class UnityNonGenericCollectionMessagePackSerializer : UnityNonGenericEnumerableMessagePackSerializerBase { - protected UnityNonGenericCollectionMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) - : base( ownerContext, targetType, schema ) { } + protected UnityNonGenericCollectionMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, targetType, schema, capabilities ) { } protected internal override void PackToCore( Packer packer, object objectTree ) { diff --git a/src/MsgPack/Serialization/CollectionSerializers/NonGenericDictionaryMessagePackSerializer`1.cs b/src/MsgPack/Serialization/CollectionSerializers/NonGenericDictionaryMessagePackSerializer`1.cs index d0dec7a10..5d889fe39 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/NonGenericDictionaryMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/NonGenericDictionaryMessagePackSerializer`1.cs @@ -66,6 +66,27 @@ protected NonGenericDictionaryMessagePackSerializer( SerializationContext ownerC this._valueSerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.ItemSchema ); } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] + protected NonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, capabilities ) + { + var safeSchema = schema ?? PolymorphismSchema.Default; + this._keySerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.KeySchema ); + this._valueSerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.ItemSchema ); + } + /// /// Serializes specified object with specified . /// @@ -381,8 +402,8 @@ internal abstract class UnityNonGenericDictionaryMessagePackSerializer : NonGene private readonly MessagePackSerializer _keySerializer; private readonly MessagePackSerializer _valueSerializer; - protected UnityNonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) - : base( ownerContext, targetType ) + protected UnityNonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, targetType, capabilities ) { var safeSchema = schema ?? PolymorphismSchema.Default; this._keySerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.KeySchema ); diff --git a/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializerBase`1.cs b/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializerBase`1.cs index 8c8453300..3c74b74d3 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializerBase`1.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializerBase`1.cs @@ -65,6 +65,25 @@ protected NonGenericEnumerableMessagePackSerializerBase( SerializationContext ow this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] + protected NonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, capabilities ) + { + this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema ); + } + /// /// Creates a new collection instance with specified initial capacity. /// @@ -254,8 +273,8 @@ internal abstract class UnityNonGenericEnumerableMessagePackSerializerBase : Non internal MessagePackSerializer ItemSerializer { get { return this._itemSerializer; } } - protected UnityNonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) - : base( ownerContext, targetType ) + protected UnityNonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, targetType, capabilities ) { this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } diff --git a/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializer`1.cs b/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializer`1.cs index 07b977c56..e1c930417 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/NonGenericEnumerableMessagePackSerializer`1.cs @@ -55,6 +55,21 @@ public abstract class NonGenericEnumerableMessagePackSerializer : N protected NonGenericEnumerableMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected NonGenericEnumerableMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Serializes specified object with specified . /// @@ -121,8 +136,8 @@ protected internal override async Task PackToAsyncCore( Packer packer, TCollecti #warning TODO: Remove if possible for maintenancibility. internal abstract class UnityNonGenericEnumerableMessagePackSerializer : UnityNonGenericEnumerableMessagePackSerializerBase { - protected UnityNonGenericEnumerableMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) - : base( ownerContext, targetType, schema ) { } + protected UnityNonGenericEnumerableMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, targetType, schema, capabilities ) { } protected internal override void PackToCore( Packer packer, object objectTree ) { diff --git a/src/MsgPack/Serialization/CollectionSerializers/NonGenericListMessagePackSerializer`1.cs b/src/MsgPack/Serialization/CollectionSerializers/NonGenericListMessagePackSerializer`1.cs index b3ece847c..ee004ae7b 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/NonGenericListMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/NonGenericListMessagePackSerializer`1.cs @@ -54,6 +54,21 @@ public abstract class NonGenericListMessagePackSerializer : NonGenericCol protected NonGenericListMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext, schema ) { } + /// + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected NonGenericListMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Deserializes object with specified . /// @@ -154,8 +169,8 @@ protected override void AddItem( TList collection, object item ) #warning TODO: Remove if possible for maintenancibility. internal abstract class UnityNonGenericListMessagePackSerializer : UnityNonGenericCollectionMessagePackSerializer { - protected UnityNonGenericListMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) - : base( ownerContext, targetType, schema ) { } + protected UnityNonGenericListMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, targetType, schema, capabilities ) { } protected internal override object UnpackFromCore( Unpacker unpacker ) { diff --git a/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyCollectionMessagePackSerializer`2.cs b/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyCollectionMessagePackSerializer`2.cs index ab822f033..a0648c091 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyCollectionMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyCollectionMessagePackSerializer`2.cs @@ -50,6 +50,21 @@ public abstract class ReadOnlyCollectionMessagePackSerializer + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected ReadOnlyCollectionMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Returns count of the collection. /// diff --git a/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyDictionaryMessagePackSerializer`3.cs b/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyDictionaryMessagePackSerializer`3.cs index 0fc7c56ab..624dd5d2a 100644 --- a/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyDictionaryMessagePackSerializer`3.cs +++ b/src/MsgPack/Serialization/CollectionSerializers/ReadOnlyDictionaryMessagePackSerializer`3.cs @@ -51,6 +51,21 @@ public abstract class ReadOnlyDictionaryMessagePackSerializer + /// Initializes a new instance of the class. + /// + /// A which owns this serializer. + /// + /// The schema for collection itself or its items for the member this instance will be used to. + /// null will be considered as . + /// + /// A serializer calability flags represents capabilities of this instance. + /// + /// is null. + /// + protected ReadOnlyDictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities ) + : base( ownerContext, schema, capabilities ) { } + /// /// Returns count of the dictionary. /// diff --git a/src/MsgPack/Serialization/CollectionTraitOptions.cs b/src/MsgPack/Serialization/CollectionTraitOptions.cs index 310f4bb29..8c11b59a2 100644 --- a/src/MsgPack/Serialization/CollectionTraitOptions.cs +++ b/src/MsgPack/Serialization/CollectionTraitOptions.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2016 FUJIWARA, Yusuke +// Copyright (C) 2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; @@ -29,6 +32,7 @@ internal enum CollectionTraitOptions WithAddMethod = 0x1, WithCountPropertyGetter = 0x2, WithGetEnumeratorMethod = 0x4, - Full = unchecked( ( int ) 0xFFFFFFFF ) + AllowNonCollectionEnumerableTypes = 0x800, + Full = WithAddMethod | WithCountPropertyGetter | WithGetEnumeratorMethod } } \ No newline at end of file diff --git a/src/MsgPack/Serialization/CollectionTraits.cs b/src/MsgPack/Serialization/CollectionTraits.cs index d8e9e8237..8496d1107 100644 --- a/src/MsgPack/Serialization/CollectionTraits.cs +++ b/src/MsgPack/Serialization/CollectionTraits.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,7 +27,12 @@ namespace MsgPack.Serialization { - internal struct CollectionTraits +#if UNITY && DEBUG + public +#else + internal +#endif + struct CollectionTraits { public static readonly CollectionTraits NotCollection = new CollectionTraits( CollectionDetailedKind.NotCollection, null, null, null, null ); public static readonly CollectionTraits Unserializable = new CollectionTraits( CollectionDetailedKind.Unserializable, null, null, null, null ); @@ -46,13 +51,13 @@ public CollectionKind CollectionType case CollectionDetailedKind.GenericCollection: case CollectionDetailedKind.GenericEnumerable: case CollectionDetailedKind.GenericList: -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyCollection: case CollectionDetailedKind.GenericReadOnlyList: -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY case CollectionDetailedKind.GenericSet: -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY case CollectionDetailedKind.NonGenericCollection: case CollectionDetailedKind.NonGenericEnumerable: case CollectionDetailedKind.NonGenericList: @@ -60,9 +65,9 @@ public CollectionKind CollectionType return CollectionKind.Array; } case CollectionDetailedKind.GenericDictionary: -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyDictionary: -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.NonGenericDictionary: { return CollectionKind.Map; diff --git a/src/MsgPack/Serialization/DataMemberContract.cs b/src/MsgPack/Serialization/DataMemberContract.cs index 38b54d66d..8ff6f5abc 100644 --- a/src/MsgPack/Serialization/DataMemberContract.cs +++ b/src/MsgPack/Serialization/DataMemberContract.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT || NETSTANDARD1_1 using System.Globalization; using System.Reflection; using System.Runtime.Serialization; @@ -41,7 +41,12 @@ namespace MsgPack.Serialization internal struct DataMemberContract #else #warning TODO: To struct if possible - internal sealed class DataMemberContract +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class DataMemberContract #endif // !UNITY { #if UNITY diff --git a/src/MsgPack/Serialization/DateTimeConversionMethod.cs b/src/MsgPack/Serialization/DateTimeConversionMethod.cs index 41c93c845..47e82fac8 100644 --- a/src/MsgPack/Serialization/DateTimeConversionMethod.cs +++ b/src/MsgPack/Serialization/DateTimeConversionMethod.cs @@ -31,7 +31,7 @@ public enum DateTimeConversionMethod /// Uses context, that is, Gregorian 0000-01-01 based, 100 nano seconds resolution. This value also preserves . /// /// - /// As of 0.6, this value has been become default. This option prevents accidental data loss. + /// As of 0.6 to 0.9, this value became default. This option prevents accidental data loss. /// Native = 0, @@ -39,8 +39,26 @@ public enum DateTimeConversionMethod /// Uses Unix epoc context, that is, Gregirian 1970-01-01 based, milliseconds resolution. /// /// - /// Many binding such as Java uses this resolution, so this option gives maximom interoperability. + /// Many binding such as Java uses this resolution, so this option gives maximum interoperability. /// - UnixEpoc = 1 + UnixEpoc = 1, + + /// + /// Uses MsgPack timestamp format, that is, Gregirian 1970-01-01 based, nanoseconds resolution, with reserved ext type format. + /// + /// + /// + /// As of 1.0, this value became default. + /// + /// + /// This is best choice for interoperability and prevents accidental data loss, but old implementation does not recognize this type. + /// For backward compability purposes, use or instead. + /// + /// + /// Note that and cannot hold nanoseconds value. + /// If you can depend on this assembly, consider for date-time typed members to maximize interoperability for other languages. + /// + /// + Timestamp = 2 } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DateTimeMemberConversionMethod.cs b/src/MsgPack/Serialization/DateTimeMemberConversionMethod.cs index 5a0dce695..27dd26a69 100644 --- a/src/MsgPack/Serialization/DateTimeMemberConversionMethod.cs +++ b/src/MsgPack/Serialization/DateTimeMemberConversionMethod.cs @@ -49,6 +49,24 @@ public enum DateTimeMemberConversionMethod /// /// Many binding such as Java uses this resolution, so this option gives maximom interoperability. /// - UnixEpoc = 2 + UnixEpoc = 2, + + /// + /// Uses MsgPack timestamp format, that is, Gregirian 1970-01-01 based, nanoseconds resolution, with reserved ext type format. + /// + /// + /// + /// As of 1.0, this value became default. + /// + /// + /// This is best choice for interoperability and prevents accidental data loss, but old implementation does not recognize this type. + /// For backward compability purposes, use or instead. + /// + /// + /// Note that and cannot hold nanoseconds value. + /// If you can depend on this assembly, consider for date-time typed members to maximize interoperability for other languages. + /// + /// + Timestamp = 3 } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DateTimeMessagePackSerializerHelpers.cs b/src/MsgPack/Serialization/DateTimeMessagePackSerializerHelpers.cs index c64894444..432a0be62 100644 --- a/src/MsgPack/Serialization/DateTimeMessagePackSerializerHelpers.cs +++ b/src/MsgPack/Serialization/DateTimeMessagePackSerializerHelpers.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -73,6 +73,10 @@ DateTimeMemberConversionMethod dateTimeMemberConversionMethod { return DateTimeConversionMethod.UnixEpoc; } + case DateTimeMemberConversionMethod.Timestamp: + { + return DateTimeConversionMethod.Timestamp; + } default: { return context.DefaultDateTimeConversionMethod; @@ -85,12 +89,13 @@ internal static bool IsDateTime( Type dateTimeType ) return dateTimeType == typeof( DateTime ) || dateTimeType == typeof( DateTime? ) -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY || dateTimeType == typeof( FILETIME ) || dateTimeType == typeof( FILETIME? ) -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY - // DateTimeOffset? is not have to be treat specially. - || dateTimeType == typeof( DateTimeOffset ); +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY + // DateTimeOffset? and Timestamp? do not have to be treat specially. + || dateTimeType == typeof( DateTimeOffset ) + || dateTimeType == typeof( Timestamp ); } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DefaultConcreteTypeRepository.cs b/src/MsgPack/Serialization/DefaultConcreteTypeRepository.cs index 80cf83a8b..56b7253fb 100644 --- a/src/MsgPack/Serialization/DefaultConcreteTypeRepository.cs +++ b/src/MsgPack/Serialization/DefaultConcreteTypeRepository.cs @@ -25,7 +25,7 @@ using System; using System.Collections; using System.Collections.Generic; -#if !NETFX_35 && !SILVERLIGHT && !NETFX_40 +#if !NET35 && !SILVERLIGHT && !NET40 using System.Collections.ObjectModel; #endif using System.Globalization; @@ -44,9 +44,9 @@ internal DefaultConcreteTypeRepository() { this._defaultCollectionTypes = new TypeKeyRepository( new Dictionary( -#if NETFX_35 || ( SILVERLIGHT && !WINDOWS_PHONE ) +#if NET35 || ( SILVERLIGHT && !WINDOWS_PHONE ) 8 -#elif NETFX_40 +#elif NET40 9 #else 12 @@ -61,14 +61,14 @@ internal DefaultConcreteTypeRepository() { typeof( ICollection ).TypeHandle, typeof( List ) }, { typeof( IList ).TypeHandle, typeof( List ) }, { typeof( IDictionary ).TypeHandle, typeof( MessagePackObjectDictionary ) }, -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY { typeof( ISet<> ).TypeHandle, typeof( HashSet<> ) }, -#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) { typeof( IReadOnlyCollection<> ).TypeHandle, typeof( List<> ) }, { typeof( IReadOnlyList<> ).TypeHandle, typeof( List<> ) }, { typeof( IReadOnlyDictionary<,> ).TypeHandle, typeof( Dictionary<,> ) }, -#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#endif // !NETFX_35 && !UNITY +#endif // !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY } ); } diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractCollectionMessagePackSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractCollectionMessagePackSerializer`2.cs index 72b08b3ff..da75508d3 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractCollectionMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractCollectionMessagePackSerializer`2.cs @@ -60,9 +60,9 @@ public AbstractCollectionMessagePackSerializer( PolymorphismSchema schema ) #if !UNITY - : base( ownerContext, schema ) + : base( ownerContext, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #else - : base( ownerContext, abstractType, traits, schema ) + : base( ownerContext, abstractType, traits, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { MessagePackSerializer serializer; diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractDictionaryMessagePackSerializer`3.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractDictionaryMessagePackSerializer`3.cs index 29785664e..876c03f0d 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractDictionaryMessagePackSerializer`3.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractDictionaryMessagePackSerializer`3.cs @@ -61,9 +61,9 @@ public AbstractDictionaryMessagePackSerializer( PolymorphismSchema schema ) #if !UNITY - : base( ownerContext, schema ) + : base( ownerContext, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #else - : base( ownerContext, abstractType, keyType, valueType, traits, schema ) + : base( ownerContext, abstractType, keyType, valueType, traits, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { MessagePackSerializer serializer; diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractEnumerableMessagePackSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractEnumerableMessagePackSerializer`2.cs index 11276579d..90f1241c2 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractEnumerableMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractEnumerableMessagePackSerializer`2.cs @@ -45,6 +45,11 @@ internal sealed class AbstractEnumerableMessagePackSerializer : UnityEnumerableM private readonly ICollectionInstanceFactory _concreteCollectionInstanceFactory; private readonly MessagePackSerializer _concreteSerializer; + internal override SerializerCapabilities InternalGetCapabilities() + { + return this._concreteSerializer.Capabilities; + } + public AbstractEnumerableMessagePackSerializer( SerializationContext ownerContext, #if !UNITY @@ -59,7 +64,7 @@ PolymorphismSchema schema #if !UNITY : base( ownerContext, schema ) #else - : base( ownerContext, abstractType, traits, schema ) + : base( ownerContext, abstractType, traits, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { AbstractCollectionSerializerHelper.GetConcreteSerializer( diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericCollectionMessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericCollectionMessagePackSerializer`1.cs index bdc89dd26..e12dfadab 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericCollectionMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericCollectionMessagePackSerializer`1.cs @@ -47,6 +47,11 @@ internal sealed class AbstractNonGenericCollectionMessagePackSerializer : UnityN private readonly ICollectionInstanceFactory _concreteCollectionInstanceFactory; private readonly MessagePackSerializer _concreteSerializer; + internal override SerializerCapabilities InternalGetCapabilities() + { + return this._concreteSerializer.Capabilities; + } + public AbstractNonGenericCollectionMessagePackSerializer( SerializationContext ownerContext, #if !UNITY @@ -60,7 +65,7 @@ PolymorphismSchema schema #if !UNITY : base( ownerContext, schema ) #else - : base( ownerContext, abstractType, schema ) + : base( ownerContext, abstractType, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { AbstractCollectionSerializerHelper.GetConcreteSerializer( diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericDictionaryMessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericDictionaryMessagePackSerializer`1.cs index 324a1092e..248b8f45c 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericDictionaryMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericDictionaryMessagePackSerializer`1.cs @@ -58,9 +58,9 @@ public AbstractNonGenericDictionaryMessagePackSerializer( PolymorphismSchema schema ) #if !UNITY - : base( ownerContext, schema ) + : base( ownerContext, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #else - : base( ownerContext, abstractType, schema ) + : base( ownerContext, abstractType, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { MessagePackSerializer serializer; diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericEnumerableMessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericEnumerableMessagePackSerializer`1.cs index 623a1751b..a6cabb798 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericEnumerableMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericEnumerableMessagePackSerializer`1.cs @@ -47,6 +47,11 @@ internal sealed class AbstractNonGenericEnumerableMessagePackSerializer : UnityN private readonly ICollectionInstanceFactory _concreteCollectionInstanceFactory; private readonly MessagePackSerializer _concreteSerializer; + internal override SerializerCapabilities InternalGetCapabilities() + { + return this._concreteSerializer.Capabilities; + } + public AbstractNonGenericEnumerableMessagePackSerializer( SerializationContext ownerContext, #if !UNITY @@ -60,7 +65,7 @@ PolymorphismSchema schema #if !UNITY : base( ownerContext, schema ) #else - : base( ownerContext, abstractType, schema ) + : base( ownerContext, abstractType, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { AbstractCollectionSerializerHelper.GetConcreteSerializer( diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericListMessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericListMessagePackSerializer`1.cs index 0b823f221..2c0204c4d 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericListMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractNonGenericListMessagePackSerializer`1.cs @@ -59,9 +59,9 @@ public AbstractNonGenericListMessagePackSerializer( PolymorphismSchema schema ) #if !UNITY - : base( ownerContext, schema ) + : base( ownerContext, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #else - : base( ownerContext, abstractType, schema ) + : base( ownerContext, abstractType, schema, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) #endif // !UNITY { MessagePackSerializer serializer; diff --git a/src/MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyCollectionMessagePackSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyCollectionMessagePackSerializer`2.cs index 4424b350e..1da7616b2 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyCollectionMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/AbstractReadOnlyCollectionMessagePackSerializer`2.cs @@ -38,6 +38,11 @@ internal sealed class AbstractReadOnlyCollectionMessagePackSerializer> InitializeArr internal sealed class SByteArraySerializer : MessagePackSerializer { public SByteArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -189,7 +189,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, SByte[] collecti internal sealed class Int16ArraySerializer : MessagePackSerializer { public Int16ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -302,7 +302,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Int16[] collecti internal sealed class Int32ArraySerializer : MessagePackSerializer { public Int32ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -415,7 +415,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Int32[] collecti internal sealed class Int64ArraySerializer : MessagePackSerializer { public Int64ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -528,7 +528,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Int64[] collecti internal sealed class ByteArraySerializer : MessagePackSerializer { public ByteArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -641,7 +641,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Byte[] collectio internal sealed class UInt16ArraySerializer : MessagePackSerializer { public UInt16ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -754,7 +754,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, UInt16[] collect internal sealed class UInt32ArraySerializer : MessagePackSerializer { public UInt32ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -867,7 +867,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, UInt32[] collect internal sealed class UInt64ArraySerializer : MessagePackSerializer { public UInt64ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -980,7 +980,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, UInt64[] collect internal sealed class SingleArraySerializer : MessagePackSerializer { public SingleArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1093,7 +1093,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Single[] collect internal sealed class DoubleArraySerializer : MessagePackSerializer { public DoubleArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1206,7 +1206,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Double[] collect internal sealed class BooleanArraySerializer : MessagePackSerializer { public BooleanArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1319,7 +1319,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Boolean[] collec internal sealed class NullableSByteArraySerializer : MessagePackSerializer { public NullableSByteArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1432,7 +1432,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, SByte?[] collect internal sealed class NullableInt16ArraySerializer : MessagePackSerializer { public NullableInt16ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1545,7 +1545,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Int16?[] collect internal sealed class NullableInt32ArraySerializer : MessagePackSerializer { public NullableInt32ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1658,7 +1658,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Int32?[] collect internal sealed class NullableInt64ArraySerializer : MessagePackSerializer { public NullableInt64ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1771,7 +1771,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Int64?[] collect internal sealed class NullableByteArraySerializer : MessagePackSerializer { public NullableByteArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1884,7 +1884,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Byte?[] collecti internal sealed class NullableUInt16ArraySerializer : MessagePackSerializer { public NullableUInt16ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -1997,7 +1997,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, UInt16?[] collec internal sealed class NullableUInt32ArraySerializer : MessagePackSerializer { public NullableUInt32ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2110,7 +2110,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, UInt32?[] collec internal sealed class NullableUInt64ArraySerializer : MessagePackSerializer { public NullableUInt64ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2223,7 +2223,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, UInt64?[] collec internal sealed class NullableSingleArraySerializer : MessagePackSerializer { public NullableSingleArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2336,7 +2336,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Single?[] collec internal sealed class NullableDoubleArraySerializer : MessagePackSerializer { public NullableDoubleArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2449,7 +2449,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Double?[] collec internal sealed class NullableBooleanArraySerializer : MessagePackSerializer { public NullableBooleanArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2562,7 +2562,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Boolean?[] colle internal sealed class StringArraySerializer : MessagePackSerializer { public StringArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2675,7 +2675,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, String[] collect internal sealed class BinaryArraySerializer : MessagePackSerializer { public BinaryArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -2788,7 +2788,7 @@ private static async Task UnpackToAsyncCore( Unpacker unpacker, Byte[][] collect internal sealed class MessagePackObjectArraySerializer : MessagePackSerializer { public MessagePackObjectArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] diff --git a/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.Primitives.tt b/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.Primitives.tt index 9abc3a32f..07f7aa9e3 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.Primitives.tt +++ b/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.Primitives.tt @@ -117,7 +117,7 @@ private void GeneratePrimitiveArraySerializer( string itemTypeName, string simpl internal sealed class <#= simpleName #>ArraySerializer : MessagePackSerializer<#= "<" + itemTypeName + "[]>" #> { public <#= simpleName #>ArraySerializer( SerializationContext ownerContext ) - : base ( ownerContext ) { } + : base ( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] diff --git a/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.cs index cce934acb..c80607511 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack.Serialization.DefaultSerializers { diff --git a/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer`1.cs index e132a9d2e..c34c4b85d 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/ArraySerializer`1.cs @@ -50,13 +50,13 @@ internal sealed class UnityArraySerializer : NonGenericMessagePackSerializer #if !UNITY public ArraySerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer( itemsSchema ); } #else public UnityArraySerializer( SerializationContext ownerContext, Type itemType, PolymorphismSchema itemsSchema ) - : base( ownerContext, itemType.MakeArrayType() ) + : base( ownerContext, itemType.MakeArrayType(), SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer( itemType, itemsSchema ); this._itemType = itemType; diff --git a/src/MsgPack/Serialization/DefaultSerializers/DateTimeMessagePackSerializerProvider.cs b/src/MsgPack/Serialization/DefaultSerializers/DateTimeMessagePackSerializerProvider.cs index dbcec5fa9..fa7f11779 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/DateTimeMessagePackSerializerProvider.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/DateTimeMessagePackSerializerProvider.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -34,6 +34,7 @@ internal class DateTimeMessagePackSerializerProvider : MessagePackSerializerProv { private readonly MessagePackSerializer _unixEpoc; private readonly MessagePackSerializer _native; + private readonly MessagePackSerializer _timestamp; public DateTimeMessagePackSerializerProvider( SerializationContext context, bool isNullable ) { @@ -44,17 +45,22 @@ public DateTimeMessagePackSerializerProvider( SerializationContext context, bool new NullableMessagePackSerializer( context, new UnixEpocDateTimeMessagePackSerializer( context ) ); this._native = new NullableMessagePackSerializer( context, new NativeDateTimeMessagePackSerializer( context ) ); + this._timestamp = + new NullableMessagePackSerializer( context, new TimestampDateTimeMessagePackSerializer( context ) ); #else this._unixEpoc = new NullableMessagePackSerializer( context, typeof( DateTime? ), new UnixEpocDateTimeMessagePackSerializer( context ) ); this._native = new NullableMessagePackSerializer( context, typeof( DateTime? ), new NativeDateTimeMessagePackSerializer( context ) ); + this._timestamp = + new NullableMessagePackSerializer( context, typeof( DateTime? ), new TimestampDateTimeMessagePackSerializer( context ) ); #endif // !UNITY } else { this._unixEpoc = new UnixEpocDateTimeMessagePackSerializer( context ); this._native = new NativeDateTimeMessagePackSerializer( context ); + this._timestamp = new TimestampDateTimeMessagePackSerializer( context ); } } @@ -72,6 +78,10 @@ public override object Get( SerializationContext context, object providerParamet { return this._unixEpoc; } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } } } @@ -85,6 +95,10 @@ public override object Get( SerializationContext context, object providerParamet { return this._unixEpoc; } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } default: { throw new NotSupportedException( @@ -99,4 +113,4 @@ public override object Get( SerializationContext context, object providerParamet } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializer.cs index de8b96361..8f9610315 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializer.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Runtime.Serialization; #if FEATURE_TAP using System.Threading; @@ -44,7 +44,7 @@ internal class DateTimeOffsetMessagePackSerializer : MessagePackSerializer().GetValueOrDefault() ) + { + return Timestamp.Decode( unpacker.LastReadData.DeserializeAsMessagePackExtendedTypeObject() ).ToDateTimeOffset(); + } + else if ( unpacker.IsArrayHeader ) { if ( UnpackHelpers.GetItemsCount( unpacker ) != 2 ) { @@ -96,7 +104,7 @@ protected internal override DateTimeOffset UnpackFromCore( Unpacker unpacker ) } else { - return MessagePackConvert.ToDateTimeOffset( unpacker.LastReadData.AsInt64() ); + return MessagePackConvert.ToDateTimeOffset( unpacker.LastReadData.DeserializeAsInt64() ); } } @@ -104,7 +112,11 @@ protected internal override DateTimeOffset UnpackFromCore( Unpacker unpacker ) protected internal override async Task PackToAsyncCore( Packer packer, DateTimeOffset objectTree, CancellationToken cancellationToken ) { - if ( this._conversion == DateTimeConversionMethod.Native ) + if ( this._conversion == DateTimeConversionMethod.Timestamp ) + { + await packer.PackAsync( Timestamp.FromDateTimeOffset( objectTree ).Encode(), cancellationToken ).ConfigureAwait( false ); + } + else if ( this._conversion == DateTimeConversionMethod.Native ) { await packer.PackArrayHeaderAsync( 2, cancellationToken ).ConfigureAwait( false ); await packer.PackAsync( objectTree.DateTime.ToBinary(), cancellationToken ).ConfigureAwait( false ); @@ -141,4 +153,4 @@ protected internal override Task UnpackFromAsyncCore( Unpacker u #endif // FEATURE_TAP } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializerProvider.cs b/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializerProvider.cs index cdfddeaa7..f66b16b66 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializerProvider.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/DateTimeOffsetMessagePackSerializerProvider.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -34,6 +34,7 @@ internal class DateTimeOffsetMessagePackSerializerProvider : MessagePackSerializ { private readonly MessagePackSerializer _unixEpoc; private readonly MessagePackSerializer _native; + private readonly MessagePackSerializer _timestamp; public DateTimeOffsetMessagePackSerializerProvider( SerializationContext context, bool isNullable ) { @@ -44,17 +45,22 @@ public DateTimeOffsetMessagePackSerializerProvider( SerializationContext context new NullableMessagePackSerializer( context, new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.UnixEpoc ) ); this._native = new NullableMessagePackSerializer( context, new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.Native ) ); + this._timestamp = + new NullableMessagePackSerializer( context, new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.Timestamp ) ); #else this._unixEpoc = new NullableMessagePackSerializer( context, typeof( DateTimeOffset? ), new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.UnixEpoc ) ); this._native = new NullableMessagePackSerializer( context, typeof( DateTimeOffset? ), new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.Native ) ); + this._timestamp = + new NullableMessagePackSerializer( context, typeof( DateTimeOffset? ), new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.Timestamp ) ); #endif // !UNITY } else { this._unixEpoc = new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.UnixEpoc ); this._native = new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.Native ); + this._timestamp = new DateTimeOffsetMessagePackSerializer( context, DateTimeConversionMethod.Timestamp ); } } @@ -72,6 +78,10 @@ public override object Get( SerializationContext context, object providerParamet { return this._unixEpoc; } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } } } @@ -85,6 +95,10 @@ public override object Get( SerializationContext context, object providerParamet { return this._unixEpoc; } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } default: { throw new NotSupportedException( @@ -99,4 +113,4 @@ public override object Get( SerializationContext context, object providerParamet } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.cs b/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.cs index 7904b3988..8f1780feb 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -42,7 +42,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_BooleanMessagePackSerializer : MessagePackSerializer< System.Boolean > { public System_BooleanMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Boolean value ) @@ -95,7 +95,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Bo internal sealed class System_ByteMessagePackSerializer : MessagePackSerializer< System.Byte > { public System_ByteMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Byte value ) @@ -148,7 +148,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.By internal sealed class System_CharMessagePackSerializer : MessagePackSerializer< System.Char > { public System_CharMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Char value ) @@ -205,7 +205,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Ch internal sealed class System_DecimalMessagePackSerializer : MessagePackSerializer< System.Decimal > { public System_DecimalMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Decimal value ) @@ -262,7 +262,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.De internal sealed class System_DoubleMessagePackSerializer : MessagePackSerializer< System.Double > { public System_DoubleMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Double value ) @@ -315,12 +315,12 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Do internal sealed class System_GuidMessagePackSerializer : MessagePackSerializer< System.Guid > { public System_GuidMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Guid value ) { - packer.PackRaw( value.ToByteArray() ); + packer.PackBinary( value.ToByteArray() ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -345,7 +345,7 @@ protected internal override System.Guid UnpackFromCore( Unpacker unpacker ) [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override async Task PackToAsyncCore( Packer packer, System.Guid value, CancellationToken cancellationToken ) { - await packer.PackRawAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false ); + await packer.PackBinaryAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -372,7 +372,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Gu internal sealed class System_Int16MessagePackSerializer : MessagePackSerializer< System.Int16 > { public System_Int16MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Int16 value ) @@ -425,7 +425,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.In internal sealed class System_Int32MessagePackSerializer : MessagePackSerializer< System.Int32 > { public System_Int32MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Int32 value ) @@ -478,7 +478,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.In internal sealed class System_Int64MessagePackSerializer : MessagePackSerializer< System.Int64 > { public System_Int64MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Int64 value ) @@ -531,7 +531,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.In internal sealed class System_SByteMessagePackSerializer : MessagePackSerializer< System.SByte > { public System_SByteMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.SByte value ) @@ -584,7 +584,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.SB internal sealed class System_SingleMessagePackSerializer : MessagePackSerializer< System.Single > { public System_SingleMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Single value ) @@ -637,7 +637,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Si internal sealed class System_TimeSpanMessagePackSerializer : MessagePackSerializer< System.TimeSpan > { public System_TimeSpanMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.TimeSpan value ) @@ -693,7 +693,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Ti internal sealed class System_UInt16MessagePackSerializer : MessagePackSerializer< System.UInt16 > { public System_UInt16MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.UInt16 value ) @@ -746,7 +746,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.UI internal sealed class System_UInt32MessagePackSerializer : MessagePackSerializer< System.UInt32 > { public System_UInt32MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.UInt32 value ) @@ -799,7 +799,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.UI internal sealed class System_UInt64MessagePackSerializer : MessagePackSerializer< System.UInt64 > { public System_UInt64MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.UInt64 value ) @@ -855,7 +855,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.UI internal sealed class System_Collections_Specialized_BitVector32MessagePackSerializer : MessagePackSerializer< System.Collections.Specialized.BitVector32 > { public System_Collections_Specialized_BitVector32MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Collections.Specialized.BitVector32 value ) @@ -912,17 +912,17 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Co #endif // !UNITY || MSGPACK_UNITY_FULL #if !WINDOWS_PHONE -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY #if !UNITY || MSGPACK_UNITY_FULL internal sealed class System_Numerics_BigIntegerMessagePackSerializer : MessagePackSerializer< System.Numerics.BigInteger > { public System_Numerics_BigIntegerMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, System.Numerics.BigInteger value ) { - packer.PackRaw( value.ToByteArray() ); + packer.PackBinary( value.ToByteArray() ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -947,7 +947,7 @@ protected internal override System.Numerics.BigInteger UnpackFromCore( Unpacker [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override async Task PackToAsyncCore( Packer packer, System.Numerics.BigInteger value, CancellationToken cancellationToken ) { - await packer.PackRawAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false ); + await packer.PackBinaryAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -970,7 +970,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, System.Nu #endif // FEATURE_TAP } -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY #endif // !WINDOWS_PHONE #endif // !UNITY || MSGPACK_UNITY_FULL // ReSharper restore RedundantCast diff --git a/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.tt b/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.tt index ec3d6a5b6..6091fae95 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.tt +++ b/src/MsgPack/Serialization/DefaultSerializers/DefaultSerializers.tt @@ -1,4 +1,4 @@ -<# +<# // // MessagePack for CLI // @@ -53,6 +53,15 @@ var excludes = typeof( System.Numerics.Quaternion ), // Special handling on serializer: typeof( System.Nullable<> ), + typeof( System.ValueTuple ), + typeof( System.ValueTuple<> ), + typeof( System.ValueTuple<,> ), + typeof( System.ValueTuple<,,> ), + typeof( System.ValueTuple<,,,> ), + typeof( System.ValueTuple<,,,,> ), + typeof( System.ValueTuple<,,,,,> ), + typeof( System.ValueTuple<,,,,,,> ), + typeof( System.ValueTuple<,,,,,,,> ), // Not supported: typeof( void ), typeof( System.IntPtr ), @@ -126,6 +135,9 @@ var excludes = typeof( System.Security.Cryptography.CngProperty ), typeof( System.Security.Cryptography.X509Certificates.X509ChainStatus ), typeof( System.Security.Cryptography.HashAlgorithmName ), + typeof( System.Security.Cryptography.ECCurve ), + typeof( System.Security.Cryptography.ECParameters ), + typeof( System.Security.Cryptography.ECPoint ), typeof( System.Threading.AsyncFlowControl ), typeof( System.Threading.AsyncLocalValueChangedArgs<> ), typeof( System.Threading.CancellationToken ), @@ -154,8 +166,8 @@ var workArounds = { { typeof( char ), new WorkAround(){ PackCode = "packer.Pack( ( System.UInt16 )value );", UnpackCode = "return ( System.Char ) unpacker.LastReadData.AsUInt16(); " } }, { typeof( decimal ), new WorkAround(){ PackCode = "packer.PackString( value.ToString( \"G\", CultureInfo.InvariantCulture ) );", UnpackCode = "return System.Decimal.Parse( unpacker.LastReadData.AsString(), CultureInfo.InvariantCulture ); " } }, - { typeof( Guid ), new WorkAround(){ PackCode = "packer.PackRaw( value.ToByteArray() );", UnpackCode = "return new System.Guid( unpacker.LastReadData.AsBinary() ); " } }, - { typeof( BigInteger ), new WorkAround(){ PackCode = "packer.PackRaw( value.ToByteArray() );", UnpackCode = "return new System.Numerics.BigInteger( unpacker.LastReadData.AsBinary() ); " } }, + { typeof( Guid ), new WorkAround(){ PackCode = "packer.PackBinary( value.ToByteArray() );", UnpackCode = "return new System.Guid( unpacker.LastReadData.AsBinary() ); " } }, + { typeof( BigInteger ), new WorkAround(){ PackCode = "packer.PackBinary( value.ToByteArray() );", UnpackCode = "return new System.Numerics.BigInteger( unpacker.LastReadData.AsBinary() ); " } }, }; var asyncWorkArounds = @@ -163,8 +175,8 @@ var asyncWorkArounds = { { typeof( char ), "packer.PackAsync( ( System.UInt16 )value, cancellationToken ).ConfigureAwait( false );" }, { typeof( decimal ), "packer.PackStringAsync( value.ToString( \"G\", CultureInfo.InvariantCulture ), cancellationToken ).ConfigureAwait( false );" }, - { typeof( Guid ), "packer.PackRawAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false );" }, - { typeof( BigInteger ), "packer.PackRawAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false );" }, + { typeof( Guid ), "packer.PackBinaryAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false );" }, + { typeof( BigInteger ), "packer.PackBinaryAsync( value.ToByteArray(), cancellationToken ).ConfigureAwait( false );" }, }; var notInSLs = @@ -276,7 +288,7 @@ foreach( Type type in types ) if ( notInNetFX35.Contains( type ) ) { #> -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY <# } @@ -292,7 +304,7 @@ foreach( Type type in types ) internal sealed class <#= typeName #> : MessagePackSerializer< <#= ToCSharpToken( type ) #> > { public <#= typeName #>( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, <#= type.FullName #> value ) @@ -522,7 +534,7 @@ foreach( var ctor in ctors ) if ( notInNetFX35.Contains( type ) ) { #> -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY <# } @@ -642,4 +654,4 @@ private struct WorkAround public string PackCode; public string UnpackCode; } -#> \ No newline at end of file +#> diff --git a/src/MsgPack/Serialization/DefaultSerializers/FSharpCollectionSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/FSharpCollectionSerializer`2.cs new file mode 100644 index 000000000..dd0ea0020 --- /dev/null +++ b/src/MsgPack/Serialization/DefaultSerializers/FSharpCollectionSerializer`2.cs @@ -0,0 +1,211 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization.DefaultSerializers +{ + [Preserve( AllMembers = true )] + internal sealed class FSharpCollectionSerializer : MessagePackSerializer + where T : IEnumerable + { + private readonly Func _factory; + + private static Func FindFactory( string factoryTypeName ) + { + var factoryType = + typeof( T ).GetAssembly().GetType( + typeof( T ).Namespace + "." + factoryTypeName + ); + + if ( factoryType == null ) + { + return + _ => + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Cannot find {1}. '{0}' may not be an fsharp collection.", + typeof( T ).AssemblyQualifiedName, + factoryTypeName + ) + ); + }; + } + + var methods = + factoryType + .GetMethods() + .Where( + m => + m.IsStatic + && m.IsPublic + && m.IsGenericMethod + && m.Name == "OfSeq" + && m.GetParameters().Length == 1 + ); + + var method = methods.FirstOrDefault(); + + if ( method == null ) + { + return + _ => + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "'{0}' does not have OfSeq({1}) public static method.", + factoryType.AssemblyQualifiedName, + typeof( IEnumerable ) + ) + ); + }; + } + + var result = method.MakeGenericMethod( typeof( TItem ) ); +#if !UNITY + return result.CreateDelegate( typeof( Func, T> ) ) as Func, T>; +#else + return Delegate.CreateDelegate( typeof( Func, T> ), result ) as Func, T>; +#endif // !UNITY + } + + private readonly MessagePackSerializer _itemSerializer; + + public FSharpCollectionSerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema, string factoryTypeName ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) + { + this._itemSerializer = ownerContext.GetSerializer( itemsSchema ); + this._factory = FindFactory( factoryTypeName ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override void PackToCore( Packer packer, T objectTree ) + { + packer.PackArrayHeader( objectTree.Count() ); + + foreach ( var item in objectTree ) + { + this._itemSerializer.PackTo( packer, item ); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override T UnpackFromCore( Unpacker unpacker ) + { + if ( !unpacker.IsArrayHeader ) + { + SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); + } + + var buffer = new TItem[ UnpackHelpers.GetItemsCount( unpacker ) ]; + + using ( var subTreeUnpacker = unpacker.ReadSubtree() ) + { + for ( int i = 0; i < buffer.Length; i++ ) + { + if ( !subTreeUnpacker.Read() ) + { + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); + } + + buffer[ i ] = this._itemSerializer.UnpackFrom( subTreeUnpacker ); + } + } + + return this._factory( buffer ); + } + + protected internal override void UnpackToCore( Unpacker unpacker, T collection ) + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Unable to unpack items to existing immutable collection '{0}'.", + typeof( T ) + ) + ); + } + +#if FEATURE_TAP + + protected internal override async Task PackToAsyncCore( Packer packer, T objectTree, CancellationToken cancellationToken ) + { + await packer.PackArrayHeaderAsync( objectTree.Count(), cancellationToken ).ConfigureAwait( false ); + + foreach ( var item in objectTree ) + { + await this._itemSerializer.PackToAsync( packer, item, cancellationToken ).ConfigureAwait( false ); + } + } + + protected internal override async Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) + { + if ( !unpacker.IsArrayHeader ) + { + SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); + } + + var buffer = new TItem[ UnpackHelpers.GetItemsCount( unpacker ) ]; + + using ( var subTreeUnpacker = unpacker.ReadSubtree() ) + { + for ( int i = 0; i < buffer.Length; i++ ) + { + if ( !await subTreeUnpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) + { + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); + } + + buffer[ i ] = await this._itemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ); + } + } + + return this._factory( buffer ); + } + + protected internal override Task UnpackToAsyncCore( Unpacker unpacker, T collection, CancellationToken cancellationToken ) + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Unable to unpack items to existing immutable collection '{0}'.", + typeof( T ) + ) + ); + } + +#endif // FEATURE_TAP + + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/DefaultSerializers/FSharpMapSerializer`3.cs b/src/MsgPack/Serialization/DefaultSerializers/FSharpMapSerializer`3.cs new file mode 100644 index 000000000..5c3defc46 --- /dev/null +++ b/src/MsgPack/Serialization/DefaultSerializers/FSharpMapSerializer`3.cs @@ -0,0 +1,232 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization.DefaultSerializers +{ + [Preserve( AllMembers = true )] + internal sealed class FSharpMapSerializer : MessagePackSerializer + where T : IEnumerable> + { + private readonly Func>, T> _factory; + + private static Func>, T> FindFactory() + { + var factoryType = + typeof( T ).GetAssembly().GetType( + typeof( T ).Namespace + ".MapModule" + ); + + if ( factoryType == null ) + { + return + _ => + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Cannot find MapModule. '{0}' may not be an fsharp collection.", + typeof( T ).AssemblyQualifiedName + ) + ); + }; + } + + var methods = + factoryType + .GetMethods() + .Where( + m => + m.IsStatic + && m.IsPublic + && m.IsGenericMethod + && m.Name == "OfSeq" + && m.GetParameters().Length == 1 + ); + + var method = methods.FirstOrDefault(); + + if ( method == null ) + { + return + _ => + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "'{0}' does not have OfSeq({1}) public static method.", + factoryType.AssemblyQualifiedName, + typeof( IEnumerable> ) + ) + ); + }; + } + + var result = method.MakeGenericMethod( typeof( TKey ), typeof( TValue ) ); +#if !UNITY + return result.CreateDelegate( typeof( Func>, T> ) ) as Func>, T>; +#else + return Delegate.CreateDelegate( typeof( Func>, T> ), result ) as Func>, T>; +#endif // !UNITY + } + + private readonly MessagePackSerializer _keySerializer; + private readonly MessagePackSerializer _valueSerializer; + + public FSharpMapSerializer( SerializationContext ownerContext, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) + { + this._keySerializer = ownerContext.GetSerializer( keysSchema ); + this._valueSerializer = ownerContext.GetSerializer( valuesSchema ); + this._factory = FindFactory(); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override void PackToCore( Packer packer, T objectTree ) + { + packer.PackMapHeader( objectTree.Count() ); + + foreach ( var item in objectTree ) + { + this._keySerializer.PackTo( packer, item.Key ); + this._valueSerializer.PackTo( packer, item.Value ); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override T UnpackFromCore( Unpacker unpacker ) + { + if ( !unpacker.IsMapHeader ) + { + SerializationExceptions.ThrowIsNotMapHeader( unpacker ); + } + + var buffer = new Tuple[ UnpackHelpers.GetItemsCount( unpacker ) ]; + + using ( var subTreeUnpacker = unpacker.ReadSubtree() ) + { + for ( int i = 0; i < buffer.Length; i++ ) + { + if ( !subTreeUnpacker.Read() ) + { + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); + } + + var key = this._keySerializer.UnpackFrom( unpacker ); + + if ( !subTreeUnpacker.Read() ) + { + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); + } + + var value = this._valueSerializer.UnpackFrom( unpacker ); + + buffer[ i ] = new Tuple( key, value ); + } + } + + return this._factory( buffer ); + } + + protected internal override void UnpackToCore( Unpacker unpacker, T collection ) + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Unable to unpack items to existing F# map '{0}'.", + typeof( T ) + ) + ); + } + +#if FEATURE_TAP + + protected internal override async Task PackToAsyncCore( Packer packer, T objectTree, CancellationToken cancellationToken ) + { + await packer.PackMapHeaderAsync( objectTree.Count(), cancellationToken ).ConfigureAwait( false ); + + foreach ( var item in objectTree ) + { + await this._keySerializer.PackToAsync( packer, item.Key, cancellationToken ).ConfigureAwait( false ); + await this._valueSerializer.PackToAsync( packer, item.Value, cancellationToken ).ConfigureAwait( false ); + } + } + + protected internal override async Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) + { + if ( !unpacker.IsMapHeader ) + { + SerializationExceptions.ThrowIsNotMapHeader( unpacker ); + } + + var buffer = new Tuple[ UnpackHelpers.GetItemsCount( unpacker ) ]; + + using ( var subTreeUnpacker = unpacker.ReadSubtree() ) + { + for ( int i = 0; i < buffer.Length; i++ ) + { + if ( !await subTreeUnpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) + { + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); + } + + var key = await this._keySerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ); + + if ( !await subTreeUnpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) + { + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); + } + + var value = await this._valueSerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ); + + buffer[ i ] = new Tuple( key, value ); + } + } + + return this._factory( buffer ); + } + + protected internal override Task UnpackToAsyncCore( Unpacker unpacker, T collection, CancellationToken cancellationToken ) + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Unable to unpack items to existing F# map '{0}'.", + typeof( T ) + ) + ); + } + +#endif // FEATURE_TAP + + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/DefaultSerializers/FileTimeMessagePackSerializerProvider.cs b/src/MsgPack/Serialization/DefaultSerializers/FileTimeMessagePackSerializerProvider.cs index 1ec3e36a3..f10869b3d 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/FileTimeMessagePackSerializerProvider.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/FileTimeMessagePackSerializerProvider.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ internal class FileTimeMessagePackSerializerProvider : MessagePackSerializerProv { private readonly MessagePackSerializer _unixEpoc; private readonly MessagePackSerializer _native; + private readonly MessagePackSerializer _timestamp; public FileTimeMessagePackSerializerProvider( SerializationContext context, bool isNullable ) { @@ -45,17 +46,22 @@ public FileTimeMessagePackSerializerProvider( SerializationContext context, bool new NullableMessagePackSerializer( context, new UnixEpocFileTimeMessagePackSerializer( context ) ); this._native = new NullableMessagePackSerializer( context, new NativeFileTimeMessagePackSerializer( context ) ); + this._timestamp = + new NullableMessagePackSerializer( context, new TimestampFileTimeMessagePackSerializer( context ) ); #else this._unixEpoc = new NullableMessagePackSerializer( context, typeof( FILETIME? ), new UnixEpocFileTimeMessagePackSerializer( context ) ); this._native = new NullableMessagePackSerializer( context, typeof( FILETIME? ), new NativeFileTimeMessagePackSerializer( context ) ); + this._timestamp = + new NullableMessagePackSerializer( context, typeof( FILETIME? ), new TimestampFileTimeMessagePackSerializer( context ) ); #endif // !UNITY } else { this._unixEpoc = new UnixEpocFileTimeMessagePackSerializer( context ); this._native = new NativeFileTimeMessagePackSerializer( context ); + this._timestamp = new TimestampFileTimeMessagePackSerializer( context ); } } @@ -73,6 +79,10 @@ public override object Get( SerializationContext context, object providerParamet { return this._unixEpoc; } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } } } @@ -86,6 +96,10 @@ public override object Get( SerializationContext context, object providerParamet { return this._unixEpoc; } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } default: { throw new NotSupportedException( @@ -100,4 +114,4 @@ public override object Get( SerializationContext context, object providerParamet } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/GenericSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/GenericSerializer.cs index 329c0e3a2..30b99f939 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/GenericSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/GenericSerializer.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2012-2015 FUJIWARA, Yusuke +// Copyright (C) 2012-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -27,11 +30,11 @@ using System.Collections; #endif // !UNITY using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack.Serialization.DefaultSerializers { @@ -74,7 +77,7 @@ public static MessagePackSerializer Create( SerializationContext context, Type t #if !UNITY return CreateListSerializer( context, targetType.GetGenericArguments()[ 0 ], schema ); #else - return CreateListSerializer( context, targetType, targetType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod ), schema ); + return CreateListSerializer( context, targetType, targetType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ), schema ); #endif // !UNITY } @@ -84,7 +87,7 @@ public static MessagePackSerializer Create( SerializationContext context, Type t #if !UNITY return CreateDictionarySerializer( context, genericTypeArguments[ 0 ], genericTypeArguments[ 1 ], schema ); #else - return CreateDictionarySerializer( context, targetType, targetType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod ), genericTypeArguments[ 0 ], genericTypeArguments[ 1 ], schema ); + return CreateDictionarySerializer( context, targetType, targetType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ), genericTypeArguments[ 0 ], genericTypeArguments[ 1 ], schema ); #endif // !UNITY } } @@ -122,12 +125,12 @@ private static MessagePackSerializer CreateNullableSerializer( SerializationCont #if !UNITY private static MessagePackSerializer CreateListSerializer( SerializationContext context, Type itemType, PolymorphismSchema schema ) { -#if DEBUG && !XAMARIN && !UNITY_IPHONE && !UNITY_ANDROID +#if DEBUG if ( SerializerDebugging.AvoidsGenericSerializer ) { return null; } -#endif // DEBUG && !XAMARIN && !UNITY_IPHONE && !UNITY_ANDROID +#endif // DEBUG return ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( ListInstanceFactory<> ).MakeGenericType( itemType ) @@ -143,12 +146,12 @@ private static MessagePackSerializer CreateListSerializer( SerializationContext #if !UNITY private static MessagePackSerializer CreateDictionarySerializer( SerializationContext context, Type keyType, Type valueType, PolymorphismSchema schema ) { -#if DEBUG && !XAMARIN && !UNITY_IPHONE && !UNITY_ANDROID +#if DEBUG if ( SerializerDebugging.AvoidsGenericSerializer ) { return null; } -#endif // DEBUG && !XAMARIN && !UNITY_IPHONE && !UNITY_ANDROID +#endif // DEBUG return ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( DictionaryInstanceFactory<,> ).MakeGenericType( keyType, valueType ) @@ -172,18 +175,19 @@ private static MessagePackSerializer CreateDictionarySerializer( SerializationCo #endif // !UNITY #if !UNITY -#if SILVERLIGHT || NETFX_35 || NETFX_40 +#if SILVERLIGHT || NET35 || NET40 [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context", Justification = "Used in other platform" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "targetType", Justification = "Used in other platform" )] #endif // SILVERLIGHT // ReSharper disable UnusedParameter.Local private static MessagePackSerializer TryCreateImmutableCollectionSerializer( SerializationContext context, Type targetType, PolymorphismSchema schema ) { -#if NETFX_35 || NETFX_40 || SILVERLIGHT +#if NET35 || NET40 || SILVERLIGHT // ImmutableCollections does not support above platforms. return null; #else - if ( targetType.Namespace != "System.Collections.Immutable" ) + if ( targetType.Namespace != "System.Collections.Immutable" + && targetType.Namespace != "Microsoft.FSharp.Collections" ) { return null; } @@ -194,7 +198,7 @@ private static MessagePackSerializer TryCreateImmutableCollectionSerializer( Ser } var itemSchema = ( schema ?? PolymorphismSchema.Default ); - switch ( DetermineImmutableCollectionType(targetType) ) + switch ( DetermineImmutableCollectionType( targetType ) ) { case ImmutableCollectionType.ImmutableArray: case ImmutableCollectionType.ImmutableList: @@ -222,6 +226,29 @@ private static MessagePackSerializer TryCreateImmutableCollectionSerializer( Ser typeof( ImmutableDictionarySerializerFactory<,,> ).MakeGenericType( targetType, targetType.GetGenericArguments()[ 0 ], targetType.GetGenericArguments()[ 1 ] ) ).Create( context, itemSchema ); } + case ImmutableCollectionType.FSharpList: + { + return + ReflectionExtensions.CreateInstancePreservingExceptionType( + typeof( FSharpCollectionSerializerFactory<,> ).MakeGenericType( targetType, targetType.GetGenericArguments()[ 0 ] ), + "ListModule" + ).Create( context, itemSchema ); + } + case ImmutableCollectionType.FSharpSet: + { + return + ReflectionExtensions.CreateInstancePreservingExceptionType( + typeof( FSharpCollectionSerializerFactory<,> ).MakeGenericType( targetType, targetType.GetGenericArguments()[ 0 ] ), + "SetModule" + ).Create( context, itemSchema ); + } + case ImmutableCollectionType.FSharpMap: + { + return + ReflectionExtensions.CreateInstancePreservingExceptionType( + typeof( FSharpMapSerializerFactory<,,> ).MakeGenericType( targetType, targetType.GetGenericArguments()[ 0 ], targetType.GetGenericArguments()[ 1 ] ) + ).Create( context, itemSchema ); + } default: { #if DEBUG @@ -232,13 +259,14 @@ private static MessagePackSerializer TryCreateImmutableCollectionSerializer( Ser // ReSharper restore HeuristicUnreachableCode } } -#endif // NETFX_35 || NETFX_40 || SILVERLIGHT +#endif // NET35 || NET40 || SILVERLIGHT } -#if !NETFX_35 && !NETFX_40 && !SILVERLIGHT +#if !NET35 && !NET40 && !SILVERLIGHT private static ImmutableCollectionType DetermineImmutableCollectionType( Type targetType ) { - if ( targetType.Namespace != "System.Collections.Immutable" ) + if ( targetType.Namespace != "System.Collections.Immutable" + && targetType.Namespace != "Microsoft.FSharp.Collections" ) { return ImmutableCollectionType.Unknown; } @@ -282,6 +310,18 @@ private static ImmutableCollectionType DetermineImmutableCollectionType( Type ta { return ImmutableCollectionType.ImmutableSortedDictionary; } + case "FSharpList`1": + { + return ImmutableCollectionType.FSharpList; + } + case "FSharpSet`1": + { + return ImmutableCollectionType.FSharpSet; + } + case "FSharpMap`2": + { + return ImmutableCollectionType.FSharpMap; + } default: { #if DEBUG @@ -293,7 +333,7 @@ private static ImmutableCollectionType DetermineImmutableCollectionType( Type ta } } } -#endif // !NETFX_35 && !NETFX_40 && !SILVERLIGHT +#endif // !NET35 && !NET40 && !SILVERLIGHT #endif // !UNITY public static MessagePackSerializer TryCreateAbstractCollectionSerializer( SerializationContext context, Type abstractType, Type concreteType, PolymorphismSchema schema ) @@ -309,7 +349,7 @@ public static MessagePackSerializer TryCreateAbstractCollectionSerializer( Seria abstractType, concreteType, schema, - abstractType.GetCollectionTraits( CollectionTraitOptions.None ) + abstractType.GetCollectionTraits( CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) ); } @@ -318,9 +358,9 @@ internal static MessagePackSerializer TryCreateAbstractCollectionSerializer( Ser switch ( traits.DetailedCollectionType ) { case CollectionDetailedKind.GenericList: -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY case CollectionDetailedKind.GenericSet: -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY case CollectionDetailedKind.GenericCollection: { #if !UNITY @@ -332,7 +372,7 @@ internal static MessagePackSerializer TryCreateAbstractCollectionSerializer( Ser return new AbstractCollectionMessagePackSerializer( context, abstractType, concreteType, traits, schema ); #endif } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyList: case CollectionDetailedKind.GenericReadOnlyCollection: { @@ -345,7 +385,7 @@ internal static MessagePackSerializer TryCreateAbstractCollectionSerializer( Ser return new AbstractCollectionMessagePackSerializer( context, abstractType, concreteType, traits, schema ); #endif } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericEnumerable: { #if !UNITY @@ -373,7 +413,7 @@ genericArgumentOfKeyValuePair[ 1 ] return new AbstractDictionaryMessagePackSerializer( context, abstractType, concreteType, genericArgumentOfKeyValuePair[ 0 ], genericArgumentOfKeyValuePair[ 1 ], traits, schema ); #endif } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.GenericReadOnlyDictionary: { var genericArgumentOfKeyValuePair = traits.ElementType.GetGenericArguments(); @@ -390,7 +430,7 @@ genericArgumentOfKeyValuePair[ 1 ] return new AbstractDictionaryMessagePackSerializer( context, abstractType, concreteType, genericArgumentOfKeyValuePair[ 0 ], genericArgumentOfKeyValuePair[ 1 ], traits, schema ); #endif } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) case CollectionDetailedKind.NonGenericList: { #if !UNITY @@ -476,13 +516,13 @@ internal static bool IsSupported( Type type, CollectionTraits traits, bool prefe } } -#if !UNITY && !NETFX_35 && !NETFX_40 && !SILVERLIGHT +#if !UNITY && !NET35 && !NET40 && !SILVERLIGHT // ImmutableCollections does not support above platforms. if ( DetermineImmutableCollectionType( type ) != ImmutableCollectionType.Unknown ) { return true; } -#endif // !UNITY && !NETFX_35 && !NETFX_40 && !SILVERLIGHT +#endif // !UNITY && !NET35 && !NET40 && !SILVERLIGHT if ( preferReflectionBasedSerializer ) { @@ -498,13 +538,23 @@ internal static bool IsSupported( Type type, CollectionTraits traits, bool prefe /// /// Defines non-generic factory method for built-in serializers which require generic type argument. /// - private interface IGenericBuiltInSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + interface IGenericBuiltInSerializerFactory { MessagePackSerializer Create( SerializationContext context, PolymorphismSchema schema ); } [Preserve( AllMembers = true )] - private sealed class NullableInstanceFactory : IGenericBuiltInSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NullableInstanceFactory : IGenericBuiltInSerializerFactory where T : struct { public NullableInstanceFactory() { } @@ -516,7 +566,12 @@ public MessagePackSerializer Create( SerializationContext context, PolymorphismS } [Preserve( AllMembers = true )] - private sealed class ListInstanceFactory : IGenericBuiltInSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class ListInstanceFactory : IGenericBuiltInSerializerFactory { public ListInstanceFactory() { } @@ -528,7 +583,12 @@ public MessagePackSerializer Create( SerializationContext context, PolymorphismS } [Preserve( AllMembers = true )] - private sealed class DictionaryInstanceFactory : IGenericBuiltInSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class DictionaryInstanceFactory : IGenericBuiltInSerializerFactory { public DictionaryInstanceFactory() { } @@ -539,7 +599,7 @@ public MessagePackSerializer Create( SerializationContext context, PolymorphismS } } -#if !NETFX_35 && !NETFX_40 && !SILVERLIGHT +#if !NET35 && !NET40 && !SILVERLIGHT [Preserve( AllMembers = true )] private sealed class ImmutableCollectionSerializerFactory : IGenericBuiltInSerializerFactory @@ -580,19 +640,60 @@ public MessagePackSerializer Create( SerializationContext context, PolymorphismS } } + + [Preserve( AllMembers = true )] + private sealed class FSharpCollectionSerializerFactory : IGenericBuiltInSerializerFactory + where T : IEnumerable + { + private readonly string _factoryTypeName; + + public FSharpCollectionSerializerFactory( string factoryTypeName ) + { + this._factoryTypeName = factoryTypeName; + } + + public MessagePackSerializer Create( SerializationContext context, PolymorphismSchema schema ) + { + var itemSchema = schema ?? PolymorphismSchema.Default; + return new FSharpCollectionSerializer( context, itemSchema.ItemSchema, this._factoryTypeName ); + } + } + + [Preserve( AllMembers = true )] + private sealed class FSharpMapSerializerFactory : IGenericBuiltInSerializerFactory + where T : IDictionary + { + public FSharpMapSerializerFactory() { } + + public MessagePackSerializer Create( SerializationContext context, PolymorphismSchema schema ) + { + var itemSchema = schema ?? PolymorphismSchema.Default; + return new FSharpMapSerializer( context, itemSchema.KeySchema, itemSchema.ItemSchema ); + } + } #endif /// /// Defines non-generic factory method for 'universal' serializers which use general collection features. /// - private interface IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + interface IVariantSerializerFactory { MessagePackSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema ); } // ReSharper disable MemberHidesStaticFromOuterClass [Preserve( AllMembers = true )] - private sealed class NonGenericEnumerableSerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericEnumerableSerializerFactory : IVariantSerializerFactory where T : IEnumerable { public NonGenericEnumerableSerializerFactory() { } @@ -604,7 +705,12 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } [Preserve( AllMembers = true )] - private sealed class NonGenericCollectionSerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericCollectionSerializerFactory : IVariantSerializerFactory where T : ICollection { public NonGenericCollectionSerializerFactory() { } @@ -616,7 +722,12 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } [Preserve( AllMembers = true )] - private sealed class NonGenericListSerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericListSerializerFactory : IVariantSerializerFactory where T : IList { public NonGenericListSerializerFactory() { } @@ -628,7 +739,12 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } [Preserve( AllMembers = true )] - private sealed class NonGenericDictionarySerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericDictionarySerializerFactory : IVariantSerializerFactory where T : IDictionary { public NonGenericDictionarySerializerFactory() { } @@ -640,7 +756,12 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } [Preserve( AllMembers = true )] - private sealed class EnumerableSerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class EnumerableSerializerFactory : IVariantSerializerFactory where TCollection : IEnumerable { public EnumerableSerializerFactory() { } @@ -652,7 +773,12 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } [Preserve( AllMembers = true )] - private sealed class CollectionSerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class CollectionSerializerFactory : IVariantSerializerFactory where TCollection : ICollection { public CollectionSerializerFactory() { } @@ -663,7 +789,7 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) [Preserve( AllMembers = true )] private sealed class ReadOnlyCollectionSerializerFactory : IVariantSerializerFactory where TCollection : IReadOnlyCollection @@ -675,10 +801,15 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy return new AbstractReadOnlyCollectionMessagePackSerializer( context, targetType, schema ); } } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) [Preserve( AllMembers = true )] - private sealed class DictionarySerializerFactory : IVariantSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class DictionarySerializerFactory : IVariantSerializerFactory where TDictionary : IDictionary { public DictionarySerializerFactory() { } @@ -689,7 +820,7 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy } } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) [Preserve( AllMembers = true )] private sealed class ReadOnlyDictionarySerializerFactory : IVariantSerializerFactory where TDictionary : IReadOnlyDictionary @@ -701,11 +832,11 @@ public MessagePackSerializer Create( SerializationContext context, Type targetTy return new AbstractReadOnlyDictionaryMessagePackSerializer( context, targetType, schema ); } } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) // ReSharper restore MemberHidesStaticFromOuterClass #endif // !UNITY -#if !NETFX_35 && !NETFX_40 && !SILVERLIGHT && !UNITY +#if !NET35 && !NET40 && !SILVERLIGHT && !UNITY private enum ImmutableCollectionType { Unknown = 0, @@ -717,7 +848,10 @@ private enum ImmutableCollectionType ImmutableSortedDictionary, ImmutableSortedSet, ImmutableStack, + FSharpList, + FSharpMap, + FSharpSet, } -#endif // !NETFX_35 && !NETFX_40 && !SILVERLIGHT && !UNITY +#endif // !NET35 && !NET40 && !SILVERLIGHT && !UNITY } } diff --git a/src/MsgPack/Serialization/DefaultSerializers/ImmutableCollectionSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/ImmutableCollectionSerializer`2.cs index d955d26f3..db522ff08 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/ImmutableCollectionSerializer`2.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/ImmutableCollectionSerializer`2.cs @@ -37,7 +37,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal class ImmutableCollectionSerializer : MessagePackSerializer where T : IEnumerable { - protected static readonly Func Factory = FindFactory(); + protected readonly Func Factory; private static Func FindFactory() { @@ -98,12 +98,13 @@ private static Func FindFactory() #endif // !UNITY } - private readonly MessagePackSerializer _itemSerializer; + protected readonly MessagePackSerializer ItemSerializer; public ImmutableCollectionSerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { - this._itemSerializer = ownerContext.GetSerializer( itemsSchema ); + this.ItemSerializer = ownerContext.GetSerializer( itemsSchema ); + this.Factory = FindFactory(); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -113,7 +114,7 @@ protected internal override void PackToCore( Packer packer, T objectTree ) foreach ( var item in objectTree ) { - this._itemSerializer.PackTo( packer, item ); + this.ItemSerializer.PackTo( packer, item ); } } @@ -136,11 +137,11 @@ protected internal override T UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - buffer[ i ] = this._itemSerializer.UnpackFrom( subTreeUnpacker ); + buffer[ i ] = this.ItemSerializer.UnpackFrom( subTreeUnpacker ); } } - return Factory( buffer ); + return this.Factory( buffer ); } protected internal override void UnpackToCore( Unpacker unpacker, T collection ) @@ -162,7 +163,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, T objectT foreach ( var item in objectTree ) { - await this._itemSerializer.PackToAsync( packer, item, cancellationToken ).ConfigureAwait( false ); + await this.ItemSerializer.PackToAsync( packer, item, cancellationToken ).ConfigureAwait( false ); } } @@ -184,11 +185,11 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker unpacker SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - buffer[ i ] = await this._itemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ); + buffer[ i ] = await this.ItemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ); } } - return Factory( buffer ); + return this.Factory( buffer ); } protected internal override Task UnpackToAsyncCore( Unpacker unpacker, T collection, CancellationToken cancellationToken ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/ImmutableDictionarySerializer`3.cs b/src/MsgPack/Serialization/DefaultSerializers/ImmutableDictionarySerializer`3.cs index 7c39b0357..58f1621b3 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/ImmutableDictionarySerializer`3.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/ImmutableDictionarySerializer`3.cs @@ -37,7 +37,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class ImmutableDictionarySerializer : MessagePackSerializer where T : IEnumerable> { - private static readonly Func[], T> _factory = FindFactory(); + private readonly Func[], T> _factory; private static Func[], T> FindFactory() { @@ -85,7 +85,7 @@ private static Func[], T> FindFactory() CultureInfo.CurrentCulture, "'{0}' does not have CreateRange({1}[]) public static method.", factoryType.AssemblyQualifiedName, - typeof( IEnumerable> ) + typeof( KeyValuePair ) ) ); }; @@ -103,10 +103,11 @@ private static Func[], T> FindFactory() private readonly MessagePackSerializer _valueSerializer; public ImmutableDictionarySerializer( SerializationContext ownerContext, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._keySerializer = ownerContext.GetSerializer( keysSchema ); this._valueSerializer = ownerContext.GetSerializer( valuesSchema ); + this._factory = FindFactory(); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -153,7 +154,7 @@ protected internal override T UnpackFromCore( Unpacker unpacker ) } } - return _factory( buffer ); + return this._factory( buffer ); } protected internal override void UnpackToCore( Unpacker unpacker, T collection ) @@ -211,7 +212,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker unpacker } } - return _factory( buffer ); + return this._factory( buffer ); } protected internal override Task UnpackToAsyncCore( Unpacker unpacker, T collection, CancellationToken cancellationToken ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/ImmutableStackSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/ImmutableStackSerializer`2.cs index 5d5726920..3d96429b3 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/ImmutableStackSerializer`2.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/ImmutableStackSerializer`2.cs @@ -31,13 +31,8 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class ImmutableStackSerializer : ImmutableCollectionSerializer where T : IEnumerable { - private readonly MessagePackSerializer _itemSerializer; - public ImmutableStackSerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) - : base( ownerContext, itemsSchema ) - { - this._itemSerializer = ownerContext.GetSerializer( itemsSchema ); - } + : base( ownerContext, itemsSchema ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override T UnpackFromCore( Unpacker unpacker ) @@ -59,11 +54,11 @@ protected internal override T UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - buffer[ i ] = this._itemSerializer.UnpackFrom( subTreeUnpacker ); + buffer[ i ] = this.ItemSerializer.UnpackFrom( subTreeUnpacker ); } } - return Factory( buffer ); + return this.Factory( buffer ); } #if FEATURE_TAP @@ -87,11 +82,11 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker unpacker SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - buffer[ i ] = await this._itemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ); + buffer[ i ] = await this.ItemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ); } } - return Factory( buffer ); + return this.Factory( buffer ); } #endif // FEATURE_TAP diff --git a/src/MsgPack/Serialization/DefaultSerializers/InternalDateTimeExtensions.cs b/src/MsgPack/Serialization/DefaultSerializers/InternalDateTimeExtensions.cs index b0cf6e135..4924a5301 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/InternalDateTimeExtensions.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/InternalDateTimeExtensions.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -23,9 +23,9 @@ #endif using System; -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY using System.Runtime.InteropServices.ComTypes; -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY namespace MsgPack.Serialization.DefaultSerializers { @@ -70,7 +70,7 @@ public static Int64 ToBinary( this DateTime source ) // End porting #endif // SILVERLIGHT -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY private static readonly DateTime _fileTimeEpocUtc = new DateTime( 1601, 1, 1, 0, 0, 0, DateTimeKind.Utc ); public static DateTime ToDateTime( this FILETIME source ) @@ -92,6 +92,6 @@ public static FILETIME ToWin32FileTimeUtc( this DateTime source ) dwLowDateTime = unchecked( ( int ) ( value & 0xffffffff ) ) }; } -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/MessagePackObjectExtensions.cs b/src/MsgPack/Serialization/DefaultSerializers/MessagePackObjectExtensions.cs index accf3cc1e..4336e25bf 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/MessagePackObjectExtensions.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/MessagePackObjectExtensions.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -26,6 +26,24 @@ namespace MsgPack.Serialization.DefaultSerializers { internal static class MessagePackObjectExtensions { + /// + /// Invokes in deserializaton manner. + /// + /// . + /// A deserialized value. + /// is not expected type. + public static long DeserializeAsInt64( this MessagePackObject source ) + { + try + { + return source.AsInt64(); + } + catch ( InvalidOperationException ex ) + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message ), ex ); + } + } + /// /// Invokes in deserializaton manner. /// @@ -43,5 +61,23 @@ public static string DeserializeAsString( this MessagePackObject source ) throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message ), ex ); } } + + /// + /// Invokes in deserializaton manner. + /// + /// . + /// A deserialized value. + /// is not expected type. + public static MessagePackExtendedTypeObject DeserializeAsMessagePackExtendedTypeObject( this MessagePackObject source ) + { + try + { + return source.AsMessagePackExtendedTypeObject(); + } + catch ( InvalidOperationException ex ) + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message ), ex ); + } + } } } diff --git a/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs index cb7070e8d..5455582bb 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs @@ -19,6 +19,8 @@ #endregion -- License Terms -- using System; +using System.Globalization; +using System.Runtime.Serialization; #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; @@ -30,7 +32,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer : MessagePackSerializer { public MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, MessagePackExtendedTypeObject value ) @@ -41,7 +43,14 @@ protected internal override void PackToCore( Packer packer, MessagePackExtendedT [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override MessagePackExtendedTypeObject UnpackFromCore( Unpacker unpacker ) { - return unpacker.LastReadData.AsMessagePackExtendedTypeObject(); + try + { + return unpacker.LastReadData.AsMessagePackExtendedTypeObject(); + } + catch ( InvalidOperationException ex ) + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message ), ex ); + } } #if FEATURE_TAP diff --git a/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs index c8d8c9149..fd540677c 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectDictionaryMessagePackSerializer.cs @@ -32,7 +32,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class MsgPack_MessagePackObjectDictionaryMessagePackSerializer : MessagePackSerializer, ICollectionInstanceFactory { public MsgPack_MessagePackObjectDictionaryMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] diff --git a/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectMessagePackSerializer.cs index e6f97f8f2..8fe869fbe 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackObjectMessagePackSerializer.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; #if FEATURE_TAP using System.Threading; @@ -27,10 +31,15 @@ namespace MsgPack.Serialization.DefaultSerializers { // ReSharper disable once InconsistentNaming - internal sealed class MsgPack_MessagePackObjectMessagePackSerializer : MessagePackSerializer +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class MsgPack_MessagePackObjectMessagePackSerializer : MessagePackSerializer { public MsgPack_MessagePackObjectMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } protected internal override void PackToCore( Packer packer, MessagePackObject value ) { diff --git a/src/MsgPack/Serialization/DefaultSerializers/MultidimensionalArraySerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/MultidimensionalArraySerializer`1.cs index a2e4930bd..914062e19 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/MultidimensionalArraySerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/MultidimensionalArraySerializer`1.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -51,14 +51,14 @@ internal sealed class UnityMultidimensionalArraySerializer : NonGenericMessagePa #if !UNITY public MultidimensionalArraySerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._itemSerializer = ownerContext.GetSerializer( itemsSchema ); this._int32ArraySerializer = ownerContext.GetSerializer( itemsSchema ); } #else public UnityMultidimensionalArraySerializer( SerializationContext ownerContext, Type itemType, PolymorphismSchema itemsSchema ) - : base( ownerContext, itemType.MakeArrayType() ) + : base( ownerContext, itemType.MakeArrayType(), SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._itemSerializer = ownerContext.GetSerializer( itemType, itemsSchema ); this._int32ArraySerializer = ownerContext.GetSerializer( typeof( int[] ), itemsSchema ); @@ -444,7 +444,7 @@ this.OwnerContext.ExtTypeCodeMapping[ KnownExtTypeName.MultidimensionalArray ] var totalLength = UnpackHelpers.GetItemsCount( arrayUnpacker ); if ( totalLength > 0 ) { - ForEach( + await ForEachAsync( result, totalLength, lengthsAndLowerBounds.Item2, @@ -463,7 +463,7 @@ await this._itemSerializer.UnpackFromAsync( arrayUnpacker, cancellationToken ).C ); // ReSharper restore AccessToDisposedClosure } - ); + ).ConfigureAwait( false ); } return ( TArray )( object )result; @@ -536,5 +536,35 @@ private static void ForEach( Array array, int totalLength, int[] lowerBounds, in } } } + +#if FEATURE_TAP + + private static async Task ForEachAsync( Array array, int totalLength, int[] lowerBounds, int[] lengths, Func action ) + { + var indices = new int[ array.Rank ]; + for ( var dimension = 0; dimension < array.Rank; dimension++ ) + { + indices[ dimension ] = lowerBounds[ dimension ]; + } + + for ( var i = 0; i < totalLength; i++ ) + { + await action( indices ).ConfigureAwait( false ); + // Canculate indices with carrying up. + var dimension = indices.Length - 1; + for ( ; dimension >= 0; dimension-- ) + { + if ( ( indices[ dimension ] + 1 ) < lengths[ dimension ] + lowerBounds[ dimension ] ) + { + indices[ dimension ]++; + break; + } + + // Let's carry up, so set 0 to current dimension. + indices[ dimension ] = lowerBounds[ dimension ]; + } + } + } +#endif // FEATURE_TAP } } \ No newline at end of file diff --git a/src/MsgPack/Serialization/DefaultSerializers/NativeDateTimeMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/NativeDateTimeMessagePackSerializer.cs index 4c01a8bcd..58d5d9256 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/NativeDateTimeMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/NativeDateTimeMessagePackSerializer.cs @@ -31,7 +31,7 @@ namespace MsgPack.Serialization.DefaultSerializers /// internal class NativeDateTimeMessagePackSerializer : MessagePackSerializer { - public NativeDateTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext ) { } + public NativeDateTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, DateTime objectTree ) @@ -42,7 +42,7 @@ protected internal override void PackToCore( Packer packer, DateTime objectTree [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override DateTime UnpackFromCore( Unpacker unpacker ) { - return DateTime.FromBinary( unpacker.LastReadData.AsInt64() ); + return DateTime.FromBinary( unpacker.LastReadData.DeserializeAsInt64() ); } #if FEATURE_TAP diff --git a/src/MsgPack/Serialization/DefaultSerializers/NativeFileTimeMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/NativeFileTimeMessagePackSerializer.cs index fdfe16d2d..a1a81cd04 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/NativeFileTimeMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/NativeFileTimeMessagePackSerializer.cs @@ -32,7 +32,7 @@ namespace MsgPack.Serialization.DefaultSerializers /// internal sealed class NativeFileTimeMessagePackSerializer : MessagePackSerializer { - public NativeFileTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext ) { } + public NativeFileTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, FILETIME objectTree ) @@ -43,7 +43,7 @@ protected internal override void PackToCore( Packer packer, FILETIME objectTree [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override FILETIME UnpackFromCore( Unpacker unpacker ) { - return DateTime.FromBinary( unpacker.LastReadData.AsInt64() ).ToWin32FileTimeUtc(); + return DateTime.FromBinary( unpacker.LastReadData.DeserializeAsInt64() ).ToWin32FileTimeUtc(); } #if FEATURE_TAP diff --git a/src/MsgPack/Serialization/DefaultSerializers/NullableMessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/NullableMessagePackSerializer`1.cs index 64a26e43b..212d5f796 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/NullableMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/NullableMessagePackSerializer`1.cs @@ -24,11 +24,11 @@ using System; #if DEBUG -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // DEBUG #if FEATURE_TAP using System.Threading; @@ -45,13 +45,10 @@ internal class NullableMessagePackSerializer : MessagePackSerializer private readonly MessagePackSerializer _valueSerializer; public NullableMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) - { - this._valueSerializer = ownerContext.GetSerializer(); - } + : this( ownerContext, ownerContext.GetSerializer() ) { } public NullableMessagePackSerializer( SerializationContext ownerContext, MessagePackSerializer valueSerializer ) - : base( ownerContext ) + : base( ownerContext, valueSerializer.Capabilities ) { this._valueSerializer = valueSerializer; } @@ -106,13 +103,13 @@ internal class NullableMessagePackSerializer : NonGenericMessagePackSerializer private readonly MessagePackSerializer _valueSerializer; public NullableMessagePackSerializer( SerializationContext ownerContext, Type nullableType, Type underlyingType ) - : base( ownerContext, nullableType ) + : base( ownerContext, nullableType, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._valueSerializer = ownerContext.GetSerializer( underlyingType ); } public NullableMessagePackSerializer( SerializationContext ownerContext, Type nullableType, MessagePackSerializer valueSerializer ) - : base( ownerContext, nullableType ) + : base( ownerContext, nullableType, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._valueSerializer = valueSerializer; } diff --git a/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs b/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs index 97a5bbedf..8c5e603f3 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.cs @@ -43,7 +43,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Numerics_Vector2MessagePackSerializer : MessagePackSerializer { public System_Numerics_Vector2MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Vector2 objectTree ) @@ -61,7 +61,7 @@ protected internal override Vector2 UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Vector2 ), 2 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 2 ) { @@ -131,7 +131,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker un internal sealed class System_Numerics_Vector3MessagePackSerializer : MessagePackSerializer { public System_Numerics_Vector3MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Vector3 objectTree ) @@ -150,7 +150,7 @@ protected internal override Vector3 UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Vector3 ), 3 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 3 ) { @@ -233,7 +233,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker un internal sealed class System_Numerics_Vector4MessagePackSerializer : MessagePackSerializer { public System_Numerics_Vector4MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Vector4 objectTree ) @@ -253,7 +253,7 @@ protected internal override Vector4 UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Vector4 ), 4 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 4 ) { @@ -349,7 +349,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker un internal sealed class System_Numerics_PlaneMessagePackSerializer : MessagePackSerializer { public System_Numerics_PlaneMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Plane objectTree ) @@ -369,7 +369,7 @@ protected internal override Plane UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Plane ), 4 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 4 ) { @@ -465,7 +465,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker unpa internal sealed class System_Numerics_QuaternionMessagePackSerializer : MessagePackSerializer { public System_Numerics_QuaternionMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Quaternion objectTree ) @@ -485,7 +485,7 @@ protected internal override Quaternion UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Quaternion ), 4 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 4 ) { @@ -581,7 +581,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker internal sealed class System_Numerics_Matrix3x2MessagePackSerializer : MessagePackSerializer { public System_Numerics_Matrix3x2MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Matrix3x2 objectTree ) @@ -603,7 +603,7 @@ protected internal override Matrix3x2 UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Matrix3x2 ), 6 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 6 ) { @@ -725,7 +725,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker internal sealed class System_Numerics_Matrix4x4MessagePackSerializer : MessagePackSerializer { public System_Numerics_Matrix4x4MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, Matrix4x4 objectTree ) @@ -757,7 +757,7 @@ protected internal override Matrix4x4 UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Matrix4x4 ), 16 ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 16 ) { diff --git a/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.tt b/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.tt index a4b9c4cac..a4ff39306 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.tt +++ b/src/MsgPack/Serialization/DefaultSerializers/SimdTypeSerializers.tt @@ -68,7 +68,7 @@ foreach( var type in types ) internal sealed class System_Numerics_<#= type.Name #>MessagePackSerializer : MessagePackSerializer<#= typeArgument #> { public System_Numerics_<#= type.Name #>MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, <#= type.Name #> objectTree ) @@ -92,7 +92,7 @@ foreach( var type in types ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( <#= type.Name #> ), <#= type.Fields.Length #> ); } - var length = unpacker.LastReadData.AsInt64(); + var length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != <#= type.Fields.Length #> ) { diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_ArraySegment_1MessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/System_ArraySegment_1MessagePackSerializer`1.cs index 1dc894a12..b47bce5da 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_ArraySegment_1MessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_ArraySegment_1MessagePackSerializer`1.cs @@ -135,7 +135,7 @@ private static Func, CancellationToken, Task< private readonly MessagePackSerializer _itemSerializer; public System_ArraySegment_1MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._itemSerializer = ownerContext.GetSerializer(); } diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_ByteArrayMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_ByteArrayMessagePackSerializer.cs index 4ec81e27f..acdffe1e4 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_ByteArrayMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_ByteArrayMessagePackSerializer.cs @@ -30,15 +30,15 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_ByteArrayMessagePackSerializer : MessagePackSerializer { public System_ByteArrayMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, byte[] value ) { packer.PackBinary( value ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override byte[] UnpackFromCore( Unpacker unpacker ) { var result = unpacker.LastReadData; diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_CharArrayMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_CharArrayMessagePackSerializer.cs index b8c2a1822..07ce5fe46 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_CharArrayMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_CharArrayMessagePackSerializer.cs @@ -30,9 +30,9 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_CharArrayMessagePackSerializer : MessagePackSerializer { public System_CharArrayMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, char[] value ) { if ( value == null ) @@ -45,7 +45,7 @@ protected internal override void PackToCore( Packer packer, char[] value ) } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override char[] UnpackFromCore( Unpacker unpacker ) { var result = unpacker.LastReadData; diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_DictionaryEntryMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_DictionaryEntryMessagePackSerializer.cs index 278f378b7..efa5df1c7 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_DictionaryEntryMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_DictionaryEntryMessagePackSerializer.cs @@ -32,9 +32,9 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Collections_DictionaryEntryMessagePackSerializer : MessagePackSerializer { public System_Collections_DictionaryEntryMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, DictionaryEntry objectTree ) { packer.PackArrayHeader( 2 ); @@ -57,7 +57,7 @@ private static MessagePackObject EnsureMessagePackObject( object obj ) return ( MessagePackObject )obj; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override DictionaryEntry UnpackFromCore( Unpacker unpacker ) { if ( unpacker.IsArrayHeader ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs index a9b9f65c2..d8a630619 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Dictionary_2MessagePackSerializer`2.cs @@ -53,7 +53,7 @@ internal class System_Collections_Generic_Dictionary_2MessagePackSerializer _valueSerializer; public System_Collections_Generic_Dictionary_2MessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._keySerializer = ownerContext.GetSerializer( keysSchema ); this._valueSerializer = ownerContext.GetSerializer( valuesSchema ); @@ -64,7 +64,7 @@ protected internal override void PackToCore( Packer packer, Dictionary UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsMapHeader ) @@ -78,7 +78,7 @@ protected internal override Dictionary UnpackFromCore( Unpacker un return collection; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, Dictionary collection ) { if ( !unpacker.IsMapHeader ) @@ -103,12 +103,12 @@ private void UnpackToCore( Unpacker unpacker, Dictionary collectio { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { - key = this._keySerializer.UnpackFromCore( subTreeUnpacker ); + key = this._keySerializer.UnpackFrom( subTreeUnpacker ); } } else { - key = this._keySerializer.UnpackFromCore( unpacker ); + key = this._keySerializer.UnpackFrom( unpacker ); } if ( !unpacker.Read() ) @@ -120,12 +120,12 @@ private void UnpackToCore( Unpacker unpacker, Dictionary collectio { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { - collection.Add( key, this._valueSerializer.UnpackFromCore( subTreeUnpacker ) ); + collection.Add( key, this._valueSerializer.UnpackFrom( subTreeUnpacker ) ); } } else { - collection.Add( key, this._valueSerializer.UnpackFromCore( unpacker ) ); + collection.Add( key, this._valueSerializer.UnpackFrom( unpacker ) ); } } } @@ -180,12 +180,12 @@ private async Task UnpackToAsyncCore( Unpacker unpacker, Dictionary _valueSerializer; public System_Collections_Generic_KeyValuePair_2MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { this._keySerializer = ownerContext.GetSerializer(); this._valueSerializer = ownerContext.GetSerializer(); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, KeyValuePair objectTree ) { packer.PackArrayHeader( 2 ); @@ -53,7 +53,7 @@ protected internal override void PackToCore( Packer packer, KeyValuePair UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.Read() ) @@ -61,14 +61,14 @@ protected internal override KeyValuePair UnpackFromCore( Unpacker SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - var key = unpacker.LastReadData.IsNil ? default( TKey ) : this._keySerializer.UnpackFromCore( unpacker ); + var key = unpacker.LastReadData.IsNil ? default( TKey ) : this._keySerializer.UnpackFrom( unpacker ); if ( !unpacker.Read() ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - var value = unpacker.LastReadData.IsNil ? default( TValue ) : this._valueSerializer.UnpackFromCore( unpacker ); + var value = unpacker.LastReadData.IsNil ? default( TValue ) : this._valueSerializer.UnpackFrom( unpacker ); return new KeyValuePair( key, value ); } @@ -89,14 +89,14 @@ protected internal override async Task> UnpackFromAsy SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - var key = unpacker.LastReadData.IsNil ? default( TKey ) : await this._keySerializer.UnpackFromAsyncCore( unpacker, cancellationToken ).ConfigureAwait( false ); + var key = unpacker.LastReadData.IsNil ? default( TKey ) : await this._keySerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ); if ( !await unpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } - var value = unpacker.LastReadData.IsNil ? default( TValue ) : await this._valueSerializer.UnpackFromAsyncCore( unpacker, cancellationToken ).ConfigureAwait( false ); + var value = unpacker.LastReadData.IsNil ? default( TValue ) : await this._valueSerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ); return new KeyValuePair( key, value ); } diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs index bf82d06e8..116251a31 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer.cs @@ -33,10 +33,10 @@ namespace MsgPack.Serialization.DefaultSerializers internal class System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer : MessagePackSerializer>, ICollectionInstanceFactory { public System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, List objectTree ) { packer.PackArrayHeader( objectTree.Count ); @@ -46,7 +46,7 @@ protected internal override void PackToCore( Packer packer, List UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -60,7 +60,7 @@ protected internal override List UnpackFromCore( Unpacker unp return collection; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, List collection ) { if ( !unpacker.IsArrayHeader ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_List_1MessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_List_1MessagePackSerializer`1.cs index 739ad2b72..b7ebcb9c5 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_List_1MessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_List_1MessagePackSerializer`1.cs @@ -51,7 +51,7 @@ internal class System_Collections_Generic_List_1MessagePackSerializer : Messa private readonly MessagePackSerializer _itemSerializer; public System_Collections_Generic_List_1MessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer( itemsSchema ); } @@ -61,7 +61,7 @@ protected internal override void PackToCore( Packer packer, List objectTree ) PackerUnpackerExtensions.PackCollectionCore( packer, objectTree, this._itemSerializer ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override List UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -75,7 +75,7 @@ protected internal override List UnpackFromCore( Unpacker unpacker ) return collection; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, List collection ) { if ( !unpacker.IsArrayHeader ) @@ -99,12 +99,12 @@ private void UnpackToCore( Unpacker unpacker, List collection, int count ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { - collection.Add( this._itemSerializer.UnpackFromCore( subTreeUnpacker ) ); + collection.Add( this._itemSerializer.UnpackFrom( subTreeUnpacker ) ); } } else { - collection.Add( this._itemSerializer.UnpackFromCore( unpacker ) ); + collection.Add( this._itemSerializer.UnpackFrom( unpacker ) ); } } } @@ -158,12 +158,12 @@ private async Task UnpackToAsyncCore( Unpacker unpacker, List collection, int { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { - collection.Add( await this._itemSerializer.UnpackFromAsyncCore( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ) ); + collection.Add( await this._itemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ) ); } } else { - collection.Add( await this._itemSerializer.UnpackFromAsyncCore( unpacker, cancellationToken ).ConfigureAwait( false ) ); + collection.Add( await this._itemSerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ) ); } } } @@ -179,7 +179,7 @@ internal class System_Collections_Generic_List_1MessagePackSerializer : NonGener private readonly MethodInfo _add; public System_Collections_Generic_List_1MessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits traits, PolymorphismSchema itemsSchema ) - : base( ownerContext, targetType ) + : base( ownerContext, targetType, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer( traits.ElementType, itemsSchema ); this._constructor = targetType.GetConstructor( ConstructorWithCapacityParameterTypes ); @@ -202,7 +202,7 @@ protected internal override void PackToCore( Packer packer, object objectTree ) } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override object UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -216,7 +216,7 @@ protected internal override object UnpackFromCore( Unpacker unpacker ) return collection; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsArrayHeader ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Queue_1MessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Queue_1MessagePackSerializer`1.cs index 57e5a5780..7ed8c30a9 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Queue_1MessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Queue_1MessagePackSerializer`1.cs @@ -36,13 +36,13 @@ internal sealed class System_Collections_Generic_Queue_1MessagePackSerializer _itemSerializer; public System_Collections_Generic_Queue_1MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer(); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Queue objectTree ) { packer.PackArrayHeader( objectTree.Count ); @@ -52,7 +52,7 @@ protected internal override void PackToCore( Packer packer, Queue objectT } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Queue UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -66,8 +66,8 @@ protected internal override Queue UnpackFromCore( Unpacker unpacker ) return queue; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, Queue collection ) { var itemsCount = UnpackHelpers.GetItemsCount( unpacker ); diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Stack_1MessagePackSerializer`1.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Stack_1MessagePackSerializer`1.cs index a22c1b82e..91867bd8d 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Stack_1MessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Generic_Stack_1MessagePackSerializer`1.cs @@ -36,13 +36,13 @@ internal sealed class System_Collections_Generic_Stack_1MessagePackSerializer _itemSerializer; public System_Collections_Generic_Stack_1MessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer(); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Stack objectTree ) { packer.PackArrayHeader( objectTree.Count ); @@ -52,7 +52,7 @@ protected internal override void PackToCore( Packer packer, Stack objectT } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Stack UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -63,8 +63,8 @@ protected internal override Stack UnpackFromCore( Unpacker unpacker ) return new Stack( this.UnpackItemsInReverseOrder( unpacker, UnpackHelpers.GetItemsCount( unpacker ) ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, Stack collection ) { if ( !unpacker.IsArrayHeader ) @@ -111,7 +111,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, Stack, ICollectionInstanceFactory { public System_Collections_QueueMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Queue objectTree ) { packer.PackArrayHeader( objectTree.Count ); @@ -47,7 +47,7 @@ protected internal override void PackToCore( Packer packer, Queue objectTree ) } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Queue UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -61,8 +61,8 @@ protected internal override Queue UnpackFromCore( Unpacker unpacker ) return queue; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, Queue collection ) { var itemsCount = UnpackHelpers.GetItemsCount( unpacker ); diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs index b4a587332..26805e409 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_Specialized_NameValueCollectionMessagePackSerializer.cs @@ -35,10 +35,10 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Collections_Specialized_NameValueCollectionMessagePackSerializer : MessagePackSerializer, ICollectionInstanceFactory { public System_Collections_Specialized_NameValueCollectionMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, NameValueCollection objectTree ) { if ( objectTree == null ) @@ -73,7 +73,7 @@ protected internal override void PackToCore( Packer packer, NameValueCollection } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override NameValueCollection UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsMapHeader ) @@ -87,7 +87,7 @@ protected internal override NameValueCollection UnpackFromCore( Unpacker unpacke return collection; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, NameValueCollection collection ) { if ( !unpacker.IsMapHeader ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_StackMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_StackMessagePackSerializer.cs index 2acec9e73..762f0cf17 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Collections_StackMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Collections_StackMessagePackSerializer.cs @@ -34,10 +34,10 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Collections_StackMessagePackSerializer : MessagePackSerializer, ICollectionInstanceFactory { public System_Collections_StackMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Stack objectTree ) { packer.PackArrayHeader( objectTree.Count ); @@ -47,7 +47,7 @@ protected internal override void PackToCore( Packer packer, Stack objectTree ) } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Stack UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -58,8 +58,8 @@ protected internal override Stack UnpackFromCore( Unpacker unpacker ) return new Stack( UnpackItemsInReverseOrder( unpacker, UnpackHelpers.GetItemsCount( unpacker ) ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, Stack collection ) { if ( !unpacker.IsArrayHeader ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_DBNullMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_DBNullMessagePackSerializer.cs index ea384cd50..e5cf3a5ee 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_DBNullMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_DBNullMessagePackSerializer.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -22,12 +22,14 @@ #define UNITY #endif +#if !NETSTANDARD1_1 + using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Runtime.Serialization; #if FEATURE_TAP using System.Threading; @@ -40,7 +42,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal class System_DBNullMessagePackSerializer : MessagePackSerializer { public System_DBNullMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) {} + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) {} [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, DBNull objectTree ) @@ -80,4 +82,5 @@ protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, #endif // FEATURE_TAP } -} \ No newline at end of file +} +#endif // !NETSTANDARD1_1 diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Globalization_CultureInfoMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Globalization_CultureInfoMessagePackSerializer.cs index 423a07780..20b1e3876 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Globalization_CultureInfoMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Globalization_CultureInfoMessagePackSerializer.cs @@ -31,7 +31,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Globalization_CultureInfoMessagePackSerializer : MessagePackSerializer { public System_Globalization_CultureInfoMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -40,13 +40,13 @@ protected internal override void PackToCore( Packer packer, CultureInfo objectTr packer.PackString( objectTree.Name ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override CultureInfo UnpackFromCore( Unpacker unpacker ) { #if SILVERLIGHT || NETSTANDARD1_1 || NETSTANDARD1_3 - return new CultureInfo( unpacker.LastReadData.AsString() ); + return new CultureInfo( unpacker.LastReadData.DeserializeAsString() ); #else - return CultureInfo.GetCultureInfo( unpacker.LastReadData.AsString() ); + return CultureInfo.GetCultureInfo( unpacker.LastReadData.DeserializeAsString() ); #endif // SILVERLIGHT || NETSTANDARD1_1 || NETSTANDARD1_3 } diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Numerics_ComplexMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Numerics_ComplexMessagePackSerializer.cs index e65ed6f17..9ee0d20f5 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Numerics_ComplexMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Numerics_ComplexMessagePackSerializer.cs @@ -35,9 +35,9 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Numerics_ComplexMessagePackSerializer : MessagePackSerializer { public System_Numerics_ComplexMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Complex objectTree ) { packer.PackArrayHeader( 2 ); @@ -45,9 +45,20 @@ protected internal override void PackToCore( Packer packer, Complex objectTree ) packer.Pack( objectTree.Imaginary ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Complex UnpackFromCore( Unpacker unpacker ) { + if ( !unpacker.IsArrayHeader ) + { + SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Complex ), 2 ); + } + + long length = UnpackHelpers.GetItemsCount( unpacker ); + if ( length != 2 ) + { + SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Complex ), 2 ); + } + double real, imaginary; if ( !unpacker.ReadDouble( out real ) ) { diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_ObjectMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_ObjectMessagePackSerializer.cs index 2f76cb8c8..459087133 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_ObjectMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_ObjectMessagePackSerializer.cs @@ -31,7 +31,7 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_ObjectMessagePackSerializer : MessagePackSerializer { public System_ObjectMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )] @@ -46,7 +46,7 @@ protected internal override void PackToCore( Packer packer, object value ) packer.PackObject( value, this.OwnerContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override object UnpackFromCore( Unpacker unpacker ) { if ( unpacker.IsArrayHeader ) diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs index 38583473e..581484270 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer.cs @@ -31,29 +31,29 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer : MessagePackSerializer { public System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer(SerializationContext ownerContext) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, HashAlgorithmName objectTree ) { packer.PackString( objectTree.Name ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override HashAlgorithmName UnpackFromCore( Unpacker unpacker ) { - return new HashAlgorithmName( unpacker.LastReadData.AsString() ); + return new HashAlgorithmName( unpacker.LastReadData.DeserializeAsString() ); } #if FEATURE_TAP - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Task PackToAsyncCore( Packer packer, HashAlgorithmName objectTree, CancellationToken cancellationToken ) { return packer.PackStringAsync( objectTree.Name, cancellationToken ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Transfers all catched exceptions." )] protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) { diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_StringMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_StringMessagePackSerializer.cs index 847817660..f8f731695 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_StringMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_StringMessagePackSerializer.cs @@ -30,15 +30,15 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_StringMessagePackSerializer : MessagePackSerializer { public System_StringMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, string value ) { packer.PackString( value ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override string UnpackFromCore( Unpacker unpacker ) { var result = unpacker.LastReadData; @@ -47,14 +47,14 @@ protected internal override string UnpackFromCore( Unpacker unpacker ) #if FEATURE_TAP - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Task PackToAsyncCore( Packer packer, string objectTree, CancellationToken cancellationToken ) { return packer.PackStringAsync( objectTree, cancellationToken ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Transfers all catched exceptions." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) { var tcs = new TaskCompletionSource(); diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_Text_StringBuilderMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_Text_StringBuilderMessagePackSerializer.cs index adb4df40e..279e1be36 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_Text_StringBuilderMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_Text_StringBuilderMessagePackSerializer.cs @@ -31,17 +31,17 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_Text_StringBuilderMessagePackSerializer : MessagePackSerializer { public System_Text_StringBuilderMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, StringBuilder value ) { // NOTE: More efficient? packer.PackString( value.ToString() ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override StringBuilder UnpackFromCore( Unpacker unpacker ) { // NOTE: More efficient? @@ -49,6 +49,18 @@ protected internal override StringBuilder UnpackFromCore( Unpacker unpacker ) return result.IsNil ? null : new StringBuilder( result.DeserializeAsString() ); } + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally." )] + protected internal override void UnpackToCore( Unpacker unpacker, StringBuilder collection ) + { + // NOTE: More efficient? + var result = unpacker.LastReadData; + if ( !result.IsNil ) + { + collection.Append( result.DeserializeAsString() ); + } + } + #if FEATURE_TAP protected internal override Task PackToAsyncCore( Packer packer, StringBuilder objectTree, CancellationToken cancellationToken ) @@ -73,6 +85,31 @@ protected internal override Task UnpackFromAsyncCore( Unpacker un return tcs.Task; } + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Transferring exception." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally." )] + protected internal override Task UnpackToAsyncCore( Unpacker unpacker, StringBuilder collection, CancellationToken cancellationToken ) + { + // NOTE: More efficient? + var tcs = new TaskCompletionSource(); + try + { + var result = unpacker.LastReadData; + if ( !result.IsNil ) + { + collection.Append( result.DeserializeAsString() ); + } + + tcs.SetResult( null ); + } + catch ( Exception ex ) + { + tcs.SetException( ex ); + } + + return tcs.Task; + } + #endif // FEATURE_TAP } } diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_UriMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_UriMessagePackSerializer.cs index 809966eb5..08fd7859d 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_UriMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_UriMessagePackSerializer.cs @@ -30,16 +30,16 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_UriMessagePackSerializer : MessagePackSerializer { public System_UriMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Uri objectTree ) { packer.PackString( objectTree.ToString() ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Uri UnpackFromCore( Unpacker unpacker ) { return new Uri( unpacker.LastReadData.DeserializeAsString() ); diff --git a/src/MsgPack/Serialization/DefaultSerializers/System_VersionMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/System_VersionMessagePackSerializer.cs index a290f5cae..14e1c45e4 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/System_VersionMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/System_VersionMessagePackSerializer.cs @@ -30,10 +30,10 @@ namespace MsgPack.Serialization.DefaultSerializers internal sealed class System_VersionMessagePackSerializer : MessagePackSerializer { public System_VersionMessagePackSerializer( SerializationContext ownerContext ) - : base( ownerContext ) { } + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected internal override void PackToCore( Packer packer, Version objectTree ) { packer.PackArrayHeader( 4 ); @@ -43,7 +43,7 @@ protected internal override void PackToCore( Packer packer, Version objectTree ) packer.Pack( objectTree.Revision ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override Version UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -51,7 +51,7 @@ protected internal override Version UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Version ), 4 ); } - long length = unpacker.LastReadData.AsInt64(); + long length = UnpackHelpers.GetItemsCount( unpacker ); if ( length != 4 ) { SerializationExceptions.ThrowInvalidArrayItemsCount( unpacker, typeof( Version ), 4 ); @@ -78,6 +78,15 @@ protected internal override Version UnpackFromCore( Unpacker unpacker ) SerializationExceptions.ThrowMissingItem( 3, unpacker ); } + if (build < 0 && revision < 0) + { + return new Version(major, minor); + } + else if (revision < 0) + { + return new Version(major, minor, build); + } + return new Version( major, minor, build, revision ); } @@ -129,6 +138,15 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker un SerializationExceptions.ThrowMissingItem( 3, unpacker ); } + if (build.Value < 0 && revision.Value < 0) + { + return new Version(major.Value, minor.Value); + } + else if (revision.Value < 0) + { + return new Version(major.Value, minor.Value, build.Value); + } + return new Version( major.Value, minor.Value, build.Value, revision.Value ); } diff --git a/src/MsgPack/Serialization/DefaultSerializers/TimestampDateTimeMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/TimestampDateTimeMessagePackSerializer.cs new file mode 100644 index 000000000..ada00df8a --- /dev/null +++ b/src/MsgPack/Serialization/DefaultSerializers/TimestampDateTimeMessagePackSerializer.cs @@ -0,0 +1,75 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization.DefaultSerializers +{ + /// + /// serializer using timestamp representation. + /// + internal class TimestampDateTimeMessagePackSerializer : MessagePackSerializer + { + public TimestampDateTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override void PackToCore( Packer packer, DateTime objectTree ) + { + packer.Pack( Timestamp.FromDateTime( objectTree ).Encode() ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override DateTime UnpackFromCore( Unpacker unpacker ) + { + return Timestamp.Decode( unpacker.LastReadData.DeserializeAsMessagePackExtendedTypeObject() ).ToDateTime(); + } + +#if FEATURE_TAP + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override Task PackToAsyncCore( Packer packer, DateTime objectTree, CancellationToken cancellationToken ) + { + return packer.PackAsync( Timestamp.FromDateTime( objectTree ).Encode(), cancellationToken ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Transfers all catched exceptions." )] + protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) + { + var tcs = new TaskCompletionSource(); + try + { + tcs.SetResult( this.UnpackFromCore( unpacker ) ); + } + catch ( Exception ex ) + { + tcs.SetException( ex ); + } + + return tcs.Task; + } + +#endif // FEATURE_TAP + + } +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/TimestampFileTimeMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/TimestampFileTimeMessagePackSerializer.cs new file mode 100644 index 000000000..d538f1514 --- /dev/null +++ b/src/MsgPack/Serialization/DefaultSerializers/TimestampFileTimeMessagePackSerializer.cs @@ -0,0 +1,75 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Runtime.InteropServices.ComTypes; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization.DefaultSerializers +{ + /// + /// serializer using timestamp representation. + /// + internal sealed class TimestampFileTimeMessagePackSerializer : MessagePackSerializer + { + public TimestampFileTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override void PackToCore( Packer packer, FILETIME objectTree ) + { + packer.Pack( Timestamp.FromDateTime( objectTree.ToDateTime() ).Encode() ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override FILETIME UnpackFromCore( Unpacker unpacker ) + { + return Timestamp.Decode( unpacker.LastReadData.DeserializeAsMessagePackExtendedTypeObject() ).ToDateTime().ToWin32FileTimeUtc(); + } + +#if FEATURE_TAP + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override Task PackToAsyncCore( Packer packer, FILETIME objectTree, CancellationToken cancellationToken ) + { + return packer.PackAsync( Timestamp.FromDateTime( objectTree.ToDateTime() ).Encode(), cancellationToken ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Transfers all catched exceptions." )] + protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) + { + var tcs = new TaskCompletionSource(); + try + { + tcs.SetResult( this.UnpackFromCore( unpacker ) ); + } + catch ( Exception ex ) + { + tcs.SetException( ex ); + } + + return tcs.Task; + } + +#endif // FEATURE_TAP + } +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/TimestampMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/TimestampMessagePackSerializer.cs new file mode 100644 index 000000000..37f77b87f --- /dev/null +++ b/src/MsgPack/Serialization/DefaultSerializers/TimestampMessagePackSerializer.cs @@ -0,0 +1,128 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization.DefaultSerializers +{ + /// + /// serializer using Unix Epoc or native representation. + /// + internal class TimestampMessagePackSerializer : MessagePackSerializer + { + private readonly DateTimeConversionMethod _conversion; + + public TimestampMessagePackSerializer( SerializationContext ownerContext, DateTimeConversionMethod conversion ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) + { + this._conversion = conversion; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override void PackToCore( Packer packer, Timestamp objectTree ) + { + if ( this._conversion == DateTimeConversionMethod.Timestamp ) + { + packer.Pack( objectTree.Encode() ); + } + else if ( this._conversion == DateTimeConversionMethod.Native ) + { + packer.Pack( objectTree.ToDateTime().ToBinary() ); + } + else + { +#if DEBUG + Contract.Assert( this._conversion == DateTimeConversionMethod.UnixEpoc ); +#endif // DEBUG + packer.Pack( MessagePackConvert.FromDateTimeOffset( objectTree.ToDateTimeOffset() ) ); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] + protected internal override Timestamp UnpackFromCore( Unpacker unpacker ) + { + if ( unpacker.LastReadData.IsTypeOf().GetValueOrDefault() ) + { + return Timestamp.Decode( unpacker.LastReadData.AsMessagePackExtendedTypeObject() ); + } + else if ( this._conversion == DateTimeConversionMethod.UnixEpoc ) + { + return MessagePackConvert.ToDateTimeOffset( unpacker.LastReadData.DeserializeAsInt64() ); + } + else + { + return new DateTimeOffset( DateTime.FromBinary( unpacker.LastReadData.DeserializeAsInt64() ), TimeSpan.Zero ); + } + } + +#if FEATURE_TAP + + protected internal override async Task PackToAsyncCore( Packer packer, Timestamp objectTree, CancellationToken cancellationToken ) + { + if ( this._conversion == DateTimeConversionMethod.Timestamp ) + { + await packer.PackAsync( objectTree.Encode(), cancellationToken ).ConfigureAwait( false ); + } + else if ( this._conversion == DateTimeConversionMethod.Native ) + { + await packer.PackAsync( objectTree.ToDateTime().ToBinary(), cancellationToken ).ConfigureAwait( false ); + } + else + { +#if DEBUG + Contract.Assert( this._conversion == DateTimeConversionMethod.UnixEpoc ); +#endif // DEBUG + await packer.PackAsync( MessagePackConvert.FromDateTimeOffset( objectTree.ToDateTimeOffset() ), cancellationToken ).ConfigureAwait( false ); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Transfers all catched exceptions." )] + protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) + { + var tcs = new TaskCompletionSource(); + try + { + tcs.SetResult( this.UnpackFromCore( unpacker ) ); + } + catch ( Exception ex ) + { + tcs.SetException( ex ); + } + + return tcs.Task; + } + +#endif // FEATURE_TAP + + } +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/TimestampMessagePackSerializerProvider.cs b/src/MsgPack/Serialization/DefaultSerializers/TimestampMessagePackSerializerProvider.cs new file mode 100644 index 000000000..13fa60997 --- /dev/null +++ b/src/MsgPack/Serialization/DefaultSerializers/TimestampMessagePackSerializerProvider.cs @@ -0,0 +1,116 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Globalization; + +namespace MsgPack.Serialization.DefaultSerializers +{ + /// + /// Provides runtime selection ability for serialization. + /// + internal class TimestampMessagePackSerializerProvider : MessagePackSerializerProvider + { + private readonly MessagePackSerializer _unixEpoc; + private readonly MessagePackSerializer _native; + private readonly MessagePackSerializer _timestamp; + + public TimestampMessagePackSerializerProvider( SerializationContext context, bool isNullable ) + { + if ( isNullable ) + { +#if !UNITY + this._unixEpoc = + new NullableMessagePackSerializer( context, new TimestampMessagePackSerializer( context, DateTimeConversionMethod.UnixEpoc ) ); + this._native = + new NullableMessagePackSerializer( context, new TimestampMessagePackSerializer( context, DateTimeConversionMethod.Native ) ); + this._timestamp = + new NullableMessagePackSerializer( context, new TimestampMessagePackSerializer( context, DateTimeConversionMethod.Timestamp ) ); +#else + this._unixEpoc = + new NullableMessagePackSerializer( context, typeof( Timestamp? ), new TimestampMessagePackSerializer( context, DateTimeConversionMethod.UnixEpoc ) ); + this._native = + new NullableMessagePackSerializer( context, typeof( Timestamp? ), new TimestampMessagePackSerializer( context, DateTimeConversionMethod.Native ) ); + this._timestamp = + new NullableMessagePackSerializer( context, typeof( Timestamp? ), new TimestampMessagePackSerializer( context, DateTimeConversionMethod.Timestamp ) ); +#endif // !UNITY + } + else + { + this._unixEpoc = new TimestampMessagePackSerializer( context, DateTimeConversionMethod.UnixEpoc ); + this._native = new TimestampMessagePackSerializer( context, DateTimeConversionMethod.Native ); + this._timestamp = new TimestampMessagePackSerializer( context, DateTimeConversionMethod.Timestamp ); + } + } + + public override object Get( SerializationContext context, object providerParameter ) + { + if ( providerParameter is DateTimeConversionMethod ) + { + switch ( ( DateTimeConversionMethod )providerParameter ) + { + case DateTimeConversionMethod.Native: + { + return this._native; + } + case DateTimeConversionMethod.UnixEpoc: + { + return this._unixEpoc; + } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } + } + } + + switch ( context.DefaultDateTimeConversionMethod ) + { + case DateTimeConversionMethod.Native: + { + return this._native; + } + case DateTimeConversionMethod.UnixEpoc: + { + return this._unixEpoc; + } + case DateTimeConversionMethod.Timestamp: + { + return this._timestamp; + } + default: + { + throw new NotSupportedException( + String.Format( + CultureInfo.CurrentCulture, + "Unknown {0} value '{1:G}'({1:D})", + typeof( DateTimeConversionMethod ), + context.DefaultDateTimeConversionMethod + ) + ); + } + } + } + } +} diff --git a/src/MsgPack/Serialization/DefaultSerializers/UnixEpocDateTimeMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/UnixEpocDateTimeMessagePackSerializer.cs index 5cdd539ce..0086f3e7f 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/UnixEpocDateTimeMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/UnixEpocDateTimeMessagePackSerializer.cs @@ -31,7 +31,7 @@ namespace MsgPack.Serialization.DefaultSerializers /// internal class UnixEpocDateTimeMessagePackSerializer : MessagePackSerializer { - public UnixEpocDateTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext ) { } + public UnixEpocDateTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, DateTime objectTree ) @@ -42,7 +42,7 @@ protected internal override void PackToCore( Packer packer, DateTime objectTree [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override DateTime UnpackFromCore( Unpacker unpacker ) { - return MessagePackConvert.ToDateTime( unpacker.LastReadData.AsInt64() ); + return MessagePackConvert.ToDateTime( unpacker.LastReadData.DeserializeAsInt64() ); } #if FEATURE_TAP diff --git a/src/MsgPack/Serialization/DefaultSerializers/UnixEpocFileTimeMessagePackSerializer.cs b/src/MsgPack/Serialization/DefaultSerializers/UnixEpocFileTimeMessagePackSerializer.cs index a478e0c73..c698d0714 100644 --- a/src/MsgPack/Serialization/DefaultSerializers/UnixEpocFileTimeMessagePackSerializer.cs +++ b/src/MsgPack/Serialization/DefaultSerializers/UnixEpocFileTimeMessagePackSerializer.cs @@ -32,7 +32,7 @@ namespace MsgPack.Serialization.DefaultSerializers /// internal sealed class UnixEpocFileTimeMessagePackSerializer : MessagePackSerializer { - public UnixEpocFileTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext ) { } + public UnixEpocFileTimeMessagePackSerializer( SerializationContext ownerContext ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override void PackToCore( Packer packer, FILETIME objectTree ) @@ -43,7 +43,7 @@ protected internal override void PackToCore( Packer packer, FILETIME objectTree [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override FILETIME UnpackFromCore( Unpacker unpacker ) { - return MessagePackConvert.ToDateTime( unpacker.LastReadData.AsInt64() ).ToWin32FileTimeUtc(); + return MessagePackConvert.ToDateTime( unpacker.LastReadData.DeserializeAsInt64() ).ToWin32FileTimeUtc(); } #if FEATURE_TAP diff --git a/src/MsgPack/Serialization/DependentAssemblyManager.cs b/src/MsgPack/Serialization/DependentAssemblyManager.cs new file mode 100644 index 000000000..43e382f99 --- /dev/null +++ b/src/MsgPack/Serialization/DependentAssemblyManager.cs @@ -0,0 +1,234 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if DEBUG +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +#if FEATURE_CONCURRENT +using System.Collections.Concurrent; +using System.Threading; +#endif // FEATURE_CONCURRENT + +namespace MsgPack.Serialization +{ + internal abstract class DependentAssemblyManager + { +#if FEATURE_CONCURRENT + + private static DependentAssemblyManager _default = new NullDependentAssemblyManager(); + + public static DependentAssemblyManager Default + { + get { return Volatile.Read( ref _default ); } + set { Volatile.Write( ref _default, value ); } + } + + private readonly ConcurrentDictionary _runtimeAssemblies; + + private readonly ConcurrentDictionary _compiledCodeDomSerializerAssemblies; + +#else + + private static volatile DependentAssemblyManager _default = new NullDependentAssemblyManager(); + + public static DependentAssemblyManager Default + { + get { return _default; } + set { _default = value; } + } + + private readonly object _syncRoot; + + private readonly Dictionary _runtimeAssemblies; + + private readonly Dictionary _compiledCodeDomSerializerAssemblies; + +#endif // FEATURE_CONCURRENT + + public IEnumerable CodeSerializerDependentAssemblies + { + get + { + // ReSharper disable JoinDeclarationAndInitializer + IEnumerable runtimeAssemblies; + IEnumerable compiledAssemblies; + // ReSharper restore JoinDeclarationAndInitializer +#if !FEATURE_CONCURRENT + lock ( this._syncRoot ) + { + runtimeAssemblies = this._runtimeAssemblies.Keys.ToArray(); + compiledAssemblies = this._compiledCodeDomSerializerAssemblies.Select( kv => kv.Value as object ?? kv.Key ).ToArray(); + } +#else + runtimeAssemblies = this._runtimeAssemblies.Keys; + compiledAssemblies = this._compiledCodeDomSerializerAssemblies.Select( kv => kv.Value as object ?? kv.Key ); +#endif // !FEATURE_CONCURRENT + + // FCL dependencies and msgpack core libs + foreach ( var runtimeAssembly in runtimeAssemblies ) + { + yield return runtimeAssembly; + } + + // dependents + foreach ( var compiledAssembly in compiledAssemblies ) + { + yield return compiledAssembly; + } + } + } + +#if FEATURE_CONCURRENT + + private string _dumpDirectory; + + public string DumpDirectory + { + get { return Volatile.Read( ref this._dumpDirectory ); } + set { Volatile.Write( ref this._dumpDirectory, value ); } + } + +#else + + private volatile string _dumpDirectory; + + public string DumpDirectory + { + get { return this._dumpDirectory; } + set { this._dumpDirectory = value; } + } + +#endif // FEATURE_CONCURRENT + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "It is by design for internal utilities." )] + protected DependentAssemblyManager() + { +#if FEATURE_CONCURRENT + this._runtimeAssemblies = new ConcurrentDictionary( StringComparer.OrdinalIgnoreCase ); +#else + this._syncRoot = new object(); + this._runtimeAssemblies = new Dictionary( StringComparer.OrdinalIgnoreCase ); +#endif // FEATURE_CONCURRENT + + this.ResetRuntimeAssemblies(); + +#if FEATURE_CONCURRENT + this._compiledCodeDomSerializerAssemblies = new ConcurrentDictionary( StringComparer.OrdinalIgnoreCase ); +#else + this._compiledCodeDomSerializerAssemblies = new Dictionary( StringComparer.OrdinalIgnoreCase ); +#endif // FEATURE_CONCURRENT + } + + protected abstract IEnumerable GetRuntimeAssemblies(); + + private void ResetRuntimeAssemblies() + { + var assemblies = this.GetRuntimeAssemblies(); +#if !FEATURE_CONCURRENT + lock ( this._syncRoot ) + { +#endif // !FEATURE_CONCURRENT + this._runtimeAssemblies.Clear(); + foreach ( var assembly in assemblies ) + { + this._runtimeAssemblies[ assembly ] = null; + } +#if !FEATURE_CONCURRENT + } +#endif // !FEATURE_CONCURRENT + } + + public void AddRuntimeAssembly( string pathToAssembly ) + { +#if !FEATURE_CONCURRENT + lock ( this._syncRoot ) + { +#endif // !FEATURE_CONCURRENT + this._runtimeAssemblies[ pathToAssembly ] = null; +#if !FEATURE_CONCURRENT + } +#endif // !FEATURE_CONCURRENT + } + + public void AddCompiledCodeAssembly( string pathToAssembly ) + { +#if !FEATURE_CONCURRENT + lock ( this._syncRoot ) + { +#endif // !FEATURE_CONCURRENT + this._compiledCodeDomSerializerAssemblies[ pathToAssembly ] = null; +#if !FEATURE_CONCURRENT + } +#endif // !FEATURE_CONCURRENT + } + + public void AddCompiledCodeAssembly( string name, byte[] image ) + { +#if !FEATURE_CONCURRENT + lock ( this._syncRoot ) + { +#endif // !FEATURE_CONCURRENT + this._compiledCodeDomSerializerAssemblies[ name ] = image; +#if !FEATURE_CONCURRENT + } +#endif // !FEATURE_CONCURRENT + } + + public void ResetDependentAssemblies() + { +#if !FEATURE_CONCURRENT + lock ( this._syncRoot ) + { +#endif // !FEATURE_CONCURRENT + this.Record( this._compiledCodeDomSerializerAssemblies.Where( kv => kv.Value == null ).Select( kv => kv.Key ) ); + this._compiledCodeDomSerializerAssemblies.Clear(); + this.ResetRuntimeAssemblies(); +#if !FEATURE_CONCURRENT + } +#endif // !FEATURE_CONCURRENT + } + + protected abstract void Record( IEnumerable assemblies ); + + public abstract void DeletePastTemporaries(); + + public virtual Assembly LoadAssembly( string path ) + { + throw new NotSupportedException(); + } + + private sealed class NullDependentAssemblyManager : DependentAssemblyManager + { + public NullDependentAssemblyManager() : base() { } + + protected override void Record( IEnumerable assemblies ) { } + + public override void DeletePastTemporaries() { } + + protected override IEnumerable GetRuntimeAssemblies() + { + yield break; + } + } + } +} +#endif // DEBUG diff --git a/src/MsgPack/Serialization/DictionaryKeyTransformers.cs b/src/MsgPack/Serialization/DictionaryKeyTransformers.cs new file mode 100644 index 000000000..b0f4df332 --- /dev/null +++ b/src/MsgPack/Serialization/DictionaryKeyTransformers.cs @@ -0,0 +1,46 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack.Serialization +{ + /// + /// Defines built-in, out-of-box handlers for . + /// + public static class DictionaryKeyTransformers + { + private static readonly Func _lowerCamel = KeyNameTransformers.ToLowerCamel; + + /// + /// Gets the handler which transforms upper camel casing (PascalCasing) key to lower camel casing (camelCasing) key. + /// + /// + /// The handler which transforms upper camel casing (PascalCasing) key to lower camel casing (camelCasing) key. + /// + /// + /// This method uses based invariant culture to tranform casing, so non ASCII charactors may not be transformed correctly espetially surrogate pairs. + /// + public static Func LowerCamel + { + get { return _lowerCamel; } + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/DictionarySerializationOptions.cs b/src/MsgPack/Serialization/DictionarySerializationOptions.cs new file mode 100644 index 000000000..0f5f86c18 --- /dev/null +++ b/src/MsgPack/Serialization/DictionarySerializationOptions.cs @@ -0,0 +1,128 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Threading; + +namespace MsgPack.Serialization +{ + /// + /// Defines dictionary (map) based serialization options. + /// + /// + /// These options do NOT affect serialization of + /// and . + /// The option only affect dictionary (map) based serialization which can be enabled via . + /// + public sealed class DictionarySerializationOptions + { +#if !FEATURE_CONCURRENT + private volatile bool _omitNullEntry; +#else + private bool _omitNullEntry; +#endif // !FEATURE_CONCURRENT + + /// + /// Gets or sets a value indicating whether omit key-value entry itself when the value is null. + /// + /// + /// true if key-value entry itself when the value is null; otherwise, false. + /// The default is false. + /// + /// + /// When the value is false, null value entry is emitted as following (using JSON syntax for easy visualization): + ///
+		///		{ "Foo": null }
+		///		
+ /// else, the value is true, null value entry is ommitted as following: + ///
+		///		{}
+		///		
+ ///
+ public bool OmitNullEntry + { + get + { +#if !FEATURE_CONCURRENT + return this._omitNullEntry; +#else + return Volatile.Read( ref this._omitNullEntry ); +#endif // !FEATURE_CONCURRENT + } + set + { +#if !FEATURE_CONCURRENT + this._omitNullEntry = value; +#else + Volatile.Write( ref this._omitNullEntry, value ); +#endif // !FEATURE_CONCURRENT + } + } + +#if !FEATURE_CONCURRENT + private volatile Func _keyNameHandler; +#else + private Func _keyTransformer; +#endif // !FEATURE_CONCURRENT + + + /// + /// Gets or sets the key name handler which enables dictionary key name customization. + /// + /// + /// The key name handler which enables dictionary key name customization. + /// The default value is null, which indicates that key name is not transformed. + /// + /// + public Func KeyTransformer + { + get + { +#if !FEATURE_CONCURRENT + return this._keyNameHandler; +#else + return Volatile.Read( ref this._keyTransformer ); +#endif // !FEATURE_CONCURRENT + } + set + { +#if !FEATURE_CONCURRENT + this._keyNameHandler = value; +#else + Volatile.Write( ref this._keyTransformer, value ); +#endif // !FEATURE_CONCURRENT + } + } + + internal Func SafeKeyTransformer + { + get { return this.KeyTransformer ?? KeyNameTransformers.AsIs; } + } + + /// + /// Initializes a new instance of the class. + /// + public DictionarySerializationOptions() { } + } +} diff --git a/src/MsgPack/Serialization/EmitterFlavor.cs b/src/MsgPack/Serialization/EmitterFlavor.cs index 4fc4aab41..6f6577ee2 100644 --- a/src/MsgPack/Serialization/EmitterFlavor.cs +++ b/src/MsgPack/Serialization/EmitterFlavor.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; namespace MsgPack.Serialization @@ -25,7 +29,12 @@ namespace MsgPack.Serialization /// /// Determines emitter strategy. /// - internal enum EmitterFlavor +#if UNITY && DEBUG + public +#else + internal +#endif + enum EmitterFlavor { #if !SILVERLIGHT /// diff --git a/src/MsgPack/Serialization/EmittingSerializers/AndConditionILConstruct.cs b/src/MsgPack/Serialization/EmittingSerializers/AndConditionILConstruct.cs index b65603f25..7daa18d31 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/AndConditionILConstruct.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/AndConditionILConstruct.cs @@ -24,6 +24,7 @@ using System.Linq; using System.Reflection.Emit; +using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers @@ -33,7 +34,7 @@ internal sealed class AndConditionILConstruct : ILConstruct private readonly IList _expressions; public AndConditionILConstruct( IList expressions ) - : base( typeof( bool ) ) + : base( TypeDefinition.BooleanType ) { if ( expressions.Count == 0 ) { diff --git a/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderCodeGenerationContext.cs b/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderCodeGenerationContext.cs index 1ca9edd15..9c22f7275 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderCodeGenerationContext.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderCodeGenerationContext.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -101,6 +101,9 @@ out serializerTypeNamespace /// A collection which correspond to genereated codes. public IEnumerable Generate() { +#if NETSTANDARD2_0 + throw new PlatformNotSupportedException( "Assembly generation is not supported in .NET Standard." ); +#else var assemblyFileName = this._assemblyBuilder.GetName().Name + ".dll"; this._assemblyBuilder.Save( assemblyFileName ); var assemblyFilePath = @@ -121,6 +124,7 @@ public IEnumerable Generate() s.SerializerTypeName ) ); +#endif // NETSTANDARD2_0 } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderEmittingContext.cs b/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderEmittingContext.cs index 880e86d29..c85e4e87c 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderEmittingContext.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderEmittingContext.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,16 +16,20 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; using System.Collections.Generic; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Linq; using System.Reflection; -#if FEATURE_TAP -using System.Threading; -#endif // FEATURE_TAP using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.Reflection; @@ -102,27 +106,29 @@ public AssemblyBuilderEmittingContext( SerializationContext context, Type target protected sealed override void ResetCore( Type targetType, Type baseClass ) { // Note: baseClass is always null this class hiearchy. - this.Packer = ILConstruct.Argument( 1, typeof( Packer ), "packer" ); - this.PackToTarget = ILConstruct.Argument( 2, targetType, "objectTree" ); - this.Unpacker = ILConstruct.Argument( 1, typeof( Unpacker ), "unpacker" ); - this.IndexOfItem = ILConstruct.Argument( 3, typeof( int ), "indexOfItem" ); - this.ItemsCount = ILConstruct.Argument( 4, typeof( int ), "itemsCount" ); - this.UnpackToTarget = ILConstruct.Argument( 2, targetType, "collection" ); - var traits = targetType.GetCollectionTraits( CollectionTraitOptions.Full ); + var targetTypeDefinition = TypeDefinition.Object( targetType ); + this.Packer = ILConstruct.Argument( 1, TypeDefinition.PackerType, "packer" ); + this.PackToTarget = ILConstruct.Argument( 2, targetTypeDefinition, "objectTree" ); + this.NullCheckTarget = ILConstruct.Argument( 1, targetTypeDefinition, "objectTree" ); + this.Unpacker = ILConstruct.Argument( 1, TypeDefinition.UnpackerType, "unpacker" ); + this.IndexOfItem = ILConstruct.Argument( 3, TypeDefinition.Int32Type, "indexOfItem" ); + this.ItemsCount = ILConstruct.Argument( 4, TypeDefinition.Int32Type, "itemsCount" ); + this.UnpackToTarget = ILConstruct.Argument( 2, targetTypeDefinition, "collection" ); + var traits = targetType.GetCollectionTraits( CollectionTraitOptions.Full, this.SerializationContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); if ( traits.ElementType != null ) { - this.CollectionToBeAdded = ILConstruct.Argument( 1, targetType, "collection" ); + this.CollectionToBeAdded = ILConstruct.Argument( 1, targetTypeDefinition, "collection" ); this.ItemToAdd = ILConstruct.Argument( 2, traits.ElementType, "item" ); if ( traits.DetailedCollectionType == CollectionDetailedKind.GenericDictionary -#if !NETFX_35 && !UNITY && !NETFX_40 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !SILVERLIGHT || traits.DetailedCollectionType == CollectionDetailedKind.GenericReadOnlyDictionary -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !SILVERLIGHT ) { this.KeyToAdd = ILConstruct.Argument( 2, traits.ElementType.GetGenericArguments()[ 0 ], "key" ); this.ValueToAdd = ILConstruct.Argument( 3, traits.ElementType.GetGenericArguments()[ 1 ], "value" ); } - this.InitialCapacity = ILConstruct.Argument( 1, typeof( int ), "initialCapacity" ); + this.InitialCapacity = ILConstruct.Argument( 1, TypeDefinition.Int32Type, "initialCapacity" ); } this._emitter = null; @@ -134,7 +140,7 @@ public override void BeginMethodOverride( string name ) this._ilGeneratorStack.Push( this.Emitter.DefineOverrideMethod( name ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] public override void BeginPrivateMethod( string name, bool isStatic, TypeDefinition returnType, params ILConstruct[] parameters ) { Contract.Assert( returnType != null ); @@ -169,19 +175,24 @@ private MethodDefinition EndMethod( ILConstruct body ) body.Evaluate( this.IL ); } - this.IL.EmitRet(); + if ( body == null || !body.IsTerminating ) + { + this.IL.EmitRet(); + } } finally { this.IL.FlushTrace(); +#if DEBUG SerializerDebugging.FlushTraceData(); +#endif // DEBUG lastMethod = this._ilGeneratorStack.Pop(); } return new MethodDefinition( lastMethod.Method, null, lastMethod.ParameterTypes ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override FieldDefinition DeclarePrivateFieldCore( string name, TypeDefinition type ) { Contract.Assert( type != null ); diff --git a/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderSerializerBuilder.cs b/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderSerializerBuilder.cs index b84ef28b4..0836f6f73 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderSerializerBuilder.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/AssemblyBuilderSerializerBuilder.cs @@ -20,7 +20,11 @@ using System; using System.Collections.Generic; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; @@ -48,13 +52,13 @@ internal sealed class AssemblyBuilderSerializerBuilder : SerializerBuilder statements ) { return ILConstruct.Sequence( contextType.ResolveRuntimeType(), statements ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct MakeNullLiteral( AssemblyBuilderEmittingContext context, TypeDefinition contextType ) { return ILConstruct.Literal( contextType.ResolveRuntimeType(), default( object ), il => il.EmitLdnull() ); @@ -62,36 +66,36 @@ protected override ILConstruct MakeNullLiteral( AssemblyBuilderEmittingContext c protected override ILConstruct MakeByteLiteral( AssemblyBuilderEmittingContext context, byte constant ) { - return MakeIntegerLiteral( typeof( byte ), constant ); + return MakeIntegerLiteral( TypeDefinition.ByteType, constant ); } protected override ILConstruct MakeSByteLiteral( AssemblyBuilderEmittingContext context, sbyte constant ) { - return MakeIntegerLiteral( typeof( sbyte ), constant ); + return MakeIntegerLiteral( TypeDefinition.SByteType, constant ); } protected override ILConstruct MakeInt16Literal( AssemblyBuilderEmittingContext context, short constant ) { - return MakeIntegerLiteral( typeof( short ), constant ); + return MakeIntegerLiteral( TypeDefinition.Int16Type, constant ); } protected override ILConstruct MakeUInt16Literal( AssemblyBuilderEmittingContext context, ushort constant ) { - return MakeIntegerLiteral( typeof( ushort ), constant ); + return MakeIntegerLiteral( TypeDefinition.UInt16Type, constant ); } protected override ILConstruct MakeInt32Literal( AssemblyBuilderEmittingContext context, int constant ) { - return MakeIntegerLiteral( typeof( int ), constant ); + return MakeIntegerLiteral( TypeDefinition.Int32Type, constant ); } protected override ILConstruct MakeUInt32Literal( AssemblyBuilderEmittingContext context, uint constant ) { - return MakeIntegerLiteral( typeof( uint ), unchecked( ( int )constant ) ); + return MakeIntegerLiteral( TypeDefinition.UInt32Type, unchecked( ( int )constant ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Many case switch" )] - private static ILConstruct MakeIntegerLiteral( Type contextType, int constant ) + private static ILConstruct MakeIntegerLiteral( TypeDefinition contextType, int constant ) { switch ( constant ) { @@ -151,40 +155,40 @@ private static ILConstruct MakeIntegerLiteral( Type contextType, int constant ) protected override ILConstruct MakeInt64Literal( AssemblyBuilderEmittingContext context, long constant ) { - return ILConstruct.Literal( typeof( long ), constant, il => il.EmitLdc_I8( constant ) ); + return ILConstruct.Literal( TypeDefinition.Int64Type, constant, il => il.EmitLdc_I8( constant ) ); } protected override ILConstruct MakeUInt64Literal( AssemblyBuilderEmittingContext context, ulong constant ) { - return ILConstruct.Literal( typeof( ulong ), constant, il => il.EmitLdc_I8( unchecked( ( long )constant ) ) ); + return ILConstruct.Literal( TypeDefinition.UInt64Type, constant, il => il.EmitLdc_I8( unchecked( ( long )constant ) ) ); } protected override ILConstruct MakeReal32Literal( AssemblyBuilderEmittingContext context, float constant ) { - return ILConstruct.Literal( typeof( float ), constant, il => il.EmitLdc_R4( constant ) ); + return ILConstruct.Literal( TypeDefinition.SingleType, constant, il => il.EmitLdc_R4( constant ) ); } protected override ILConstruct MakeReal64Literal( AssemblyBuilderEmittingContext context, double constant ) { - return ILConstruct.Literal( typeof( double ), constant, il => il.EmitLdc_R8( constant ) ); + return ILConstruct.Literal( TypeDefinition.DoubleType, constant, il => il.EmitLdc_R8( constant ) ); } protected override ILConstruct MakeBooleanLiteral( AssemblyBuilderEmittingContext context, bool constant ) { - return MakeIntegerLiteral( typeof( bool ), constant ? 1 : 0 ); + return MakeIntegerLiteral( TypeDefinition.BooleanType, constant ? 1 : 0 ); } protected override ILConstruct MakeCharLiteral( AssemblyBuilderEmittingContext context, char constant ) { - return MakeIntegerLiteral( typeof( char ), constant ); + return MakeIntegerLiteral( TypeDefinition.CharType, constant ); } protected override ILConstruct MakeStringLiteral( AssemblyBuilderEmittingContext context, string constant ) { - return ILConstruct.Literal( typeof( string ), constant, il => il.EmitLdstr( constant ) ); + return ILConstruct.Literal( TypeDefinition.StringType, constant, il => il.EmitLdstr( constant ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct MakeEnumLiteral( AssemblyBuilderEmittingContext context, TypeDefinition type, object constant ) { var underyingType = Enum.GetUnderlyingType( type.ResolveRuntimeType() ); @@ -249,7 +253,7 @@ protected override ILConstruct MakeEnumLiteral( AssemblyBuilderEmittingContext c } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct MakeDefaultLiteral( AssemblyBuilderEmittingContext context, TypeDefinition type ) { return @@ -266,7 +270,7 @@ protected override ILConstruct MakeDefaultLiteral( AssemblyBuilderEmittingContex ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitThisReferenceExpression( AssemblyBuilderEmittingContext context ) { return ILConstruct.Literal( context.GetSerializerType( this.TargetType ), "(this)", il => il.EmitLdarg_0() ); @@ -300,7 +304,7 @@ protected override ILConstruct EmitUnboxAnyExpression( AssemblyBuilderEmittingCo ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitNotExpression( AssemblyBuilderEmittingContext context, ILConstruct booleanExpression ) { if ( booleanExpression.ContextType.ResolveRuntimeType() != typeof( bool ) ) @@ -329,14 +333,14 @@ protected override ILConstruct EmitNotExpression( AssemblyBuilderEmittingContext ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitEqualsExpression( AssemblyBuilderEmittingContext context, ILConstruct left, ILConstruct right ) { var equality = left.ContextType.ResolveRuntimeType().GetMethod( "op_Equality" ); return ILConstruct.BinaryOperator( "==", - typeof( bool ), + TypeDefinition.BooleanType, left, right, ( il, l, r ) => @@ -370,7 +374,7 @@ protected override ILConstruct EmitEqualsExpression( AssemblyBuilderEmittingCont ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitGreaterThanExpression( AssemblyBuilderEmittingContext context, ILConstruct left, ILConstruct right ) { #if DEBUG && !CORE_CLR @@ -380,7 +384,7 @@ protected override ILConstruct EmitGreaterThanExpression( AssemblyBuilderEmittin return ILConstruct.BinaryOperator( ">", - typeof( bool ), + TypeDefinition.BooleanType, left, right, ( il, l, r ) => @@ -413,7 +417,7 @@ protected override ILConstruct EmitGreaterThanExpression( AssemblyBuilderEmittin ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitLessThanExpression( AssemblyBuilderEmittingContext context, ILConstruct left, ILConstruct right ) { #if DEBUG && !CORE_CLR @@ -423,7 +427,7 @@ protected override ILConstruct EmitLessThanExpression( AssemblyBuilderEmittingCo return ILConstruct.BinaryOperator( "<", - typeof( bool ), + TypeDefinition.BooleanType, left, right, ( il, l, r ) => @@ -477,13 +481,13 @@ protected override ILConstruct EmitTypeOfExpression( AssemblyBuilderEmittingCont { return ILConstruct.Literal( - typeof( Type ), + TypeDefinition.TypeType, type, il => il.EmitTypeOf( type.ResolveRuntimeType() ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitMethodOfExpression( AssemblyBuilderEmittingContext context, MethodBase method ) { var instructions = @@ -494,14 +498,14 @@ protected override ILConstruct EmitMethodOfExpression( AssemblyBuilderEmittingCo return ILConstruct.Instruction( "getsetter", - typeof( MethodBase ), + TypeDefinition.MethodBaseType, false, // Both of this pointer for FieldBasedSerializerEmitter and context argument of methods for ContextBasedSerializerEmitter are 0. il => instructions( il, 0 ) ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitFieldOfExpression( AssemblyBuilderEmittingContext context, FieldInfo field ) { var instructions = @@ -512,13 +516,30 @@ protected override ILConstruct EmitFieldOfExpression( AssemblyBuilderEmittingCon return ILConstruct.Instruction( "getfield", - typeof( FieldInfo ), + TypeDefinition.FieldInfoType, false, // Both of this pointer for FieldBasedSerializerEmitter and context argument of methods for ContextBasedSerializerEmitter are 0. il => instructions( il, 0 ) ); } + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + protected override ILConstruct EmitThrowStatement( AssemblyBuilderEmittingContext context, ILConstruct exception ) + { + return + ILConstruct.Instruction( + "throw", + TypeDefinition.VoidType, + true, + il => + { + exception.LoadValue( il, false ); + il.EmitThrow(); + } + ); + } + protected override ILConstruct DeclareLocal( AssemblyBuilderEmittingContext context, TypeDefinition nestedType, string name ) { return @@ -528,38 +549,44 @@ protected override ILConstruct DeclareLocal( AssemblyBuilderEmittingContext cont ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct ReferArgument( AssemblyBuilderEmittingContext context, TypeDefinition type, string name, int index ) { return ILConstruct.Argument( index, type.ResolveRuntimeType(), name ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitInvokeVoidMethod( AssemblyBuilderEmittingContext context, ILConstruct instance, MethodDefinition method, params ILConstruct[] arguments ) { return method.ResolveRuntimeMethod().ReturnType == typeof( void ) ? ILConstruct.Invoke( instance, method, arguments ) : ILConstruct.Sequence( - typeof( void ), + TypeDefinition.VoidType, new[] { ILConstruct.Invoke( instance, method, arguments ), - ILConstruct.Instruction( "pop", typeof( void ), false, il => il.EmitPop() ) + ILConstruct.Instruction( "pop", TypeDefinition.VoidType, false, il => il.EmitPop() ) } ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitCreateNewObjectExpression( AssemblyBuilderEmittingContext context, ILConstruct variable, ConstructorDefinition constructor, params ILConstruct[] arguments ) { - Contract.Assert( constructor != null ); - +#if DEBUG + Contract.Assert( constructor?.ResolveRuntimeConstructor() != null ); +#endif // DEBUG return ILConstruct.NewObject( variable, constructor.ResolveRuntimeConstructor(), arguments ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + protected override ILConstruct EmitMakeRef( AssemblyBuilderEmittingContext context, ILConstruct target ) + { + return ILConstruct.MakeRef( target ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override ILConstruct EmitCreateNewArrayExpression( AssemblyBuilderEmittingContext context, TypeDefinition elementType, int length ) { var array = @@ -591,8 +618,8 @@ protected override ILConstruct EmitCreateNewArrayExpression( AssemblyBuilderEmit ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override ILConstruct EmitCreateNewArrayExpression( AssemblyBuilderEmittingContext context, TypeDefinition elementType, int length, IEnumerable initialElements ) { var array = @@ -633,7 +660,7 @@ protected override ILConstruct EmitCreateNewArrayExpression( AssemblyBuilderEmit ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitGetArrayElementExpression( AssemblyBuilderEmittingContext context, ILConstruct array, ILConstruct index ) { return @@ -652,7 +679,7 @@ protected override ILConstruct EmitGetArrayElementExpression( AssemblyBuilderEmi ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitSetArrayElementStatement( AssemblyBuilderEmittingContext context, ILConstruct array, ILConstruct index, ILConstruct value ) { return @@ -677,25 +704,25 @@ protected override ILConstruct EmitInvokeMethodExpression( AssemblyBuilderEmitti return ILConstruct.Invoke( instance, method, arguments ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitInvokeDelegateExpression( AssemblyBuilderEmittingContext context, TypeDefinition delegateReturnType, ILConstruct @delegate, params ILConstruct[] arguments ) { return ILConstruct.Invoke( @delegate, @delegate.ContextType.ResolveRuntimeType().GetMethod( "Invoke" ), arguments ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitGetPropertyExpression( AssemblyBuilderEmittingContext context, ILConstruct instance, PropertyInfo property ) { return ILConstruct.Invoke( instance, property.GetGetMethod( true ), ILConstruct.NoArguments ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitGetFieldExpression( AssemblyBuilderEmittingContext context, ILConstruct instance, FieldDefinition field ) { return ILConstruct.LoadField( instance, field.ResolveRuntimeField() ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitSetProperty( AssemblyBuilderEmittingContext context, ILConstruct instance, PropertyInfo property, ILConstruct value ) { #if DEBUG @@ -709,7 +736,7 @@ protected override ILConstruct EmitSetProperty( AssemblyBuilderEmittingContext c return ILConstruct.Invoke( instance, property.GetSetMethod( true ), new[] { value } ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "Validated by caller in base class" )] protected override ILConstruct EmitSetIndexedProperty( AssemblyBuilderEmittingContext context, ILConstruct instance, TypeDefinition declaringType, string proeprtyName, ILConstruct key, ILConstruct value ) { @@ -721,19 +748,19 @@ protected override ILConstruct EmitSetIndexedProperty( AssemblyBuilderEmittingCo return ILConstruct.Invoke( instance, indexer.GetSetMethod( true ), new[] { key, value } ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitSetField( AssemblyBuilderEmittingContext context, ILConstruct instance, FieldDefinition field, ILConstruct value ) { return ILConstruct.StoreField( instance, field.ResolveRuntimeField(), value ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitSetField( AssemblyBuilderEmittingContext context, ILConstruct instance, TypeDefinition nestedType, string fieldName, ILConstruct value ) { return ILConstruct.StoreField( instance, nestedType.ResolveRuntimeType().GetField( fieldName ), value ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitLoadVariableExpression( AssemblyBuilderEmittingContext context, ILConstruct variable ) { return ILConstruct.Instruction( "load", variable.ContextType, false, il => variable.LoadValue( il, false ) ); @@ -744,7 +771,7 @@ protected override ILConstruct EmitStoreVariableStatement( AssemblyBuilderEmitti return ILConstruct.StoreLocal( variable, value ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitTryFinally( AssemblyBuilderEmittingContext context, ILConstruct tryStatement, ILConstruct finallyStatement ) { return @@ -788,7 +815,7 @@ protected override ILConstruct EmitForEachLoop( AssemblyBuilderEmittingContext c return ILConstruct.Instruction( "foreach", - typeof( void ), + TypeDefinition.VoidType, false, il => { @@ -902,10 +929,11 @@ protected override ILConstruct EmitEnumToUnderlyingCastExpression( AssemblyBuild protected override Func CreateSerializerConstructor( AssemblyBuilderEmittingContext codeGenerationContext, SerializationTarget targetInfo, - PolymorphismSchema schema + PolymorphismSchema schema, + SerializerCapabilities? capabilities ) { - return context => codeGenerationContext.Emitter.CreateObjectInstance( codeGenerationContext, this, targetInfo, schema ); + return context => codeGenerationContext.Emitter.CreateObjectInstance( codeGenerationContext, this, targetInfo, schema, capabilities ); } protected override Func CreateEnumSerializerConstructor( AssemblyBuilderEmittingContext codeGenerationContext ) @@ -917,7 +945,7 @@ protected override Func CreateEnumS ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitGetSerializerExpression( AssemblyBuilderEmittingContext context, Type targetType, SerializingMember? memberInfo, PolymorphismSchema itemsSchema ) { var realSchema = itemsSchema ?? PolymorphismSchema.Create( targetType, memberInfo ); @@ -942,7 +970,7 @@ private IEnumerable EmitConstructPolymorphismSchema( PolymorphismSchema currentSchema ) { - var schema = this.DeclareLocal( context, typeof( PolymorphismSchema ), "schema" ); + var schema = this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, "schema" ); yield return schema; @@ -954,7 +982,7 @@ PolymorphismSchema currentSchema yield return this.EmitLoadVariableExpression( context, schema ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitGetActionsExpression( AssemblyBuilderEmittingContext context, ActionType actionType, bool isAsync ) { Type type; @@ -973,7 +1001,7 @@ protected override ILConstruct EmitGetActionsExpression( AssemblyBuilderEmitting } case ActionType.PackToMap: { - type = + type = #if FEATURE_TAP isAsync ? typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,,,> ).MakeGenericType( typeof( Packer ), this.TargetType, typeof( CancellationToken ), typeof( Task ) ) ) : #endif // FEATURE_TAP @@ -981,6 +1009,12 @@ protected override ILConstruct EmitGetActionsExpression( AssemblyBuilderEmitting name = FieldName.PackOperationTable; break; } + case ActionType.IsNull: + { + type = typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,> ).MakeGenericType( this.TargetType, typeof( bool ) ) ); + name = FieldName.NullCheckersTable; + break; + } case ActionType.UnpackFromArray: { type = @@ -1066,16 +1100,16 @@ protected override ILConstruct EmitGetActionsExpression( AssemblyBuilderEmitting return this.EmitGetFieldExpression( context, this.EmitThisReferenceExpression( context ), field ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitGetMemberNamesExpression( AssemblyBuilderEmittingContext context ) { - var field = context.DeclarePrivateField( FieldName.MemberNames, typeof( IList ) ); + var field = context.DeclarePrivateField( FieldName.MemberNames, TypeDefinition.IListOfStringType ); return this.EmitGetFieldExpression( context, this.EmitThisReferenceExpression( context ), field ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitFinishFieldInitializationStatement( AssemblyBuilderEmittingContext context, string name, ILConstruct value ) { var field = context.DeclarePrivateField( name, value.ContextType.ResolveRuntimeType() ); @@ -1110,7 +1144,7 @@ out serializerTypeNamespace ); } -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if FEATURE_ASMGEN protected override void BuildSerializerCodeCore( ISerializerCodeGenerationContext context, Type concreteType, PolymorphismSchema itemSchema ) { @@ -1135,7 +1169,7 @@ protected override void BuildSerializerCodeCore( ISerializerCodeGenerationContex SerializationTarget targetInfo; this.BuildSerializer( emittingContext, concreteType, itemSchema, out targetInfo ); // Finish type creation, and discard returned ctor. - emittingContext.Emitter.CreateObjectConstructor( emittingContext, this, targetInfo ); + emittingContext.Emitter.CreateObjectConstructor( emittingContext, this, targetInfo, targetInfo.GetCapabilitiesForObject() ); } else { @@ -1145,9 +1179,9 @@ protected override void BuildSerializerCodeCore( ISerializerCodeGenerationContex } } -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // FEATURE_ASMGEN - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitNewPrivateMethodDelegateExpression( AssemblyBuilderEmittingContext context, MethodDefinition method ) { var delegateType = SerializerBuilderHelper.GetResolvedDelegateType( method.ReturnType, method.ParameterTypes ); @@ -1159,7 +1193,14 @@ protected override ILConstruct EmitNewPrivateMethodDelegateExpression( AssemblyB false, il => { - il.EmitLdargThis(); + if ( method.IsStatic ) + { + il.EmitLdnull(); + } + else + { + il.EmitLdargThis(); + } // OK this should not be ldvirtftn because target is private. il.EmitLdftn( method.ResolveRuntimeMethod() ); // call extern .ctor(Object, void*) @@ -1168,4 +1209,4 @@ protected override ILConstruct EmitNewPrivateMethodDelegateExpression( AssemblyB ); } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/EmittingSerializers/ILConstruct.cs b/src/MsgPack/Serialization/EmittingSerializers/ILConstruct.cs index 7a3e3fa12..058aa30db 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/ILConstruct.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/ILConstruct.cs @@ -219,6 +219,11 @@ public static ILConstruct Variable( TypeDefinition type, string name ) return new VariableILConstruct( name, type ); } + public static ILConstruct MakeRef(ILConstruct variable ) + { + return new SinglelStepILConstruct( variable.ContextType, "mkref", false, il => variable.LoadValue( il, true ) ); + } + protected static void ValidateContextTypeMatch( ILConstruct left, ILConstruct right ) { if ( GetNormalizedType( left.ContextType.ResolveRuntimeType() ) != GetNormalizedType( right.ContextType.ResolveRuntimeType() ) ) diff --git a/src/MsgPack/Serialization/EmittingSerializers/InvocationILConsruct.cs b/src/MsgPack/Serialization/EmittingSerializers/InvocationILConsruct.cs index c2feb8f40..80294bd6d 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/InvocationILConsruct.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/InvocationILConsruct.cs @@ -153,7 +153,7 @@ private void Invoke( TracingILGenerator il ) il.EmitCallvirt( this._interface.GetRuntimeMethod( this._method.Name.Substring( this._method.Name.LastIndexOf( '.' ) + 1 ), - this._method.GetParameters().Select( p => p.ParameterType ).ToArray() + this._method.GetParameterTypes() ) ); } diff --git a/src/MsgPack/Serialization/EmittingSerializers/SerializationMethodGeneratorManager.cs b/src/MsgPack/Serialization/EmittingSerializers/SerializationMethodGeneratorManager.cs index 993d0c352..22bcd8398 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/SerializationMethodGeneratorManager.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/SerializationMethodGeneratorManager.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,7 +20,11 @@ using System; using System.Diagnostics; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Reflection; using System.Reflection.Emit; using System.Security; @@ -44,11 +48,11 @@ internal sealed class SerializationMethodGeneratorManager /// public static SerializationMethodGeneratorManager Get() { -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if DEBUG && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 return Get( SerializerDebugging.DumpEnabled ? SerializationMethodGeneratorOption.CanDump : SerializationMethodGeneratorOption.Fast ); #else return Get( SerializationMethodGeneratorOption.Fast ); -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // DEBUG && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 } /// @@ -90,7 +94,7 @@ public static SerializationMethodGeneratorManager Get( SerializationMethodGenera #if !SILVERLIGHT - private static SerializationMethodGeneratorManager _canCollect = new SerializationMethodGeneratorManager( false, true, null ); + private static SerializationMethodGeneratorManager _canCollect = Create( false, true, null ); /// /// Get the singleton instance for can-collect mode. @@ -101,7 +105,7 @@ public static SerializationMethodGeneratorManager CanCollect } #if !NETSTANDARD1_1 && !NETSTANDARD1_3 - private static SerializationMethodGeneratorManager _canDump = new SerializationMethodGeneratorManager( true, false, null ); + private static SerializationMethodGeneratorManager _canDump = Create( true, false, null ); /// /// Get the singleton instance for can-dump mode. @@ -114,7 +118,7 @@ public static SerializationMethodGeneratorManager CanDump #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // !SILVERLIGHT - private static SerializationMethodGeneratorManager _fast = new SerializationMethodGeneratorManager( false, false, null ); + private static SerializationMethodGeneratorManager _fast = Create( false, false, null ); /// /// Get the singleton instance for fast mode. @@ -124,15 +128,27 @@ public static SerializationMethodGeneratorManager Fast get { return _fast; } } + private static SerializationMethodGeneratorManager Create( bool isDebuggable, bool isCollectable, AssemblyBuilder assemblyBuilder ) + { + try + { + return new SerializationMethodGeneratorManager( isDebuggable, isCollectable, assemblyBuilder ); + } + catch ( PlatformNotSupportedException ) + { + return null; + } + } + internal static void Refresh() { #if !SILVERLIGHT - _canCollect = new SerializationMethodGeneratorManager( false, true, null ); + _canCollect = Create( false, true, null ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 - _canDump = new SerializationMethodGeneratorManager( true, false, null ); + _canDump = Create( true, false, null ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // !SILVERLIGHT - _fast = new SerializationMethodGeneratorManager( false, false, null ); + _fast = Create( false, false, null ); } // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable @@ -140,12 +156,12 @@ internal static void Refresh() private readonly ModuleBuilder _module; private readonly bool _isDebuggable; -#if NETFX_35 +#if NET35 [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isCollectable", Justification = "Used in other platforms" )] -#endif // NETFX_35 -#if !NETFX_35 +#endif // NET35 +#if !NET35 [SecuritySafeCritical] -#endif // !NETFX_35 +#endif // !NET35 private SerializationMethodGeneratorManager( bool isDebuggable, bool isCollectable, AssemblyBuilder assemblyBuilder ) { this._isDebuggable = isDebuggable; @@ -165,29 +181,33 @@ private SerializationMethodGeneratorManager( bool isDebuggable, bool isCollectab { assemblyName = typeof( SerializationMethodGeneratorManager ).Namespace + ".GeneratedSerealizers" + Interlocked.Increment( ref _assemblySequence ); var dedicatedAssemblyBuilder = -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( assemblyName ), isDebuggable ? AssemblyBuilderAccess.RunAndSave -#if !NETFX_35 +#if !NET35 : ( isCollectable ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run ) #else : AssemblyBuilderAccess.Run -#endif // !NETFX_35 +#endif // !NET35 +#if DEBUG + , + SerializerDebugging.DumpDirectory +#endif // DEBUG ); #else AssemblyBuilder.DefineDynamicAssembly( new AssemblyName( assemblyName ), isCollectable ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 SetUpAssemblyBuilderAttributes( dedicatedAssemblyBuilder, isDebuggable ); this._assembly = dedicatedAssemblyBuilder; } -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( isDebuggable ) { this._module = this._assembly.DefineDynamicModule( assemblyName, assemblyName + ".dll", true ); @@ -198,7 +218,7 @@ private SerializationMethodGeneratorManager( bool isDebuggable, bool isCollectab } #else this._module = this._assembly.DefineDynamicModule( assemblyName ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 } internal static void SetUpAssemblyBuilderAttributes( AssemblyBuilder dedicatedAssemblyBuilder, bool isDebuggable ) @@ -225,7 +245,7 @@ internal static void SetUpAssemblyBuilderAttributes( AssemblyBuilder dedicatedAs new object[] { 8 } ) ); -#if !NETFX_35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NET35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 dedicatedAssemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( // ReSharper disable once AssignNullToNotNullAttribute @@ -235,7 +255,7 @@ internal static void SetUpAssemblyBuilderAttributes( AssemblyBuilder dedicatedAs new object[] { true } ) ); -#endif // !NETFX_35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NET35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 } /// diff --git a/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.cs b/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.cs index 8064654f1..011a79cc1 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,7 +20,11 @@ using System; using System.Collections.Generic; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; @@ -74,12 +78,12 @@ public SerializerEmitter( ModuleBuilder host, SerializerSpecification specificat #endif // DEBUG this._isDebuggable = isDebuggable; -#if !NETFX_35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if DEBUG && !NET35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( isDebuggable && SerializerDebugging.DumpEnabled ) { SerializerDebugging.PrepareDump( host.Assembly as AssemblyBuilder ); } -#endif // !NETFX_35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // DEBUG && !NET35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 } #region -- Field -- @@ -169,7 +173,7 @@ private ILMethodConctext DefineMethod( string methodName, bool isOverride, bool ( baseMethod.Attributes | MethodAttributes.Final ) & ( ~MethodAttributes.Abstract ), baseMethod.CallingConvention, baseMethod.ReturnType, - baseMethod.GetParameters().Select( p => p.ParameterType ).ToArray() + baseMethod.GetParameterTypes() ); this._typeBuilder.DefineMethodOverride( builder, @@ -198,12 +202,14 @@ private ILMethodConctext DefineMethod( string methodName, bool isOverride, bool ); } -#endregion -- Method -- + #endregion -- Method -- -#region -- IL Generation -- + #region -- IL Generation -- + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "parameterTypes", Justification = "For DEBUG build." )] private TracingILGenerator GetILGenerator( ConstructorBuilder builder, Type[] parameterTypes ) { +#if DEBUG if ( SerializerDebugging.TraceEnabled ) { SerializerDebugging.ILTraceWriter.WriteLine(); @@ -213,19 +219,22 @@ private TracingILGenerator GetILGenerator( ConstructorBuilder builder, Type[] pa String.Join( ", ", parameterTypes.Select( t => t.GetFullName() ).ToArray() ), builder.Attributes.ToILString(), builder.CallingConvention.ToILString(), -#if !NETFX_35 && !NETFX_40 +#if !NET35 && !NET40 builder.MethodImplementationFlags.ToILString() #else String.Empty -#endif // !NETFX_35 && !NETFX_40 +#endif // !NET35 && !NET40 ); } +#endif // DEBUG return new TracingILGenerator( builder, SerializerDebugging.ILTraceWriter, this._isDebuggable ); } + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "parameterTypes", Justification = "For DEBUG build." )] private TracingILGenerator GetILGenerator( MethodBuilder builder, Type[] parameterTypes ) { +#if DEBUG if ( SerializerDebugging.TraceEnabled ) { SerializerDebugging.ILTraceWriter.WriteLine(); @@ -237,13 +246,14 @@ private TracingILGenerator GetILGenerator( MethodBuilder builder, Type[] paramet builder.ReturnType.GetFullName(), builder.Attributes.ToILString(), builder.CallingConvention.ToILString(), -#if !NETFX_35 && !NETFX_40 +#if !NET35 && !NET40 builder.MethodImplementationFlags.ToILString() #else String.Empty -#endif // !NETFX_35 && !NETFX_40 +#endif // !NET35 && !NET40 ); } +#endif // DEBUG return new TracingILGenerator( builder, SerializerDebugging.ILTraceWriter, this._isDebuggable ); } @@ -262,14 +272,16 @@ private ConstructorBuilder CreateConstructor( MethodAttributes attributes, Type[ var builder = this.DefineConstructor( attributes, parameterTypes ); emitter( this._typeBuilder.BaseType, this.GetILGenerator( builder, parameterTypes ) ); +#if DEBUG if ( SerializerDebugging.TraceEnabled ) { SerializerDebugging.FlushTraceData(); } +#endif // DEBUG return builder; } #endregion -- Constructor -- } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.enum.cs b/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.enum.cs index 1c48a3cd3..2b73b4bde 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.enum.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.enum.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014-2016 FUJIWARA, Yusuke +// Copyright (C) 2014-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,8 +19,11 @@ #endregion -- License Terms -- using System; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; -using System.Linq.Expressions; +#endif // NETSTANDARD1_1 using System.Reflection; using System.Reflection.Emit; @@ -49,7 +52,7 @@ public SerializerEmitter( SerializationContext context, ModuleBuilder host, Seri { Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, "Create {0}", specification.SerializerTypeFullName ); - this._defaultEnumSerializationMethod = context.EnumSerializationMethod; + this._defaultEnumSerializationMethod = context.EnumSerializationOptions.SerializationMethod; } /// @@ -85,27 +88,16 @@ public Func>( - Expression.New( - ctor, - contextParameter, - methodParameter - ), - contextParameter, - methodParameter - ).Compile(); + return ctor.CreateConstructorDelegate>(); } private void EmitDefaultEnumConstructor( ConstructorBuilder methodConstructor, TracingILGenerator il ) @@ -146,4 +138,4 @@ private void EmitMethodEnumConstructor( Type baseType, TracingILGenerator il ) il.EmitRet(); } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.object.cs b/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.object.cs index ac4aa71f7..e39a56f13 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.object.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/SerializerEmitter.object.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,9 +20,12 @@ using System; using System.Collections.Generic; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Linq; -using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; @@ -33,8 +36,9 @@ namespace MsgPack.Serialization.EmittingSerializers { partial class SerializerEmitter { - private static readonly Type[] ConstructorParameterTypes = { typeof( SerializationContext ) }; - private static readonly Type[] CollectionConstructorParameterTypes = { typeof( SerializationContext ), typeof( PolymorphismSchema ) }; + private static readonly Type[] ConstructorParameterTypesWithoutCapabilities = { typeof( SerializationContext ) }; + private static readonly Type[] ConstructorParameterTypesWithCapabilities = { typeof( SerializationContext ), typeof( SerializerCapabilities ) }; + private static readonly Type[] CollectionConstructorParameterTypes = { typeof( SerializationContext ), typeof( PolymorphismSchema ), typeof( SerializerCapabilities ) }; #region -- Dependent Serializer Management -- @@ -227,8 +231,6 @@ public CachedMethodBase( MethodBase target, FieldBuilder storageFieldBuilder ) private TypeBuilder _unpackingContextType; - private readonly Dictionary _unpackingContextFields = new Dictionary(); - public void DefineUnpackingContext( string name, IList> fields, out Type type, out ConstructorInfo constructor ) { this._unpackingContextType = @@ -253,7 +255,6 @@ public void DefineUnpackingContext( string name, IListThe builder which implements actions initialization emit. /// The information of the target. /// The for this instance. + /// The capabilities of the generating serializer. /// /// Newly built instance. /// This value will not be null. /// - public MessagePackSerializer CreateObjectInstance( AssemblyBuilderEmittingContext context, AssemblyBuilderSerializerBuilder builder, SerializationTarget targetInfo, PolymorphismSchema schema ) + public MessagePackSerializer CreateObjectInstance( + AssemblyBuilderEmittingContext context, + AssemblyBuilderSerializerBuilder builder, + SerializationTarget targetInfo, + PolymorphismSchema schema, + SerializerCapabilities? capabilities + ) { - return this.CreateObjectConstructor( context, builder, targetInfo )( context.SerializationContext, schema ); + return this.CreateObjectConstructor( context, builder, targetInfo, capabilities )( context.SerializationContext, schema ); } /// @@ -298,13 +308,19 @@ public MessagePackSerializer CreateObjectInstance( AssemblyBuilderEmittingContex /// /// The context. /// The builder which implements actions initialization emit. - /// The information of the target + /// The information of the targe.t + /// The for object serializer. null for other types. /// /// Newly built type constructor. /// This value will not be null. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Reflection objects" )] - public Func CreateObjectConstructor( AssemblyBuilderEmittingContext context, AssemblyBuilderSerializerBuilder builder, SerializationTarget targetInfo ) + public Func CreateObjectConstructor( + AssemblyBuilderEmittingContext context, + AssemblyBuilderSerializerBuilder builder, + SerializationTarget targetInfo, + SerializerCapabilities? capabilities + ) { var hasPackActions = targetInfo != null && !typeof( IPackable ).IsAssignableFrom( builder.TargetType ); var hasUnpackActions = targetInfo != null && !typeof( IUnpackable ).IsAssignableFrom( builder.TargetType ); @@ -321,6 +337,7 @@ public Func Cre Func> packActionTableInitialization = isAsync => new Func( () => builder.EmitPackOperationTableInitialization( context, targetInfo, isAsync ) ); + Func nullCheckerTableInitializtion = () => builder.EmitPackNullCheckerTableInitialization( context, targetInfo ); Func> unpackActionsInitialization = isAsync => new Func( () => builder.EmitUnpackOperationListInitialization( context, targetInfo, isAsync ) ); Func> unpackActionTableInitialization = @@ -330,11 +347,12 @@ public Func Cre var contextfulConstructor = this.CreateConstructor( MethodAttributes.Public, - ConstructorParameterTypes, + ConstructorParameterTypesWithoutCapabilities, ( type, il ) => this.CreateContextfulObjectConstructor( context, type, + capabilities, il, hasPackActions ? packActionsInitialization( false ) @@ -342,6 +360,15 @@ public Func Cre hasPackActions ? packActionTableInitialization( false ) : default( Func ), +#if DEBUG + !SerializerDebugging.UseLegacyNullMapEntryHandling && +#endif // DEBUG + hasPackActions +#if FEATURE_TAP + || hasPackAsyncActions +#endif // FEATURE_TAP + ? nullCheckerTableInitializtion + : default( Func ), hasUnpackActions ? unpackActionsInitialization( false ) : default( Func ), @@ -380,27 +407,19 @@ public Func Cre ( _, il ) => CreateDefaultObjectConstructor( contextfulConstructor, il ) ); -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - var ctor = this._typeBuilder.CreateType().GetConstructor( ConstructorParameterTypes ); +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 + var ctor = this._typeBuilder.CreateType().GetConstructor( ConstructorParameterTypesWithoutCapabilities ); #else - var ctor = this._typeBuilder.CreateTypeInfo().GetConstructor( ConstructorParameterTypes ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - var contextParameter = Expression.Parameter( typeof( SerializationContext ), "context" ); - var schemaParameter = Expression.Parameter( typeof( PolymorphismSchema ), "schema" ); + var ctor = this._typeBuilder.CreateTypeInfo().GetConstructor( ConstructorParameterTypesWithoutCapabilities ); +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 + #if DEBUG Contract.Assert( ctor != null, "ctor != null" ); #endif - return - Expression.Lambda>( - Expression.New( - ctor, - contextParameter - ), - contextParameter, - schemaParameter - ).Compile(); + var actualFunc = ctor.CreateConstructorDelegate>(); + return ( c, _ ) => actualFunc( c ); } - + private static void CreateDefaultObjectConstructor( ConstructorBuilder contextfulConstructorBuilder, TracingILGenerator il ) { /* @@ -417,9 +436,11 @@ private static void CreateDefaultObjectConstructor( ConstructorBuilder contextfu private void CreateContextfulObjectConstructor( AssemblyBuilderEmittingContext context, Type baseType, + SerializerCapabilities? capabilities, TracingILGenerator il, Func packActionListInitializerProvider, Func packActionTableInitializerProvider, + Func nullCheckerTableInitializerProvider, Func unpackActionListInitializerProvider, Func unpackActionTableInitializerProvider, #if FEATURE_TAP @@ -447,13 +468,27 @@ Func unpackToInitializerProvider il.EmitLdarg_1(); if ( this._specification.TargetCollectionTraits.CollectionType == CollectionKind.NotCollection ) { - il.EmitCallConstructor( - baseType.GetRuntimeConstructor( ConstructorParameterTypes ) - ); + if ( capabilities.HasValue ) + { + il.EmitAnyLdc_I4( ( int )capabilities.Value ); + + il.EmitCallConstructor( + baseType.GetRuntimeConstructor( ConstructorParameterTypesWithCapabilities ) + ); + } + else + { + il.EmitCallConstructor( + baseType.GetRuntimeConstructor( ConstructorParameterTypesWithoutCapabilities ) + ); + } } else { + Contract.Assert( capabilities.HasValue ); + il.EmitCall( this._methodTable[ MethodName.RestoreSchema ] ); + il.EmitAnyLdc_I4( ( int )capabilities.Value ); il.EmitCallConstructor( baseType.GetRuntimeConstructor( CollectionConstructorParameterTypes ) ); @@ -528,6 +563,11 @@ Func unpackToInitializerProvider } #endif // FEATURE_TAP + if ( nullCheckerTableInitializerProvider != null ) + { + nullCheckerTableInitializerProvider().Evaluate( il ); + } + if ( packActionTableInitializerProvider != null ) { packActionTableInitializerProvider().Evaluate( il ); diff --git a/src/MsgPack/Serialization/EmittingSerializers/StoreFieldILConstruct.cs b/src/MsgPack/Serialization/EmittingSerializers/StoreFieldILConstruct.cs index 4d6a88812..50ff7b12f 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/StoreFieldILConstruct.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/StoreFieldILConstruct.cs @@ -22,6 +22,7 @@ using System.Globalization; using System.Reflection; +using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers @@ -33,7 +34,7 @@ internal class StoreFieldILConstruct : ContextfulILConstruct private readonly FieldInfo _field; public StoreFieldILConstruct( ILConstruct instance, FieldInfo field, ILConstruct value ) - : base( typeof( void ) ) + : base( TypeDefinition.VoidType ) { this._instance = instance; this._field = field; diff --git a/src/MsgPack/Serialization/EmittingSerializers/StoreVariableILConstruct.cs b/src/MsgPack/Serialization/EmittingSerializers/StoreVariableILConstruct.cs index 36db0ace7..45806d414 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/StoreVariableILConstruct.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/StoreVariableILConstruct.cs @@ -21,6 +21,7 @@ using System; using System.Globalization; +using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers @@ -31,7 +32,7 @@ internal class StoreVariableILConstruct : ILConstruct private readonly ILConstruct _value; public StoreVariableILConstruct( ILConstruct variable, ILConstruct value ) - : base( typeof( void ) ) + : base( TypeDefinition.VoidType ) { this._variable = variable; this._value = value; diff --git a/src/MsgPack/Serialization/EmittingSerializers/VariableILConstruct.cs b/src/MsgPack/Serialization/EmittingSerializers/VariableILConstruct.cs index ac431bb5d..655bb85e2 100644 --- a/src/MsgPack/Serialization/EmittingSerializers/VariableILConstruct.cs +++ b/src/MsgPack/Serialization/EmittingSerializers/VariableILConstruct.cs @@ -19,11 +19,11 @@ #endregion -- License Terms -- using System; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using MsgPack.Serialization.AbstractSerializers; diff --git a/src/MsgPack/Serialization/EnumMessagePackSerializerHelpers.cs b/src/MsgPack/Serialization/EnumMessagePackSerializerHelpers.cs index 0f10db737..32723c65d 100644 --- a/src/MsgPack/Serialization/EnumMessagePackSerializerHelpers.cs +++ b/src/MsgPack/Serialization/EnumMessagePackSerializerHelpers.cs @@ -69,7 +69,7 @@ EnumMemberSerializationMethod enumMemberSerializationMethod throw new ArgumentNullException( "enumType" ); } - EnumSerializationMethod method = context.EnumSerializationMethod; + EnumSerializationMethod method = context.EnumSerializationOptions.SerializationMethod; switch ( enumMemberSerializationMethod ) { case EnumMemberSerializationMethod.ByName: @@ -107,4 +107,4 @@ EnumMemberSerializationMethod enumMemberSerializationMethod return method; } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/EnumMessagePackSerializerProvider.cs b/src/MsgPack/Serialization/EnumMessagePackSerializerProvider.cs index 0acea0aad..243a3d17f 100644 --- a/src/MsgPack/Serialization/EnumMessagePackSerializerProvider.cs +++ b/src/MsgPack/Serialization/EnumMessagePackSerializerProvider.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014 FUJIWARA, Yusuke +// Copyright (C) 2014-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; namespace MsgPack.Serialization @@ -26,7 +30,12 @@ namespace MsgPack.Serialization /// Implements for enums. /// This class accepts as a provider parameter. /// - internal sealed class EnumMessagePackSerializerProvider : MessagePackSerializerProvider +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class EnumMessagePackSerializerProvider : MessagePackSerializerProvider { private readonly Type _enumType; private readonly object _serializerForName; @@ -86,4 +95,4 @@ public override object Get( SerializationContext context, object providerParamet } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/EnumMessagePackSerializer`1.cs b/src/MsgPack/Serialization/EnumMessagePackSerializer`1.cs index 6bfa96ec2..78069d790 100644 --- a/src/MsgPack/Serialization/EnumMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/EnumMessagePackSerializer`1.cs @@ -23,6 +23,7 @@ #endif using System; +using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; #if FEATURE_TAP @@ -43,6 +44,8 @@ public abstract class EnumMessagePackSerializer : MessagePackSerializer _serializationMapping; + private readonly Dictionary _deserializationMapping; private EnumSerializationMethod _serializationMethod; // not readonly -- changed in cloned instance in GetCopyAs() /// @@ -51,8 +54,9 @@ public abstract class EnumMessagePackSerializer : MessagePackSerializerA which owns this serializer. /// The which determines serialization form of the enums. /// TEnum is not enum type. + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated in base consctructor." )] protected EnumMessagePackSerializer( SerializationContext ownerContext, EnumSerializationMethod serializationMethod ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { if ( !typeof( TEnum ).GetIsEnum() ) { @@ -63,6 +67,15 @@ protected EnumMessagePackSerializer( SerializationContext ownerContext, EnumSeri this._serializationMethod = serializationMethod; this._underlyingType = Enum.GetUnderlyingType( typeof( TEnum ) ); + var members = Enum.GetValues( typeof( TEnum ) ) as TEnum[]; + this._serializationMapping = new Dictionary( members.Length ); + this._deserializationMapping = new Dictionary( members.Length ); + foreach ( var member in members ) + { + var asString = ownerContext.EnumSerializationOptions.SafeNameTransformer( member.ToString() ); + this._serializationMapping[ member ] = asString; + this._deserializationMapping[ asString ] = member; + } } /// @@ -79,7 +92,14 @@ protected internal sealed override void PackToCore( Packer packer, TEnum objectT } else { - packer.PackString( objectTree.ToString() ); + string asString; + if ( !this._serializationMapping.TryGetValue( objectTree, out asString ) ) + { + // May be undefined value which should be numeric. + asString = objectTree.ToString(); + } + + packer.PackString( asString ); } } @@ -111,7 +131,14 @@ protected internal sealed override Task PackToAsyncCore( Packer packer, TEnum ob } else { - return packer.PackStringAsync( objectTree.ToString(), cancellationToken ); + string asString; + if ( !this._serializationMapping.TryGetValue( objectTree, out asString ) ) + { + // May be undefined value which should be numeric. + asString = objectTree.ToString(); + } + + return packer.PackStringAsync( asString, cancellationToken ); } } @@ -153,36 +180,40 @@ protected internal sealed override TEnum UnpackFromCore( Unpacker unpacker ) var asString = unpacker.LastReadData.AsString(); TEnum result; -#if NETFX_35 || UNITY - try - { - result = ( TEnum ) Enum.Parse( typeof( TEnum ), asString, false ); - } - catch ( ArgumentException ex ) + if ( !this._deserializationMapping.TryGetValue( asString, out result ) ) { - throw new SerializationException( - String.Format( - CultureInfo.CurrentCulture, - "Name '{0}' is not member of enum type '{1}'.", - asString, - typeof( TEnum ) - ), - ex - ); - } + // May be undefined value which should be numeric, or PacakCasing. +#if NET35 || UNITY + try + { + result = ( TEnum ) Enum.Parse( typeof( TEnum ), asString, false ); + } + catch ( ArgumentException ex ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Name '{0}' is not member of enum type '{1}'.", + asString, + typeof( TEnum ) + ), + ex + ); + } #else - if ( !Enum.TryParse( asString, false, out result ) ) - { - throw new SerializationException( - String.Format( - CultureInfo.CurrentCulture, - "Name '{0}' is not member of enum type '{1}'.", - asString, - typeof( TEnum ) - ) - ); + if ( !Enum.TryParse( asString, false, out result ) ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Name '{0}' is not member of enum type '{1}'.", + asString, + typeof( TEnum ) + ) + ); + } +#endif // NET35 || UNITY } -#endif // NETFX_35 || UNITY return result; } @@ -252,10 +283,12 @@ ICustomizableEnumSerializer ICustomizableEnumSerializer.GetCopyAs( EnumSerializa internal abstract class UnityEnumMessagePackSerializer : NonGenericMessagePackSerializer, ICustomizableEnumSerializer { private readonly Type _underlyingType; + private readonly Dictionary _serializationMapping; + private readonly Dictionary _deserializationMapping; private EnumSerializationMethod _serializationMethod; // not readonly -- changed in cloned instance in GetCopyAs() protected UnityEnumMessagePackSerializer( SerializationContext ownerContext, Type targetType, EnumSerializationMethod serializationMethod ) - : base( ownerContext, targetType ) + : base( ownerContext, targetType, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { if ( !targetType.GetIsEnum() ) { @@ -266,6 +299,15 @@ protected UnityEnumMessagePackSerializer( SerializationContext ownerContext, Typ this._serializationMethod = serializationMethod; this._underlyingType = Enum.GetUnderlyingType( targetType ); + var members = Enum.GetValues( targetType ); + this._serializationMapping = new Dictionary( members.Length ); + this._deserializationMapping = new Dictionary( members.Length ); + foreach ( var member in members ) + { + var asString = ownerContext.EnumSerializationOptions.SafeNameTransformer( member.ToString() ); + this._serializationMapping[ member ] = asString; + this._deserializationMapping[ asString ] = member; + } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] @@ -277,7 +319,14 @@ protected internal sealed override void PackToCore( Packer packer, object object } else { - packer.PackString( objectTree.ToString() ); + string asString; + if ( !this._serializationMapping.TryGetValue( objectTree, out asString ) ) + { + // May be undefined value which should be numeric. + asString = objectTree.ToString(); + } + + packer.PackString( asString ); } } @@ -290,22 +339,29 @@ protected internal sealed override object UnpackFromCore( Unpacker unpacker ) { var asString = unpacker.LastReadData.AsString(); - try - { - return Enum.Parse( this.TargetType, asString, false ); - } - catch ( ArgumentException ex ) + object result; + if ( !this._deserializationMapping.TryGetValue( asString, out result ) ) { - throw new SerializationException( - String.Format( - CultureInfo.CurrentCulture, - "Name '{0}' is not member of enum type '{1}'.", - asString, - this.TargetType - ), - ex - ); + // May be undefined value which should be numeric, or PacakCasing. + try + { + result = Enum.Parse( this.TargetType, asString, false ); + } + catch ( ArgumentException ex ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Name '{0}' is not member of enum type '{1}'.", + asString, + this.TargetType + ), + ex + ); + } } + + return result; } else if ( unpacker.LastReadData.IsTypeOf( this._underlyingType ).GetValueOrDefault() ) { diff --git a/src/MsgPack/Serialization/EnumNameTransformers.cs b/src/MsgPack/Serialization/EnumNameTransformers.cs new file mode 100644 index 000000000..8bc6e7cfa --- /dev/null +++ b/src/MsgPack/Serialization/EnumNameTransformers.cs @@ -0,0 +1,62 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack.Serialization +{ + /// + /// Defines built-in, out-of-box handlers for . + /// + public static class EnumNameTransformers + { + private static readonly Func _lowerCamel = KeyNameTransformers.ToLowerCamel; + + /// + /// Gets the handler which transforms upper camel casing (PascalCasing) name to lower camel casing (camelCasing) name. + /// + /// + /// The handler which transforms upper camel casing (PascalCasing) name to lower camel casing (camelCasing) name. + /// + /// + /// This method uses based invariant culture to tranform casing, so non ASCII charactors may not be transformed correctly espetially surrogate pairs. + /// + public static Func LowerCamel + { + get { return _lowerCamel; } + } + + private static readonly Func _upperSnake = KeyNameTransformers.ToUpperSnake; + + /// + /// Gets the handler which transforms upper camel casing (PascalCasing) name to upper snake casing (UPPER_SNAKE_CASING) name. + /// + /// + /// The handler which transforms upper camel casing (PascalCasing) name to upper snake casing (UPPER_SNAKE_CASING) name. + /// + /// + /// This method uses based invariant culture to tranform casing, so non ASCII charactors may not be transformed correctly espetially surrogate pairs. + /// + public static Func UpperSnake + { + get { return _upperSnake; } + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/EnumSerializationOptions.cs b/src/MsgPack/Serialization/EnumSerializationOptions.cs new file mode 100644 index 000000000..369fb46cd --- /dev/null +++ b/src/MsgPack/Serialization/EnumSerializationOptions.cs @@ -0,0 +1,129 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Threading; + +namespace MsgPack.Serialization +{ + /// + /// Defines enum serialization options. + /// + public sealed class EnumSerializationOptions + { + private int _serializationMethod; + + /// + /// Gets or sets the to determine default serialization strategy of enum types. + /// + /// + /// The to determine default serialization strategy of enum types. + /// + /// The setting value is invalid as enum. + /// + /// A serialization strategy for specific member is determined as following: + /// + /// If the member is marked with and its value is not , then it will be used. + /// Otherwise, if the enum type itself is marked with , then it will be used. + /// Otherwise, the value of this property will be used. + /// + /// Note that the default value of this property is , it is not size efficient but tolerant to unexpected enum definition change. + /// + public EnumSerializationMethod SerializationMethod + { + get + { +#if DEBUG + Contract.Ensures( Enum.IsDefined( typeof( EnumSerializationMethod ), Contract.Result() ) ); +#endif // DEBUG + + return ( EnumSerializationMethod )Volatile.Read( ref this._serializationMethod ); + } + set + { + switch ( value ) + { + case EnumSerializationMethod.ByName: + case EnumSerializationMethod.ByUnderlyingValue: + { + break; + } + default: + { + throw new ArgumentOutOfRangeException( "value" ); + } + } + + Contract.EndContractBlock(); + + Volatile.Write( ref this._serializationMethod, ( int )value ); + } + } + + +#if !FEATURE_CONCURRENT + private volatile Func _nameTransformer; +#else + private Func _nameTransformer; +#endif // !FEATURE_CONCURRENT + + /// + /// Gets or sets the key name handler which enables dictionary key name customization. + /// + /// + /// The key name handler which enables dictionary key name customization. + /// The default value is null, which indicates that key name is not transformed. + /// + /// + public Func NameTransformer + { + get + { +#if !FEATURE_CONCURRENT + return this._nameTransformer; +#else + return Volatile.Read( ref this._nameTransformer ); +#endif // !FEATURE_CONCURRENT + } + set + { +#if !FEATURE_CONCURRENT + this._nameTransformer = value; +#else + Volatile.Write( ref this._nameTransformer, value ); +#endif // !FEATURE_CONCURRENT + } + } + + internal Func SafeNameTransformer + { + get { return this.NameTransformer ?? KeyNameTransformers.AsIs; } + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/ExtTypeCodeMapping.cs b/src/MsgPack/Serialization/ExtTypeCodeMapping.cs index 3934191a4..63be059fe 100644 --- a/src/MsgPack/Serialization/ExtTypeCodeMapping.cs +++ b/src/MsgPack/Serialization/ExtTypeCodeMapping.cs @@ -22,21 +22,21 @@ #define UNITY #endif -#if !NETFX_40 && !NETFX_35 && !UNITY && !SILVERLIGHT -#define NETFX_45 -#endif // !NETFX_40 && !NETFX_35 && !UNITY && !SILVERLIGHT +#if !NET40 && !NET35 && !UNITY && !SILVERLIGHT +#define NET45 +#endif // !NET40 && !NET35 && !UNITY && !SILVERLIGHT using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; -#if NETFX_45 +#if NET45 using System.Threading; -#endif // NETFX_45 +#endif // NET45 namespace MsgPack.Serialization { @@ -89,6 +89,7 @@ internal ExtTypeCodeMapping() this._syncRoot = new object(); this._index = new Dictionary( 2 ); this._types = new Dictionary( 2 ); + this.AddInternal( KnownExtTypeName.Timestamp, KnownExtTypeCode.Timestamp ); this.Add( KnownExtTypeName.MultidimensionalArray, KnownExtTypeCode.MultidimensionalArray ); } @@ -107,7 +108,11 @@ public bool Add( string name, byte typeCode ) { ValidateName( name ); ValidateTypeCode( typeCode ); + return this.AddInternal( name, typeCode ); + } + private bool AddInternal( string name, byte typeCode ) + { lock ( this._syncRoot ) { try @@ -177,9 +182,9 @@ public bool Remove( byte typeCode ) private void RemoveCore( string name, byte typeCode ) { -#if DEBUG && NETFX_45 +#if DEBUG && NET45 Contract.Assert( Monitor.IsEntered( this._syncRoot ) ); -#endif // DEBUG && NETFX_45 +#endif // DEBUG && NET45 var shouldBeTrue = this._types.Remove( typeCode ); Contract.Assert( shouldBeTrue ); shouldBeTrue = this._index.Remove( name ); @@ -244,4 +249,4 @@ private static void ValidateTypeCode( byte typeCode ) } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/FromExpression.ToMethod.cs b/src/MsgPack/Serialization/FromExpression.ToMethod.cs deleted file mode 100644 index 7942cc279..000000000 --- a/src/MsgPack/Serialization/FromExpression.ToMethod.cs +++ /dev/null @@ -1,254 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System; -using System.Globalization; -using System.Linq.Expressions; -using System.Reflection; - -namespace MsgPack.Serialization -{ - // This file generated from FromExpression.tt T4Template. - // Do not modify this file. Edit FromExpression.tt instead. - - partial class FromExpression - { - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Action > source ) - { - return ToMethodCore( source ); - } -#endif - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif -#if !WINDOWS_PHONE && !NETFX_35 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod( Expression< System.Func > source ) - { - return ToMethodCore( source ); - } -#endif - } -} - diff --git a/src/MsgPack/Serialization/FromExpression.ToMethod.tt b/src/MsgPack/Serialization/FromExpression.ToMethod.tt deleted file mode 100644 index d7a351ae3..000000000 --- a/src/MsgPack/Serialization/FromExpression.ToMethod.tt +++ /dev/null @@ -1,184 +0,0 @@ -<# -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#> -<#@ template debug="false" hostspecific="false" language="C#" #> -<#@ output extension=".cs" #> -<#@ assembly Name="System.Core" #> -<#@ import namespace="System" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Linq.Expressions" #> -<#@ import namespace="System.Reflection" #> -<#@ import namespace="System.Text" #> -<# -var __typeName = "FromExpression"; -var __actions = GetDelegates( typeof( object ).Assembly, "Action" ).Concat( GetDelegates( typeof( Enumerable ).Assembly, "Action" ) ).ToArray(); -var __funcs = GetDelegates( typeof( object ).Assembly, "Func" ).Concat( GetDelegates( typeof( Enumerable ).Assembly, "Func" ) ).ToArray(); -var __maxWindowsPhoneArity = 5; - -#> -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System; -using System.Globalization; -using System.Linq.Expressions; -using System.Reflection; - -namespace MsgPack.Serialization -{ - // This file generated from <#= __typeName #>.tt T4Template. - // Do not modify this file. Edit <#= __typeName #>.tt instead. - - partial class <#= __typeName #> - { -<# -foreach( Type __action in __actions ) -{ - var __notAvailableOnWP = __action.GetGenericArguments().Length >= __maxWindowsPhoneArity; - - if ( __notAvailableOnWP ) - { -#> -#if !WINDOWS_PHONE && !NETFX_35 -<# - } -#> - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod<#= GetCSharpGenericArgumentsToken( __action ) #>( Expression< <#= ToCSharpToken( __action ) #> > source ) - { - return ToMethodCore( source ); - } -<# - if ( __notAvailableOnWP ) - { -#> -#endif -<# - } -} -#> - -<# -foreach( Type __func in __funcs ) -{ - var __notAvailableOnWP = __func.GetGenericArguments().Length > __maxWindowsPhoneArity; - - if ( __notAvailableOnWP ) - { -#> -#if !WINDOWS_PHONE && !NETFX_35 -<# - } -#> - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )] - public static MethodInfo ToMethod<#= GetCSharpGenericArgumentsToken( __func ) #>( Expression< <#= ToCSharpToken( __func ) #> > source ) - { - return ToMethodCore( source ); - } -<# - if ( __notAvailableOnWP ) - { -#> -#endif -<# - } -} -#> - } -} - -<#+ -private static IEnumerable GetDelegates( Assembly assembly, string name ) -{ - var genericName = name + "`"; - return assembly.GetTypes().Where( t => t.Namespace == "System" ).Where( t => typeof( MulticastDelegate ).IsAssignableFrom( t ) ).Where( t => t.Name == name || t.Name.StartsWith( genericName, StringComparison.Ordinal ) ); -} - -private static string GetCSharpGenericArgumentsToken( Type type ) -{ - var buffer = new StringBuilder(); - BuildCSharpGenericArgumentsToken( type, buffer ); - return buffer.ToString(); -} - -private static void BuildCSharpGenericArgumentsToken( Type type, StringBuilder buffer ) -{ - if( !type.IsGenericType) - { - return; - } - - buffer.Append('<'); - - bool isFirst = true; - foreach( Type genericParameter in type.GetGenericArguments () ) - { - if( isFirst ) - { - isFirst = false; - } - else - { - buffer.Append( ',' ).Append( ' ' ); - } - - if( genericParameter.IsGenericParameter ) - { - buffer.Append( genericParameter.Name ); - } - else - { - buffer.Append( genericParameter.FullName ); - } - } - - buffer.Append( '>' );} - -private static string ToCSharpToken( Type type ) -{ - if( !type.IsGenericType ) - { - return type.FullName; - } - - StringBuilder buffer = new StringBuilder( type.FullName.Remove( type.FullName.IndexOf( '`' ) ) ); - - BuildCSharpGenericArgumentsToken( type, buffer ); - - return buffer.ToString(); -} -#> \ No newline at end of file diff --git a/src/MsgPack/Serialization/FromExpression.cs b/src/MsgPack/Serialization/FromExpression.cs deleted file mode 100644 index 7314e584f..000000000 --- a/src/MsgPack/Serialization/FromExpression.cs +++ /dev/null @@ -1,108 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2012 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System; -using System.Globalization; -using System.Linq.Expressions; -using System.Reflection; - -namespace MsgPack.Serialization -{ - // TODO: NLiblet - internal static partial class FromExpression - { - public static PropertyInfo ToProperty( Expression> source ) - { - return ToPropertyCore( source ); - } - - public static PropertyInfo ToProperty( Expression> source ) - { - return ToPropertyCore( source ); - } - - private static PropertyInfo ToPropertyCore( Expression source ) - { - if ( source == null ) - { - throw new ArgumentNullException( "source" ); - } - - var memberExpression = source.Body as MemberExpression; - if ( memberExpression == null ) - { - ThrowNotValidExpressionTypeException( source ); - } - - var property = memberExpression.Member as PropertyInfo; - if ( property == null ) - { - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Member '{0}' is not property.", memberExpression.Member ), "source" ); - } - - return property; - } - - private static MethodInfo ToMethodCore( Expression source ) - { - if ( source == null ) - { - throw new ArgumentNullException( "source" ); - } - - var methodCallExpression = source.Body as MethodCallExpression; - if ( methodCallExpression == null ) - { - ThrowNotValidExpressionTypeException( source ); - } - - return methodCallExpression.Method; - } - -#if DEBUG - public static MethodInfo ToOperator( Expression> source ) - { - if ( source == null ) - { - throw new ArgumentNullException( "source" ); - } - - var binaryExpression = source.Body as BinaryExpression; - if ( binaryExpression == null ) - { - ThrowNotValidExpressionTypeException( source ); - } - - return binaryExpression.Method; - } -#endif // DEBUG - - private static void ThrowNotValidExpressionTypeException( Expression source ) - { - throw new NotSupportedException( - String.Format( - CultureInfo.CurrentCulture, - "Specified expression '{0}' is too complex. Simple member reference expression is only supported. ", - source - ) - ); - } - } -} diff --git a/src/MsgPack/Serialization/ICustomizableEnumSerializer.cs b/src/MsgPack/Serialization/ICustomizableEnumSerializer.cs index caa9f7b9a..c59f6f949 100644 --- a/src/MsgPack/Serialization/ICustomizableEnumSerializer.cs +++ b/src/MsgPack/Serialization/ICustomizableEnumSerializer.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014 FUJIWARA, Yusuke +// Copyright (C) 2014-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; namespace MsgPack.Serialization @@ -25,7 +29,12 @@ namespace MsgPack.Serialization /// /// Represents customizable enum serializer. /// - internal interface ICustomizableEnumSerializer +#if UNITY && DEBUG + public +#else + internal +#endif + interface ICustomizableEnumSerializer { /// /// Gets a copy with specified method. @@ -34,4 +43,4 @@ internal interface ICustomizableEnumSerializer /// This instance or copied instance corresponds to the specified serialization method. ICustomizableEnumSerializer GetCopyAs( EnumSerializationMethod method ); } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/INilImplicationHandlerOnUnpackedParameter.cs b/src/MsgPack/Serialization/INilImplicationHandlerOnUnpackedParameter.cs index d2f686e4b..fc7ab5479 100644 --- a/src/MsgPack/Serialization/INilImplicationHandlerOnUnpackedParameter.cs +++ b/src/MsgPack/Serialization/INilImplicationHandlerOnUnpackedParameter.cs @@ -29,7 +29,7 @@ namespace MsgPack.Serialization /// /// Defines common interface for parameter of method and its template methods. /// -#if NETFX_35 || UNITY +#if NET35 || UNITY internal interface INilImplicationHandlerOnUnpackedParameter : INilImplicationHandlerParameter #else internal interface INilImplicationHandlerOnUnpackedParameter : INilImplicationHandlerParameter diff --git a/src/MsgPack/Serialization/ISerializerGeneratorConfiguration.cs b/src/MsgPack/Serialization/ISerializerGeneratorConfiguration.cs index 5dea92d92..dc3532a46 100644 --- a/src/MsgPack/Serialization/ISerializerGeneratorConfiguration.cs +++ b/src/MsgPack/Serialization/ISerializerGeneratorConfiguration.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -79,6 +79,23 @@ internal interface ISerializerGeneratorConfiguration /// bool WithNullableSerializers { get; set; } + /// + /// Gets the compatibility options. + /// + /// + /// The which stores compatibility options. This value will not be null. + /// + SerializationCompatibilityOptions CompatibilityOptions { get; } + + /// + /// Gets or sets a value indicating whether generated serializers will override async methods or not. + /// + /// + /// true if generated serializers will override async methods; otherwise, false. + /// Default is true. + /// + bool WithAsync { get; set; } + /// /// Validates this instance state. /// diff --git a/src/MsgPack/Serialization/IdentifierUtility.cs b/src/MsgPack/Serialization/IdentifierUtility.cs index 9a3735183..58161ed34 100644 --- a/src/MsgPack/Serialization/IdentifierUtility.cs +++ b/src/MsgPack/Serialization/IdentifierUtility.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Text; using MsgPack.Serialization.Reflection; @@ -27,7 +31,12 @@ namespace MsgPack.Serialization /// /// Utilities related to member/type ID. /// - internal static class IdentifierUtility +#if UNITY && DEBUG + public +#else + internal +#endif + static class IdentifierUtility { public static string EscapeTypeName( Type type ) { diff --git a/src/MsgPack/Serialization/IndividualFileCodeGenerationSink.cs b/src/MsgPack/Serialization/IndividualFileCodeGenerationSink.cs new file mode 100644 index 000000000..678ebb7cf --- /dev/null +++ b/src/MsgPack/Serialization/IndividualFileCodeGenerationSink.cs @@ -0,0 +1,41 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System.IO; + +namespace MsgPack.Serialization +{ + /// + /// A which emits each code to individual files. + /// + internal sealed class IndividualFileCodeGenerationSink : CodeGenerationSink + { + internal static readonly IndividualFileCodeGenerationSink Instance = new IndividualFileCodeGenerationSink(); + + private IndividualFileCodeGenerationSink() { } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally." )] + protected override void AssignTextWriterCore( SerializerCodeInformation codeInformation ) + { + Directory.CreateDirectory( codeInformation.Directory ); + codeInformation.SetFileWriter( Path.Combine( codeInformation.Directory, codeInformation.TypeFullName + codeInformation.FileExtension ) ); + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/KeyNameTransformers.cs b/src/MsgPack/Serialization/KeyNameTransformers.cs new file mode 100644 index 000000000..f24c9b4a9 --- /dev/null +++ b/src/MsgPack/Serialization/KeyNameTransformers.cs @@ -0,0 +1,111 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Text; + +namespace MsgPack.Serialization +{ +#if UNITY && DEBUG + public +#else + internal +#endif + static class KeyNameTransformers + { + public static readonly Func AsIs = key => key; + + public static string ToLowerCamel( string mayBeUpperCamel ) + { + if ( String.IsNullOrEmpty( mayBeUpperCamel ) ) + { + return mayBeUpperCamel; + } + + if ( !Char.IsUpper( mayBeUpperCamel[ 0 ] ) ) + { + return mayBeUpperCamel; + } + + var buffer = new StringBuilder( mayBeUpperCamel.Length ); + buffer.Append( Char.ToLowerInvariant( mayBeUpperCamel[ 0 ] ) ); + if ( mayBeUpperCamel.Length > 1 ) + { + buffer.Append( mayBeUpperCamel, 1, mayBeUpperCamel.Length - 1 ); + } + + return buffer.ToString(); + } + + public static string ToUpperSnake( string mayBeUpperCamel ) + { + if ( String.IsNullOrEmpty( mayBeUpperCamel ) ) + { + return mayBeUpperCamel; + } + + var buffer = new StringBuilder( mayBeUpperCamel.Length * 2 ); + char previous = '\0'; + int index = 0; + for ( ; index < mayBeUpperCamel.Length; index++ ) + { + var c = mayBeUpperCamel[ index ]; + if ( Char.IsUpper( c ) ) + { + buffer.Append( c ); + previous = c; + } + else + { + buffer.Append( Char.ToUpperInvariant( c ) ); + previous = c; + index++; + break; + } + } + + for ( ; index < mayBeUpperCamel.Length; index++ ) + { + var c = mayBeUpperCamel[ index ]; + if ( Char.IsUpper( c ) ) + { + if ( previous != '_' ) + { + buffer.Append( '_' ); + } + + buffer.Append( c ); + previous = c; + } + else + { + buffer.Append( Char.ToUpperInvariant( c ) ); + previous = c; + } + } + + return buffer.ToString(); + } + } +} diff --git a/src/MsgPack/Serialization/LazyDelegatingMessagePackSerializer`1.cs b/src/MsgPack/Serialization/LazyDelegatingMessagePackSerializer`1.cs index f4b62f2da..e51ad7910 100644 --- a/src/MsgPack/Serialization/LazyDelegatingMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/LazyDelegatingMessagePackSerializer`1.cs @@ -37,6 +37,11 @@ internal sealed class LazyDelegatingMessagePackSerializer : MessagePackSerial private readonly object _providerParameter; private MessagePackSerializer _delegated; + internal override SerializerCapabilities InternalGetCapabilities() + { + return this.GetDelegatedSerializer().Capabilities; + } + /// /// Initializes a new instance of the class. /// diff --git a/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.cs b/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.cs index fda5f478f..eb5259fcb 100644 --- a/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.cs +++ b/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.cs @@ -40,7 +40,7 @@ namespace MsgPack.Serialization /// You must use one-to-one relationship between type-code and the type. /// /// - [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] public sealed class MessagePackKnownTypeAttribute : Attribute, IPolymorphicKnownTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -89,7 +89,7 @@ public MessagePackKnownTypeAttribute( string typeCode, Type bindingType ) /// You must use one-to-one relationship between type-code and the type. /// /// - [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] public sealed class MessagePackKnownCollectionItemTypeAttribute : Attribute, IPolymorphicKnownTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -138,7 +138,7 @@ public MessagePackKnownCollectionItemTypeAttribute( string typeCode, Type bindin /// You must use one-to-one relationship between type-code and the type. /// /// - [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] public sealed class MessagePackKnownDictionaryKeyTypeAttribute : Attribute, IPolymorphicKnownTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -210,10 +210,8 @@ PolymorphismTarget IPolymorphicHelperAttribute.Target /// The binding for . /// public Type BindingType { get; private set; } - } - partial class MessagePackKnownTupleItemTypeAttribute : IPolymorphicTupleItemTypeAttribute { /// diff --git a/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.tt b/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.tt index d31775a4e..4c79f3242 100644 --- a/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.tt +++ b/src/MsgPack/Serialization/MessagePackKnownTypeAttributes.tt @@ -48,6 +48,7 @@ foreach( var item in }, Target = "Member", OmitConstructor = false, + CanQualifyType = true, }, new { @@ -60,6 +61,7 @@ foreach( var item in }, Target = "CollectionItem", OmitConstructor = false, + CanQualifyType = true, }, new { @@ -72,6 +74,7 @@ foreach( var item in }, Target = "DictionaryKey", OmitConstructor = false, + CanQualifyType = true, }, new { @@ -84,6 +87,7 @@ foreach( var item in }, Target = "TupleItem", OmitConstructor = true, + CanQualifyType = false, }, } ) @@ -110,7 +114,20 @@ foreach( var item in /// You must use one-to-one relationship between type-code and the type. /// /// +<# + if ( item.CanQualifyType ) + { +#> + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] +<# + } + else + { +#> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true )] +<# + } +#> public sealed <#= item.OmitConstructor ? "partial " : String.Empty #>class <#= typeName #> : Attribute, IPolymorphicKnownTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -133,11 +150,11 @@ foreach( var item in /// The binding for . /// public Type BindingType { get; private set; } - <# if ( !item.OmitConstructor ) { #> + /// /// Initializes a new instance of the class. /// @@ -156,7 +173,6 @@ foreach( var item in <# } #> - partial class MessagePackKnownTupleItemTypeAttribute : IPolymorphicTupleItemTypeAttribute { /// diff --git a/src/MsgPack/Serialization/MessagePackMemberAttribute.cs b/src/MsgPack/Serialization/MessagePackMemberAttribute.cs index f59f7773d..2a8a78457 100644 --- a/src/MsgPack/Serialization/MessagePackMemberAttribute.cs +++ b/src/MsgPack/Serialization/MessagePackMemberAttribute.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT namespace MsgPack.Serialization { diff --git a/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.cs b/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.cs index c02709f36..de63624dd 100644 --- a/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.cs +++ b/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.cs @@ -49,7 +49,7 @@ namespace MsgPack.Serialization /// It mitigate chance of potential exploits. /// /// - [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property )] + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property )] public sealed class MessagePackRuntimeTypeAttribute : Attribute, IPolymorphicRuntimeTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -57,6 +57,40 @@ PolymorphismTarget IPolymorphicHelperAttribute.Target get { return PolymorphismTarget.Member; } } + /// + /// Gets or sets the type which implement type verfier method. + /// + /// + /// The type which implement type verfier method. + /// The default is null, which indicates that no type verification will be processed. + /// + public Type VerifierType + { + get; + set; + } + + /// + /// Gets or sets the name of the method which implement type verification. + /// + /// + /// The name of the method which implement type verification + /// The default is null, which indicates that no type verification will be processed. + /// + /// + /// The type verfication method must be following: + /// + /// The method has just only one parameter, which type must be . + /// The method must return . true indicates the verification result is OK; false indicates not OK. + /// The method can be static method or instance method. The accessibility is not limited. + /// + /// + public string VerifierMethodName + { + get; + set; + } + /// /// Initializes a new instance of the class. /// @@ -88,7 +122,7 @@ public MessagePackRuntimeTypeAttribute() /// It mitigate chance of potential exploits. /// /// - [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property )] + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property )] public sealed class MessagePackRuntimeCollectionItemTypeAttribute : Attribute, IPolymorphicRuntimeTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -96,6 +130,40 @@ PolymorphismTarget IPolymorphicHelperAttribute.Target get { return PolymorphismTarget.CollectionItem; } } + /// + /// Gets or sets the type which implement type verfier method. + /// + /// + /// The type which implement type verfier method. + /// The default is null, which indicates that no type verification will be processed. + /// + public Type VerifierType + { + get; + set; + } + + /// + /// Gets or sets the name of the method which implement type verification. + /// + /// + /// The name of the method which implement type verification + /// The default is null, which indicates that no type verification will be processed. + /// + /// + /// The type verfication method must be following: + /// + /// The method has just only one parameter, which type must be . + /// The method must return . true indicates the verification result is OK; false indicates not OK. + /// The method can be static method or instance method. The accessibility is not limited. + /// + /// + public string VerifierMethodName + { + get; + set; + } + /// /// Initializes a new instance of the class. /// @@ -127,7 +195,7 @@ public MessagePackRuntimeCollectionItemTypeAttribute() /// It mitigate chance of potential exploits. /// /// - [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property )] + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property )] public sealed class MessagePackRuntimeDictionaryKeyTypeAttribute : Attribute, IPolymorphicRuntimeTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -135,6 +203,40 @@ PolymorphismTarget IPolymorphicHelperAttribute.Target get { return PolymorphismTarget.DictionaryKey; } } + /// + /// Gets or sets the type which implement type verfier method. + /// + /// + /// The type which implement type verfier method. + /// The default is null, which indicates that no type verification will be processed. + /// + public Type VerifierType + { + get; + set; + } + + /// + /// Gets or sets the name of the method which implement type verification. + /// + /// + /// The name of the method which implement type verification + /// The default is null, which indicates that no type verification will be processed. + /// + /// + /// The type verfication method must be following: + /// + /// The method has just only one parameter, which type must be . + /// The method must return . true indicates the verification result is OK; false indicates not OK. + /// The method can be static method or instance method. The accessibility is not limited. + /// + /// + public string VerifierMethodName + { + get; + set; + } + /// /// Initializes a new instance of the class. /// @@ -174,8 +276,40 @@ PolymorphismTarget IPolymorphicHelperAttribute.Target get { return PolymorphismTarget.TupleItem; } } - } + /// + /// Gets or sets the type which implement type verfier method. + /// + /// + /// The type which implement type verfier method. + /// The default is null, which indicates that no type verification will be processed. + /// + public Type VerifierType + { + get; + set; + } + /// + /// Gets or sets the name of the method which implement type verification. + /// + /// + /// The name of the method which implement type verification + /// The default is null, which indicates that no type verification will be processed. + /// + /// + /// The type verfication method must be following: + /// + /// The method has just only one parameter, which type must be . + /// The method must return . true indicates the verification result is OK; false indicates not OK. + /// The method can be static method or instance method. The accessibility is not limited. + /// + /// + public string VerifierMethodName + { + get; + set; + } + } partial class MessagePackRuntimeTupleItemTypeAttribute : IPolymorphicTupleItemTypeAttribute { diff --git a/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.tt b/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.tt index 8ed200726..24220c61a 100644 --- a/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.tt +++ b/src/MsgPack/Serialization/MessagePackRuntimeTypeAttributes.tt @@ -48,6 +48,7 @@ foreach( var item in Target = "Member", OmitConstructor = false, AllowMulitiple = false, + CanQualifyType = true, }, new { @@ -61,6 +62,7 @@ foreach( var item in Target = "CollectionItem", OmitConstructor = false, AllowMulitiple = false, + CanQualifyType = true, }, new { @@ -74,6 +76,7 @@ foreach( var item in Target = "DictionaryKey", OmitConstructor = false, AllowMulitiple = false, + CanQualifyType = true, }, new { @@ -87,6 +90,7 @@ foreach( var item in Target = "TupleItem", OmitConstructor = true, AllowMulitiple = true, + CanQualifyType = false, }, } ) @@ -123,7 +127,20 @@ foreach( var item in /// It mitigate chance of potential exploits. /// /// +<# + if ( item.CanQualifyType ) + { +#> + [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property<#= item.AllowMulitiple ? ", AllowMultiple = true" : String.Empty #> )] +<# + } + else + { +#> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property<#= item.AllowMulitiple ? ", AllowMultiple = true" : String.Empty #> )] +<# + } +#> public sealed <#= item.OmitConstructor ? "partial " : String.Empty #>class <#= typeName #> : Attribute, IPolymorphicRuntimeTypeAttribute { PolymorphismTarget IPolymorphicHelperAttribute.Target @@ -131,10 +148,44 @@ foreach( var item in get { return PolymorphismTarget.<#= item.Target #>; } } + /// + /// Gets or sets the type which implement type verfier method. + /// + /// + /// The type which implement type verfier method. + /// The default is null, which indicates that no type verification will be processed. + /// + public Type VerifierType + { + get; + set; + } + + /// + /// Gets or sets the name of the method which implement type verification. + /// + /// + /// The name of the method which implement type verification + /// The default is null, which indicates that no type verification will be processed. + /// + /// + /// The type verfication method must be following: + /// + /// The method has just only one parameter, which type must be . + /// The method must return . true indicates the verification result is OK; false indicates not OK. + /// The method can be static method or instance method. The accessibility is not limited. + /// + /// + public string VerifierMethodName + { + get; + set; + } <# if ( !item.OmitConstructor ) { #> + /// /// Initializes a new instance of the class. /// @@ -149,7 +200,6 @@ foreach( var item in <# } #> - partial class MessagePackRuntimeTupleItemTypeAttribute : IPolymorphicTupleItemTypeAttribute { /// diff --git a/src/MsgPack/Serialization/MessagePackSerializer.Factories.cs b/src/MsgPack/Serialization/MessagePackSerializer.Factories.cs index 1e26d0ad6..18ad69a00 100644 --- a/src/MsgPack/Serialization/MessagePackSerializer.Factories.cs +++ b/src/MsgPack/Serialization/MessagePackSerializer.Factories.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,40 +16,41 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY -#define AOT #endif -#if !AOT && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 -#define FEATURE_EMIT -#endif // !AOT && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 - using System; using System.IO; using System.Globalization; +#if UNITY || WINDOWS_PHONE || WINDOWS_UWP +using System.Linq; +using System.Reflection; +#endif // UNITY || WINDOWS_PHONE || WINDOWS_UWP using System.Runtime.Serialization; using MsgPack.Serialization.DefaultSerializers; using MsgPack.Serialization.ReflectionSerializers; -#if !SILVERLIGHT && !NETFX_35 && !UNITY +#if !SILVERLIGHT && !NET35 && !UNITY using System.Collections.Concurrent; -#else // !SILVERLIGHT && !NETFX_35 && !UNITY +#else // !SILVERLIGHT && !NET35 && !UNITY using System.Collections.Generic; -#endif // !SILVERLIGHT && !NETFX_35 && !UNITY -#if CORE_CLR || UNITY +#endif // !SILVERLIGHT && !NET35 && !UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY -#if NETFX_CORE || WINDOWS_PHONE -using System.Linq.Expressions; -#endif +#endif // FEATURE_MPCONTRACT #if FEATURE_EMIT using MsgPack.Serialization.AbstractSerializers; +#if !NETSTANDARD1_3 using MsgPack.Serialization.CodeDomSerializers; +#endif // !NETSTANDARD1_3 using MsgPack.Serialization.EmittingSerializers; #endif // FEATURE_EMIT @@ -203,29 +204,37 @@ public static MessagePackSerializer Get( SerializationContext context, obj return context.GetSerializer( providerParameter ); } - internal static MessagePackSerializer CreateInternal( SerializationContext context, PolymorphismSchema schema ) +#if UNITY + [Preserve( AllMembers = true )] +#endif +#if UNITY && DEBUG + public +#else + internal +#endif + static MessagePackSerializer CreateInternal( SerializationContext context, PolymorphismSchema schema ) { #if DEBUG Contract.Ensures( Contract.Result>() != null ); #endif // DEBUG -#if DEBUG && !AOT && !SILVERLIGHT - SerializerDebugging.TraceEvent( +#if DEBUG && FEATURE_EMIT + SerializerDebugging.TraceEmitEvent( "SerializationContext::CreateInternal<{0}>(@{1}, {2})", typeof( T ), context.GetHashCode(), schema == null ? "null" : schema.DebugString ); -#endif // DEBUG && !AOT && !SILVERLIGHT +#endif // DEBUG && FEATURE_EMIT Type concreteType = null; CollectionTraits collectionTraits = -#if AOT - typeof( T ).GetCollectionTraits( CollectionTraitOptions.None ); +#if UNITY + typeof( T ).GetCollectionTraits( CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); #else - typeof( T ).GetCollectionTraits( CollectionTraitOptions.Full ); -#endif // AOT + typeof( T ).GetCollectionTraits( CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); +#endif // UNITY if ( typeof( T ).GetIsAbstract() || typeof( T ).GetIsInterface() ) { @@ -252,9 +261,11 @@ internal static MessagePackSerializer CreateInternal( SerializationContext ISerializerBuilder builder; switch ( context.SerializerOptions.EmitterFlavor ) { +#if !NETSTANDARD1_3 case EmitterFlavor.CodeDomBased: { - if ( !SerializerDebugging.OnTheFlyCodeDomEnabled ) +#if DEBUG + if ( !SerializerDebugging.OnTheFlyCodeGenerationEnabled ) { throw new NotSupportedException( String.Format( @@ -267,7 +278,11 @@ internal static MessagePackSerializer CreateInternal( SerializationContext builder = new CodeDomSerializerBuilder( typeof( T ), collectionTraits ); break; +#else // DEBUG + throw new NotSupportedException(); +#endif // DEBUG } +#endif // !NETSTANDARD1_3 case EmitterFlavor.FieldBased: { builder = new AssemblyBuilderSerializerBuilder( typeof( T ), collectionTraits ); @@ -288,12 +303,12 @@ internal static MessagePackSerializer CreateInternal( SerializationContext } #if !UNITY -#if !SILVERLIGHT && !NETFX_35 +#if !SILVERLIGHT && !NET35 private static readonly ConcurrentDictionary> _creatorCache = new ConcurrentDictionary>(); #else private static readonly object _syncRoot = new object(); private static readonly Dictionary> _creatorCache = new Dictionary>(); -#endif // !SILVERLIGHT && !NETFX_35 +#endif // !SILVERLIGHT && !NET35 #endif // !UNITY /// @@ -349,7 +364,7 @@ public static MessagePackSerializer Create( Type targetType, SerializationContex Contract.Ensures( Contract.Result() != null ); #endif // DEBUG -#if AOT +#if UNITY || WINDOWS_PHONE || WINDOWS_UWP return CreateInternal( context, targetType, null ); #else // MPS.Create should always return new instance, and creator delegate should be cached for performance. @@ -363,7 +378,7 @@ public static MessagePackSerializer Create( Type targetType, SerializationContex typeof( Func ) ) as Func ); -#elif SILVERLIGHT || NETFX_35 +#elif SILVERLIGHT || NET35 Func factory; lock ( _syncRoot ) @@ -400,7 +415,7 @@ public static MessagePackSerializer Create( Type targetType, SerializationContex ); #endif // NETSTANDARD1_1 || NETSTANDARD1_3 return factory( context ); -#endif // AOT +#endif // UNITY || WINDOWS_PHONE || WINDOWS_UWP } /// @@ -527,11 +542,12 @@ public static MessagePackSerializer Get( Type targetType, SerializationContext c return context.GetSerializer( targetType, providerParameter ); } -#if AOT +#if UNITY || WINDOWS_PHONE || WINDOWS_UWP private static readonly System.Reflection.MethodInfo CreateInternal_2 = - typeof( MessagePackSerializer ).GetRuntimeMethod( - "CreateInternal", - new []{ typeof( SerializationContext ), typeof( PolymorphismSchema ) } + typeof( MessagePackSerializer ).GetRuntimeMethods() + .Single( m => + m.Name == "CreateInternal" + && m.GetParameterTypes().SequenceEqual( new []{ typeof( SerializationContext ), typeof( PolymorphismSchema ) } ) ); internal static MessagePackSerializer CreateInternal( SerializationContext context, Type targetType, PolymorphismSchema schema ) @@ -550,7 +566,7 @@ internal static MessagePackSerializer CreateInternal( SerializationContext conte as Func )( context, schema ) as MessagePackSerializer; #endif // UNITY } -#endif // AOT +#endif // UNITY || WINDOWS_PHONE || WINDOWS_UWP internal static MessagePackSerializer CreateReflectionInternal( SerializationContext context, Type concreteType, PolymorphismSchema schema ) { @@ -572,9 +588,9 @@ internal static MessagePackSerializer CreateReflectionInternal( Serializat ValidateType( typeof( T ) ); var traits = #if !UNITY - typeof( T ).GetCollectionTraits( CollectionTraitOptions.WithAddMethod ); + typeof( T ).GetCollectionTraits( CollectionTraitOptions.WithAddMethod, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); #else - typeof( T ).GetCollectionTraits( CollectionTraitOptions.WithAddMethod | CollectionTraitOptions.WithCountPropertyGetter ); + typeof( T ).GetCollectionTraits( CollectionTraitOptions.WithAddMethod | CollectionTraitOptions.WithCountPropertyGetter, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); #endif switch ( traits.CollectionType ) { @@ -597,7 +613,7 @@ internal static MessagePackSerializer CreateReflectionInternal( Serializat { return ReflectionSerializerHelper.CreateReflectionEnumMessagePackSerializer( context ); } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY if ( TupleItems.IsTuple( typeof( T ) ) ) { return @@ -606,9 +622,11 @@ internal static MessagePackSerializer CreateReflectionInternal( Serializat ( schema ?? PolymorphismSchema.Default ).ChildSchemaList ); } -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY - return new ReflectionObjectMessagePackSerializer( context ); + SerializationTarget.VerifyType( typeof( T ) ); + var target = SerializationTarget.Prepare( context, typeof( T ) ); + return new ReflectionObjectMessagePackSerializer( context, target, target.GetCapabilitiesForObject() ); } } } @@ -660,6 +678,25 @@ public static MessagePackObject UnpackMessagePackObject( Stream stream ) return _singleTonMpoDeserializer.Unpack( stream ); } + /// + /// Directly deserialize specified MessagePack byte array as tree. + /// + /// The stream which contains deserializing data. + /// A which is root of the deserialized MessagePack object tree. + /// + /// is null. + /// + /// + /// This method is convinient wrapper for for . + /// + /// You cannot override this method behavior because this method uses private instead of default context which is able to be accessed via . + /// + /// + public static MessagePackObject UnpackMessagePackObject( byte[] buffer ) + { + return _singleTonMpoDeserializer.UnpackSingleObject( buffer ); + } + /// /// Try to prepare specified type for some AOT(Ahead-Of-Time) compilation environment. /// If the type will be used in collection or dictionary, use and/or instead. @@ -755,6 +792,6 @@ private static void PrepareTypeCore( SerializationContext dummyContext ) // Ensure Dictionary is work. AotHelper.PrepareEqualityComparer(); } -#endif // UNITY || UNITY +#endif // UNITY } } diff --git a/src/MsgPack/Serialization/MessagePackSerializer.cs b/src/MsgPack/Serialization/MessagePackSerializer.cs index aa69da881..a9beecb8d 100644 --- a/src/MsgPack/Serialization/MessagePackSerializer.cs +++ b/src/MsgPack/Serialization/MessagePackSerializer.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; #if FEATURE_TAP using System.Threading; @@ -37,6 +41,15 @@ namespace MsgPack.Serialization public abstract partial class MessagePackSerializer : IMessagePackSingleObjectSerializer #pragma warning restore 0618 { + internal static readonly UnpackerOptions DefaultUnpackerOptions = new UnpackerOptions { ValidationLevel = UnpackerValidationLevel.None }; + +#if UNITY && DEBUG + public +#else + internal +#endif + const int BufferSize = 256; + private readonly SerializationContext _ownerContext; /// @@ -73,7 +86,13 @@ protected internal PackerCompatibilityOptions PackerCompatibilityOptions /// public SerializerCapabilities Capabilities { - get { return this._capabilities; } + get { return this.InternalGetCapabilities(); } + } + + // For LazyDelegatingMessagePackSerializer + internal virtual SerializerCapabilities InternalGetCapabilities() + { + return this._capabilities; } /// @@ -114,6 +133,10 @@ public void PackTo( Packer packer, object objectTree ) /// /// The deserialized object. /// + /// + /// You must call at least once in advance. + /// Or, you will get a default value of the object. + /// /// public object UnpackFrom( Unpacker unpacker ) { @@ -229,6 +252,10 @@ public Task PackToAsync( Packer packer, object objectTree, CancellationToken can /// /// The type of deserializing is not serializable even if it can be serialized. /// + /// + /// You must call at least once in advance. + /// Or, you will get a default value of the object. + /// /// public Task UnpackFromAsync( Unpacker unpacker, CancellationToken cancellationToken ) { diff --git a/src/MsgPack/Serialization/MessagePackSerializerExtensions.cs b/src/MsgPack/Serialization/MessagePackSerializerExtensions.cs index fe61d874a..4b4a89851 100644 --- a/src/MsgPack/Serialization/MessagePackSerializerExtensions.cs +++ b/src/MsgPack/Serialization/MessagePackSerializerExtensions.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014 FUJIWARA, Yusuke +// Copyright (C) 2014-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -79,7 +79,7 @@ public static void Pack( this MessagePackSerializer source, Stream stream, objec } /// - /// Deserialize object from the . + /// Deserializes object from the . /// /// object. /// Source . @@ -112,5 +112,131 @@ public static object Unpack( this MessagePackSerializer source, Stream stream ) return source.UnpackFrom( unpacker ); } + + /// + /// Serializes object as a single . + /// + /// object. + /// The object to be serialized. + /// . + /// + /// is null. + /// + /// + /// Failed to serialize. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "obj is appropriate for this context." )] + public static MessagePackObject ToMessagePackObject( this MessagePackSerializer source, object obj ) + { + if ( source == null ) + { + throw new ArgumentNullException( "source" ); + } + + using ( var buffer = new MemoryStream() ) + { + source.Pack( buffer, obj ); + buffer.Position = 0; + return Unpacking.UnpackObject( buffer ); + } + } + + /// + /// Serializes object as a single . + /// + /// The type of the object to be serialized. + /// object. + /// The object to be serialized. + /// . + /// + /// is null. + /// + /// + /// Failed to serialize. + /// + public static MessagePackObject ToMessagePackObject( this MessagePackSerializer source, T obj ) + { + if ( source == null ) + { + throw new ArgumentNullException( "source" ); + } + + using ( var buffer = new MemoryStream() ) + { + source.Pack( buffer, obj ); + buffer.Position = 0; + return Unpacking.UnpackObject( buffer ); + } + } + + /// + /// Deserializes object from a single . + /// + /// object. + /// The which represents deserializing object structructure. + /// A deserialized object. This value can be null. + /// + /// is null. + /// + /// + /// Failed to deserialize. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2202:DoNotDisposeObjectsMultipleTimes", Justification = "ownsStream: false" )] + public static object FromMessagePackObject( this MessagePackSerializer source, MessagePackObject mpo ) + { + if ( source == null ) + { + throw new ArgumentNullException( "source" ); + } + + // This idea is borrowed from @TSnake41 + using ( var buffer = new MemoryStream() ) + { + using ( var packer = Packer.Create( buffer, PackerCompatibilityOptions.None, ownsStream: false ) ) + { + mpo.PackToMessage( packer, null ); + } + + buffer.Position = 0; + + return source.Unpack( buffer ); + } + } + + /// + /// Deserializes object from a single . + /// + /// The type of the object to be deserialized. + /// object. + /// The which represents deserializing object structructure. + /// A deserialized object. This value can be null. + /// + /// is null. + /// + /// + /// Failed to deserialize. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2202:DoNotDisposeObjectsMultipleTimes", Justification = "ownsStream: false" )] + public static T FromMessagePackObject( this MessagePackSerializer source, MessagePackObject mpo ) + { + if ( source == null ) + { + throw new ArgumentNullException( "source" ); + } + + // This idea is borrowed from @TSnake41 + using ( var buffer = new MemoryStream() ) + { + using ( var packer = Packer.Create( buffer, PackerCompatibilityOptions.None, ownsStream: false ) ) + { + mpo.PackToMessage( packer, null ); + } + + buffer.Position = 0; + + return source.Unpack( buffer ); + } + } } } + diff --git a/src/MsgPack/Serialization/MessagePackSerializerProvider.cs b/src/MsgPack/Serialization/MessagePackSerializerProvider.cs index 98a4e0cbd..0d9923147 100644 --- a/src/MsgPack/Serialization/MessagePackSerializerProvider.cs +++ b/src/MsgPack/Serialization/MessagePackSerializerProvider.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014 FUJIWARA, Yusuke +// Copyright (C) 2014-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,6 +18,10 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; namespace MsgPack.Serialization @@ -25,7 +29,12 @@ namespace MsgPack.Serialization /// /// Defines basic features and interfaces for serializer provider which is stored in repository and controlls returning serializer with its own parameter. /// - internal abstract class MessagePackSerializerProvider +#if UNITY && DEBUG + public +#else + internal +#endif + abstract class MessagePackSerializerProvider { /// /// Initializes a new instance of the class. @@ -40,4 +49,4 @@ protected MessagePackSerializerProvider() { } /// A serializer object for specified parameter. public abstract object Get( SerializationContext context, object providerParameter ); } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/MessagePackSerializer`1.cs b/src/MsgPack/Serialization/MessagePackSerializer`1.cs index 390be682f..3bebc04a7 100644 --- a/src/MsgPack/Serialization/MessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/MessagePackSerializer`1.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -25,7 +28,6 @@ using System; using System.Globalization; using System.IO; -using System.Reflection; #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; @@ -51,7 +53,7 @@ namespace MsgPack.Serialization public abstract class MessagePackSerializer : MessagePackSerializer { // ReSharper disable once StaticFieldInGenericType - private static readonly bool _isNullable = JudgeNullable(); + private static readonly bool IsNullable = JudgeNullable(); /// /// Initializes a new instance of the class with . @@ -59,7 +61,7 @@ public abstract class MessagePackSerializer : MessagePackSerializer /// /// This method supports backword compatibility with 0.3. /// - [Obsolete( "Use MessagePackSerializer (SerlaizationContext) instead." )] + [Obsolete( "Use MessagePackSerializer (SerializationContext) instead." )] protected MessagePackSerializer() : this( PackerCompatibilityOptions.Classic ) { } /// @@ -69,7 +71,7 @@ protected MessagePackSerializer() : this( PackerCompatibilityOptions.Classic ) { /// /// This method supports backword compatibility with 0.4. /// - [Obsolete( "Use MessagePackSerializer (SerlaizationContext, PackerCompatibilityOptions) instead." )] + [Obsolete( "Use MessagePackSerializer (SerializationContext, PackerCompatibilityOptions) instead." )] protected MessagePackSerializer( PackerCompatibilityOptions packerCompatibilityOptions ) : this( null, packerCompatibilityOptions ) { } @@ -141,7 +143,7 @@ private static bool JudgeNullable() private static SerializerCapabilities InferCapatibity() { var result = SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom; - var traits = typeof( T ).GetCollectionTraits( CollectionTraitOptions.WithAddMethod); + var traits = typeof( T ).GetCollectionTraits( CollectionTraitOptions.WithAddMethod, allowNonCollectionEnumerableTypes: false ); if ( traits.AddMethod != null ) { result |= SerializerCapabilities.UnpackTo; @@ -215,9 +217,17 @@ public Task PackAsync( Stream stream, T objectTree ) /// is not serializable even if it can be deserialized. /// /// - public Task PackAsync( Stream stream, T objectTree, CancellationToken cancellationToken ) + public async Task PackAsync( Stream stream, T objectTree, CancellationToken cancellationToken ) { - return this.PackToAsync( Packer.Create( stream, this.PackerCompatibilityOptions, PackerUnpackerStreamOptions.SingletonForAsync ), objectTree, cancellationToken ); + var packer = Packer.Create( stream, this.PackerCompatibilityOptions, PackerUnpackerStreamOptions.SingletonForAsyncPacking ); + try + { + await this.PackToAsync( packer, objectTree, cancellationToken ).ConfigureAwait( false ); + } + finally + { + await packer.FlushAsync( cancellationToken ).ConfigureAwait( false ); + } } #endif // FEATURE_TAP @@ -246,7 +256,7 @@ public Task PackAsync( Stream stream, T objectTree, CancellationToken cancellati public T Unpack( Stream stream ) { // Unpacker does not have finalizer, so just avoiding unpacker disposing prevents stream closing. - var unpacker = Unpacker.Create( stream ); + var unpacker = Unpacker.Create( stream, PackerUnpackerStreamOptions.None, DefaultUnpackerOptions ); if ( !unpacker.Read() ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); @@ -313,7 +323,8 @@ public Task UnpackAsync( Stream stream ) /// public async Task UnpackAsync( Stream stream, CancellationToken cancellationToken ) { - var unpacker = Unpacker.Create( stream ); + // Unpacker does not have finalizer, so just avoiding unpacker disposing prevents stream closing. + var unpacker = Unpacker.Create( stream, PackerUnpackerStreamOptions.SingletonForAsyncUnpacking, DefaultUnpackerOptions ); if ( !( await unpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); @@ -480,6 +491,10 @@ protected internal virtual Task PackToAsyncCore( Packer packer, T objectTree, Ca /// /// is not serializable even if it can be serialized. /// + /// + /// You must call at least once in advance. + /// Or, you will get a default value of . + /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] public new T UnpackFrom( Unpacker unpacker ) @@ -512,12 +527,12 @@ protected internal virtual Task PackToAsyncCore( Packer packer, T objectTree, Ca /// The implementation of this class returns null for nullable types (that is, all reference types and ); otherwise, throws . /// /// - /// Custom serializers can override this method to provide custom nil representation. For example, built-in serializer overrides this method to return instead of null. + /// Custom serializers can override this method to provide custom nil representation. For example, built-in DBNull serializer overrides this method to return DBNull.Value instead of null. /// /// protected internal virtual T UnpackNil() { - if ( !_isNullable ) + if ( !IsNullable ) { ThrowNewValueTypeCannotBeNullException(); } @@ -571,6 +586,10 @@ protected internal virtual T UnpackNil() /// /// is not serializable even if it can be serialized. /// + /// + /// You must call at least once in advance. + /// Or, you will get a default value of . + /// /// public Task UnpackFromAsync( Unpacker unpacker ) { @@ -849,13 +868,44 @@ protected internal virtual Task UnpackToAsyncCore( Unpacker unpacker, T collecti /// public byte[] PackSingleObject( T objectTree ) { - using ( var buffer = new MemoryStream() ) + var segment = this.PackSingleObjectAsBytes( objectTree ); + + if ( segment.Count == segment.Array.Length ) + { + return segment.Array; + } + else { - this.Pack( buffer, objectTree ); - return buffer.ToArray(); + var result = new byte[ segment.Count ]; + Buffer.BlockCopy( segment.Array, segment.Offset, result, 0, segment.Count ); + return result; } } + /// + /// Serializes specified object to the of . + /// + /// Object to be serialized. + /// An array of which stores serialized value. + /// + /// Failed to serialize object. + /// + /// + /// is not serializable even if it can be deserialized. + /// + /// + /// This method is more efficient than because of less copying. + /// + /// + public ArraySegment PackSingleObjectAsBytes( T objectTree ) + { + // Packer does not have finalizer, so just avoiding unpacker disposing prevents stream closing. + var packer = Packer.Create( BufferManager.NewByteBuffer( BufferSize ), /* allowExpansion */true, this.PackerCompatibilityOptions ); + + this.PackTo( packer, objectTree ); + return packer.GetResultBytes(); + } + #if FEATURE_TAP /// @@ -896,13 +946,46 @@ public Task PackSingleObjectAsync( T objectTree ) /// public async Task PackSingleObjectAsync( T objectTree, CancellationToken cancellationToken ) { - using ( var buffer = new MemoryStream() ) + var segment = await this.PackSingleObjectAsBytesAsync( objectTree, cancellationToken ).ConfigureAwait( false ); + if ( segment.Count == segment.Array.Length ) { - await this.PackAsync( buffer, objectTree, cancellationToken ).ConfigureAwait( false ); - return buffer.ToArray(); + return segment.Array; + } + else + { + var result = new byte[ segment.Count ]; + Buffer.BlockCopy( segment.Array, segment.Offset, result, 0, segment.Count ); + return result; } } + /// + /// Serializes specified object to the of asynchronously. + /// + /// Object to be serialized. + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains an array of which stores serialized value. + /// + /// + /// Failed to serialize object. + /// + /// + /// is not serializable even if it can be deserialized. + /// + /// + /// This method is more efficient than because of less copying. + /// + /// + public async Task> PackSingleObjectAsBytesAsync( T objectTree, CancellationToken cancellationToken ) + { + // Packer does not have finalizer, so just avoiding unpacker disposing prevents stream closing. + var packer = Packer.Create( BufferManager.NewByteBuffer( BufferSize ), /* allowExpansion */true, this.PackerCompatibilityOptions ); + + await this.PackToAsync( packer, objectTree, cancellationToken ).ConfigureAwait( false ); + return packer.GetResultBytes(); + } #endif // FEATURE_TAP /// @@ -943,11 +1026,16 @@ public async Task PackSingleObjectAsync( T objectTree, CancellationToken ThrowArgumentNullException( "buffer" ); } + // Unpacker does not have finalizer, so just avoiding unpacker disposing prevents stream closing. // ReSharper disable once AssignNullToNotNullAttribute - using ( var stream = new MemoryStream( buffer ) ) + var unpacker = Unpacker.Create( buffer, DefaultUnpackerOptions ); + + if ( !unpacker.Read() ) { - return this.Unpack( stream ); + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } + + return this.UnpackFrom( unpacker ); } #if FEATURE_TAP @@ -1025,18 +1113,23 @@ public Task UnpackSingleObjectAsync( byte[] buffer ) /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] - public new async Task UnpackSingleObjectAsync( byte[] buffer, CancellationToken cancellationToken ) + public new Task UnpackSingleObjectAsync( byte[] buffer, CancellationToken cancellationToken ) { if ( buffer == null ) { ThrowArgumentNullException( "buffer" ); } + // Unpacker does not have finalizer, so just avoiding unpacker disposing prevents stream closing. // ReSharper disable once AssignNullToNotNullAttribute - using ( var stream = new MemoryStream( buffer ) ) + var unpacker = Unpacker.Create( buffer, DefaultUnpackerOptions ); + + if ( !unpacker.Read() ) { - return await this.UnpackAsync( stream, cancellationToken ).ConfigureAwait( false ); + SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } + + return this.UnpackFromAsync( unpacker, cancellationToken ); } #endif // FEATURE_TAP diff --git a/src/MsgPack/Serialization/Metadata/_CultureInfo.cs b/src/MsgPack/Serialization/Metadata/_CultureInfo.cs index d20a8acc4..17425ea9f 100644 --- a/src/MsgPack/Serialization/Metadata/_CultureInfo.cs +++ b/src/MsgPack/Serialization/Metadata/_CultureInfo.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2013 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ namespace MsgPack.Serialization.Metadata // ReSharper disable InconsistentNaming internal static class _CultureInfo { - public static readonly PropertyInfo InvariantCulture = FromExpression.ToProperty( () => CultureInfo.InvariantCulture ); + public static readonly PropertyInfo InvariantCulture = typeof( CultureInfo ).GetProperty( nameof( CultureInfo.InvariantCulture ) ); } // ReSharper restore InconsistentNaming } diff --git a/src/MsgPack/Serialization/Metadata/_DateTimeMessagePackSerializerHelpers.cs b/src/MsgPack/Serialization/Metadata/_DateTimeMessagePackSerializerHelpers.cs index ef0d4bd39..a057794ac 100644 --- a/src/MsgPack/Serialization/Metadata/_DateTimeMessagePackSerializerHelpers.cs +++ b/src/MsgPack/Serialization/Metadata/_DateTimeMessagePackSerializerHelpers.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,12 +27,9 @@ namespace MsgPack.Serialization.Metadata internal static class _DateTimeMessagePackSerializerHelpers { public static readonly MethodInfo DetermineDateTimeConversionMethodMethod = - FromExpression.ToMethod( - ( SerializationContext context, DateTimeMemberConversionMethod dateTimeMemberConversionMethod ) => - DateTimeMessagePackSerializerHelpers.DetermineDateTimeConversionMethod( - context, - dateTimeMemberConversionMethod - ) + typeof( DateTimeMessagePackSerializerHelpers ).GetMethod( + nameof( DateTimeMessagePackSerializerHelpers.DetermineDateTimeConversionMethod ), + new[] { typeof( SerializationContext ), typeof( DateTimeMemberConversionMethod ) } ); } } diff --git a/src/MsgPack/Serialization/Metadata/_Decimal.cs b/src/MsgPack/Serialization/Metadata/_Decimal.cs index 22a4e7475..d75af2839 100644 --- a/src/MsgPack/Serialization/Metadata/_Decimal.cs +++ b/src/MsgPack/Serialization/Metadata/_Decimal.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015-2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ internal static class _Decimal { public static readonly ConstructorInfo Constructor = typeof( Decimal ).GetConstructor( - new[] { typeof( int ), typeof( int ), typeof( int ), typeof( bool ), typeof( byte ) } ); + new[] { typeof( int ), typeof( int ), typeof( int ), typeof( bool ), typeof( byte ) } + ); } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/Metadata/_DictionaryEntry.cs b/src/MsgPack/Serialization/Metadata/_DictionaryEntry.cs index 4b433692f..2f162b74f 100644 --- a/src/MsgPack/Serialization/Metadata/_DictionaryEntry.cs +++ b/src/MsgPack/Serialization/Metadata/_DictionaryEntry.cs @@ -26,7 +26,7 @@ namespace MsgPack.Serialization.Metadata { internal static class _DictionaryEntry { - public static readonly PropertyInfo Key = FromExpression.ToProperty( ( DictionaryEntry entry ) => entry.Key ); - public static readonly PropertyInfo Value = FromExpression.ToProperty( ( DictionaryEntry entry ) => entry.Value ); + public static readonly PropertyInfo Key = typeof( DictionaryEntry ).GetProperty( nameof( DictionaryEntry.Key ) ); + public static readonly PropertyInfo Value = typeof( DictionaryEntry ).GetProperty( nameof( DictionaryEntry.Value ) ); } } diff --git a/src/MsgPack/Serialization/Metadata/_DynamicUnpackingContext.cs b/src/MsgPack/Serialization/Metadata/_DynamicUnpackingContext.cs deleted file mode 100644 index 43b51979a..000000000 --- a/src/MsgPack/Serialization/Metadata/_DynamicUnpackingContext.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2015 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -using System; -using System.Reflection; - -using MsgPack.Serialization.AbstractSerializers; - -// ReSharper disable InconsistentNaming - -namespace MsgPack.Serialization.Metadata -{ - internal static class _DynamicUnpackingContext - { - public static MethodInfo Get = - FromExpression.ToMethod( ( DynamicUnpackingContext @this, string key ) => @this.Get( key ) ); - - public static MethodInfo Set = - FromExpression.ToMethod( ( DynamicUnpackingContext @this, string key, object value ) => @this.Set( key, value ) ); - } -} diff --git a/src/MsgPack/Serialization/Metadata/_EnumMessagePackSerializerHelpers.cs b/src/MsgPack/Serialization/Metadata/_EnumMessagePackSerializerHelpers.cs index 91a04ea6f..ed2eb09da 100644 --- a/src/MsgPack/Serialization/Metadata/_EnumMessagePackSerializerHelpers.cs +++ b/src/MsgPack/Serialization/Metadata/_EnumMessagePackSerializerHelpers.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2013 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,13 +27,9 @@ namespace MsgPack.Serialization.Metadata internal static class _EnumMessagePackSerializerHelpers { public static readonly MethodInfo DetermineEnumSerializationMethodMethod = - FromExpression.ToMethod( - ( SerializationContext context, Type enumType, EnumMemberSerializationMethod enumMemberSerializationMethod ) => - EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod( - context, - enumType, - enumMemberSerializationMethod - ) + typeof( EnumMessagePackSerializerHelpers ).GetMethod( + nameof( EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod ), + new[] { typeof( SerializationContext ), typeof( Type ), typeof( EnumMemberSerializationMethod ) } ); } } diff --git a/src/MsgPack/Serialization/Metadata/_FieldInfo.cs b/src/MsgPack/Serialization/Metadata/_FieldInfo.cs index 2a5c02dde..7d3f93837 100644 --- a/src/MsgPack/Serialization/Metadata/_FieldInfo.cs +++ b/src/MsgPack/Serialization/Metadata/_FieldInfo.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2014-2015 FUJIWARA, Yusuke +// Copyright (C) 2014-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,13 +26,14 @@ namespace MsgPack.Serialization.Metadata internal static class _FieldInfo { #if !NETFX_CORE - public static readonly MethodInfo GetFieldFromHandle = FromExpression.ToMethod( ( RuntimeFieldHandle handle, RuntimeTypeHandle declaringType ) => FieldInfo.GetFieldFromHandle( handle, declaringType ) ); + public static readonly MethodInfo GetFieldFromHandle = + typeof( FieldInfo ).GetMethod( nameof( FieldInfo.GetFieldFromHandle ), new[] { typeof( RuntimeFieldHandle ), typeof( RuntimeTypeHandle ) } ); #endif // !NETFX_CORE public static readonly MethodInfo GetValue = - FromExpression.ToMethod( ( FieldInfo @this, object obj ) => @this.GetValue( obj ) ); + typeof( FieldInfo ).GetMethod( nameof( FieldInfo.GetValue ), new[] { typeof( object ) } ); public static readonly MethodInfo SetValue = - FromExpression.ToMethod( ( FieldInfo @this, object obj, object value ) => @this.SetValue( obj, value ) ); + typeof( FieldInfo ).GetMethod( nameof( FieldInfo.SetValue ), new[] { typeof( object ), typeof( object ) } ); } } diff --git a/src/MsgPack/Serialization/Metadata/_IDictionaryEnumerator.cs b/src/MsgPack/Serialization/Metadata/_IDictionaryEnumerator.cs index de12291dc..ed69dffec 100644 --- a/src/MsgPack/Serialization/Metadata/_IDictionaryEnumerator.cs +++ b/src/MsgPack/Serialization/Metadata/_IDictionaryEnumerator.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,6 +26,6 @@ namespace MsgPack.Serialization.Metadata { internal static class _IDictionaryEnumerator { - public static readonly PropertyInfo Entry = FromExpression.ToProperty( ( IDictionaryEnumerator enumerator ) => enumerator.Entry ); + public static readonly PropertyInfo Entry = typeof( IDictionaryEnumerator ).GetProperty( nameof( IDictionaryEnumerator.Entry ) ); } } diff --git a/src/MsgPack/Serialization/Metadata/_IDisposable.cs b/src/MsgPack/Serialization/Metadata/_IDisposable.cs index c1137e11c..ee5737eee 100644 --- a/src/MsgPack/Serialization/Metadata/_IDisposable.cs +++ b/src/MsgPack/Serialization/Metadata/_IDisposable.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ namespace MsgPack.Serialization.Metadata { internal static class _IDisposable { - public static readonly MethodInfo Dispose = FromExpression.ToMethod( ( IDisposable disposable ) => disposable.Dispose() ); + public static readonly MethodInfo Dispose = typeof( IDisposable ).GetMethod( nameof( IDisposable.Dispose ), ReflectionAbstractions.EmptyTypes ); } } diff --git a/src/MsgPack/Serialization/Metadata/_IEnumreator.cs b/src/MsgPack/Serialization/Metadata/_IEnumreator.cs index a6a9475f9..285bf5355 100644 --- a/src/MsgPack/Serialization/Metadata/_IEnumreator.cs +++ b/src/MsgPack/Serialization/Metadata/_IEnumreator.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,11 @@ using System.Collections; using System.Collections.Generic; #if DEBUG +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 #endif // DEBUG using System.Reflection; @@ -30,16 +34,15 @@ namespace MsgPack.Serialization.Metadata { internal static class _IEnumerator { - private static readonly Type[] EmptyTypes = new Type[ 0 ]; - public static readonly MethodInfo MoveNext = FromExpression.ToMethod( ( IEnumerator enumerator ) => enumerator.MoveNext() ); - public static readonly PropertyInfo Current = FromExpression.ToProperty( ( IEnumerator enumerator ) => enumerator.Current ); + public static readonly MethodInfo MoveNext = typeof( IEnumerator ).GetMethod( nameof( IEnumerator.MoveNext ), ReflectionAbstractions.EmptyTypes ); + public static readonly PropertyInfo Current = typeof( IEnumerator ).GetProperty( nameof( IEnumerator.Current ) ); public static PropertyInfo FindEnumeratorCurrentProperty( Type enumeratorType, CollectionTraits traits ) { #if DEBUG Contract.Assert( traits.GetEnumeratorMethod != null ); #endif // DEBUG - PropertyInfo currentProperty = traits.GetEnumeratorMethod.ReturnType.GetProperty( "Current" ); + var currentProperty = traits.GetEnumeratorMethod.ReturnType.GetProperty( nameof( IEnumerator.Current ) ); if ( currentProperty == null ) { @@ -51,7 +54,7 @@ public static PropertyInfo FindEnumeratorCurrentProperty( Type enumeratorType, C { if ( enumeratorType.GetIsGenericType() && enumeratorType.GetGenericTypeDefinition() == typeof( IEnumerator<> ) ) { - currentProperty = typeof( IEnumerator<> ).MakeGenericType( traits.ElementType ).GetProperty( "Current" ); + currentProperty = typeof( IEnumerator<> ).MakeGenericType( traits.ElementType ).GetProperty( nameof( IEnumerator.Current ) ); } else { @@ -64,7 +67,7 @@ public static PropertyInfo FindEnumeratorCurrentProperty( Type enumeratorType, C public static MethodInfo FindEnumeratorMoveNextMethod( Type enumeratorType ) { - MethodInfo moveNextMethod = enumeratorType.GetMethod( "MoveNext", EmptyTypes ); + var moveNextMethod = enumeratorType.GetMethod( nameof( IEnumerator.MoveNext ), ReflectionAbstractions.EmptyTypes ); if ( moveNextMethod == null ) { diff --git a/src/MsgPack/Serialization/Metadata/_MessagePackObject.cs b/src/MsgPack/Serialization/Metadata/_MessagePackObject.cs index a0713507f..cddb97012 100644 --- a/src/MsgPack/Serialization/Metadata/_MessagePackObject.cs +++ b/src/MsgPack/Serialization/Metadata/_MessagePackObject.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ namespace MsgPack.Serialization.Metadata { internal static class _MessagePackObject { - public static readonly PropertyInfo IsNil = FromExpression.ToProperty( ( MessagePackObject mpo ) => mpo.IsNil ); + public static readonly PropertyInfo IsNil = typeof( MessagePackObject ).GetProperty( nameof( MessagePackObject.IsNil ) ); } } diff --git a/src/MsgPack/Serialization/Metadata/_MessagePackSerializer.cs b/src/MsgPack/Serialization/Metadata/_MessagePackSerializer.cs index 3be677791..8d57ce6d0 100644 --- a/src/MsgPack/Serialization/Metadata/_MessagePackSerializer.cs +++ b/src/MsgPack/Serialization/Metadata/_MessagePackSerializer.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ #endregion -- License Terms -- using System; +using System.Linq; using System.Reflection; namespace MsgPack.Serialization.Metadata @@ -27,8 +28,12 @@ namespace MsgPack.Serialization.Metadata internal static class _MessagePackSerializer { // ReSharper disable InconsistentNaming - public static readonly MethodInfo Create1_Method = typeof( MessagePackSerializer ).GetMethod( "Create", new[] { typeof( SerializationContext ) } ); + public static readonly MethodInfo Create1_Method = typeof( MessagePackSerializer ).GetMethod( nameof( MessagePackSerializer.Create ), new[] { typeof( SerializationContext ) } ); // ReSharper restore InconsistentNaming - public static readonly PropertyInfo OwnerContext = FromExpression.ToProperty( ( MessagePackSerializer serializer ) => serializer.OwnerContext ); + public static readonly PropertyInfo OwnerContext = + typeof( MessagePackSerializer ) + // Use LINQ to get non public property in netstandard 1.x + .GetRuntimeProperties() + .Single( p => p.Name == nameof( MessagePackSerializer.OwnerContext ) ); } } diff --git a/src/MsgPack/Serialization/Metadata/_MethodBase.cs b/src/MsgPack/Serialization/Metadata/_MethodBase.cs index 12e1d5e9d..0f4e1585c 100644 --- a/src/MsgPack/Serialization/Metadata/_MethodBase.cs +++ b/src/MsgPack/Serialization/Metadata/_MethodBase.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2014-2015 FUJIWARA, Yusuke +// Copyright (C) 2014-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,15 +26,11 @@ namespace MsgPack.Serialization.Metadata internal static class _MethodBase { #if !NETFX_CORE - public static readonly MethodInfo GetMethodFromHandle = FromExpression.ToMethod( ( RuntimeMethodHandle handle, RuntimeTypeHandle declaringType ) => MethodBase.GetMethodFromHandle( handle, declaringType ) ); + public static readonly MethodInfo GetMethodFromHandle = + typeof( MethodBase ).GetMethod( nameof( MethodBase.GetMethodFromHandle ), new[] { typeof( RuntimeMethodHandle ), typeof( RuntimeTypeHandle ) } ); #endif // !NETFX_CORE public static readonly MethodInfo Invoke_2 = - FromExpression.ToMethod( - ( MethodBase @this, - object obj, - object[] parameters - ) => @this.Invoke( obj, parameters ) - ); + typeof( MethodBase ).GetMethod( nameof( MethodBase.Invoke ), new[] { typeof( object ), typeof( object[] ) } ); } } diff --git a/src/MsgPack/Serialization/Metadata/_Packer.cs b/src/MsgPack/Serialization/Metadata/_Packer.cs index 949573264..39c50a8bd 100644 --- a/src/MsgPack/Serialization/Metadata/_Packer.cs +++ b/src/MsgPack/Serialization/Metadata/_Packer.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,9 +28,9 @@ namespace MsgPack.Serialization.Metadata { internal static class _Packer { - public static readonly MethodInfo PackNull = FromExpression.ToMethod( ( Packer packer ) => packer.PackNull() ); + public static readonly MethodInfo PackNull = typeof( Packer ).GetMethod( nameof( Packer.PackNull ), ReflectionAbstractions.EmptyTypes ); #if FEATURE_TAP - public static readonly MethodInfo PackNullAsync = FromExpression.ToMethod( ( Packer packer, CancellationToken cancellationToken ) => packer.PackNullAsync( cancellationToken ) ); + public static readonly MethodInfo PackNullAsync = typeof( Packer ).GetMethod( nameof( Packer.PackNullAsync ), new[] { typeof( CancellationToken ) } ); #endif // FEATURE_TAP } } diff --git a/src/MsgPack/Serialization/Metadata/_SerializationContext.cs b/src/MsgPack/Serialization/Metadata/_SerializationContext.cs index 03a9dbda7..3a7060b9c 100644 --- a/src/MsgPack/Serialization/Metadata/_SerializationContext.cs +++ b/src/MsgPack/Serialization/Metadata/_SerializationContext.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2013 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ namespace MsgPack.Serialization.Metadata internal static class _SerializationContext { // ReSharper disable InconsistentNaming - public static readonly MethodInfo GetSerializer1_Parameter_Method = typeof( SerializationContext ).GetMethod( "GetSerializer", new[] { typeof( object ) } ); - public static readonly PropertyInfo SerializationMethod = FromExpression.ToProperty( ( SerializationContext context ) => context.SerializationMethod ); + public static readonly MethodInfo GetSerializer1_Parameter_Method = typeof( SerializationContext ).GetMethod( nameof( SerializationContext.GetSerializer ), new[] { typeof( object ) } ); + public static readonly PropertyInfo SerializationMethod = typeof( SerializationContext ).GetProperty( nameof( SerializationContext.SerializationMethod ) ); // ReSharper restore InconsistentNaming } } diff --git a/src/MsgPack/Serialization/Metadata/_String.cs b/src/MsgPack/Serialization/Metadata/_String.cs index 90743ee07..a4a5274ab 100644 --- a/src/MsgPack/Serialization/Metadata/_String.cs +++ b/src/MsgPack/Serialization/Metadata/_String.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,9 +27,7 @@ namespace MsgPack.Serialization.Metadata internal static class _String { public static readonly MethodInfo Format_P = - FromExpression.ToMethod( - ( IFormatProvider provider, string format, object[] args ) => String.Format( provider, format, args ) - ); + typeof( string ).GetMethod( nameof( String.Format ), new[] { typeof( IFormatProvider ), typeof( string ), typeof( object[] ) } ); } // ReSharper restore InconsistentNaming } diff --git a/src/MsgPack/Serialization/Metadata/_UnpackHelpers.cs b/src/MsgPack/Serialization/Metadata/_UnpackHelpers.cs index 924703a0f..844789031 100644 --- a/src/MsgPack/Serialization/Metadata/_UnpackHelpers.cs +++ b/src/MsgPack/Serialization/Metadata/_UnpackHelpers.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -35,19 +35,19 @@ namespace MsgPack.Serialization.Metadata internal static partial class _UnpackHelpers { public static readonly MethodInfo GetItemsCount = - FromExpression.ToMethod( ( Unpacker unpacker ) => UnpackHelpers.GetItemsCount( unpacker ) ); + typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.GetItemsCount ), new[] { typeof( Unpacker ) } ); /// /// generic method. /// public static readonly MethodInfo GetEqualityComparer_1Method = - typeof( UnpackHelpers ).GetMethod( "GetEqualityComparer" ); + typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.GetEqualityComparer ) ); /// /// generic method. /// public static readonly MethodInfo UnpackCollection_1Method = - typeof( UnpackHelpers ).GetMethod( "UnpackCollection" ); + typeof( UnpackHelpers ).GetMethods().Single( m => m.Name == nameof( UnpackHelpers.UnpackCollection ) && m.GetParameters().Length == 1 ); #if FEATURE_TAP @@ -55,17 +55,17 @@ internal static partial class _UnpackHelpers /// generic method. /// public static readonly MethodInfo UnpackCollectionAsync_1Method = - typeof( UnpackHelpers ).GetMethod( "UnpackCollectionAsync" ); + typeof( UnpackHelpers ).GetMethods().Single( m => m.Name == nameof( UnpackHelpers.UnpackCollectionAsync ) && m.GetParameters().Length == 1 ); /// /// generic method. /// - public static readonly MethodInfo ToNullable1Method = typeof( UnpackHelpers ).GetMethod( "ToNullable" ); + public static readonly MethodInfo ToNullable1Method = typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.ToNullable ) ); /// /// generic method. /// - public static readonly MethodInfo UnpackFromMessageAsyncMethod = typeof( UnpackHelpers ).GetMethod( "UnpackFromMessageAsync" ); + public static readonly MethodInfo UnpackFromMessageAsyncMethod = typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackFromMessageAsync ) ); #endif // FEATURE_MAP @@ -73,12 +73,12 @@ internal static partial class _UnpackHelpers /// generic method. /// public static readonly MethodInfo GetIdentity_1Method = - typeof( UnpackHelpers ).GetMethod( "GetIdentity" ); + typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.GetIdentity ) ); /// /// generic method. /// public static readonly MethodInfo Unbox_1Method = - typeof( UnpackHelpers ).GetMethod( "Unbox" ); + typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.Unbox ) ); } } diff --git a/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.cs b/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.cs index 0741e09ae..a023c7f52 100644 --- a/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.cs +++ b/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // FEATURE_MPCONTRACT using System.Reflection; namespace MsgPack.Serialization.Metadata @@ -34,58 +34,82 @@ namespace MsgPack.Serialization.Metadata partial class _UnpackHelpers { - private static readonly Dictionary _directUnpackMethods = GetDirectUnpackMethods( false ); + private static readonly Dictionary _directUnpackMethods = GetDirectUnpackMethods(); private static readonly Dictionary _asyncDirectUnpackMethods = #if FEATURE_TAP - GetDirectUnpackMethods( true ); + GetAsyncDirectUnpackMethods(); #else _directUnpackMethods; #endif // FEATURE_TAP - private static Dictionary GetDirectUnpackMethods( bool forAsync ) + + private static Dictionary GetDirectUnpackMethods() { - var suffix = forAsync ? "ValueAsync" : "Value"; return new Dictionary( 14 ) { - - { typeof( SByte ), typeof( UnpackHelpers ).GetMethod( "UnpackSByte" + suffix ) }, - { typeof( SByte? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableSByte" + suffix ) }, - - { typeof( Int16 ), typeof( UnpackHelpers ).GetMethod( "UnpackInt16" + suffix ) }, - { typeof( Int16? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableInt16" + suffix ) }, - - { typeof( Int32 ), typeof( UnpackHelpers ).GetMethod( "UnpackInt32" + suffix ) }, - { typeof( Int32? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableInt32" + suffix ) }, - - { typeof( Int64 ), typeof( UnpackHelpers ).GetMethod( "UnpackInt64" + suffix ) }, - { typeof( Int64? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableInt64" + suffix ) }, - - { typeof( Byte ), typeof( UnpackHelpers ).GetMethod( "UnpackByte" + suffix ) }, - { typeof( Byte? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableByte" + suffix ) }, - - { typeof( UInt16 ), typeof( UnpackHelpers ).GetMethod( "UnpackUInt16" + suffix ) }, - { typeof( UInt16? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableUInt16" + suffix ) }, - - { typeof( UInt32 ), typeof( UnpackHelpers ).GetMethod( "UnpackUInt32" + suffix ) }, - { typeof( UInt32? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableUInt32" + suffix ) }, - - { typeof( UInt64 ), typeof( UnpackHelpers ).GetMethod( "UnpackUInt64" + suffix ) }, - { typeof( UInt64? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableUInt64" + suffix ) }, - - { typeof( Single ), typeof( UnpackHelpers ).GetMethod( "UnpackSingle" + suffix ) }, - { typeof( Single? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableSingle" + suffix ) }, - - { typeof( Double ), typeof( UnpackHelpers ).GetMethod( "UnpackDouble" + suffix ) }, - { typeof( Double? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableDouble" + suffix ) }, - - { typeof( Boolean ), typeof( UnpackHelpers ).GetMethod( "UnpackBoolean" + suffix ) }, - { typeof( Boolean? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullableBoolean" + suffix ) }, - { typeof( string ), typeof( UnpackHelpers ).GetMethod( "UnpackString" + suffix ) }, - { typeof( byte[] ), typeof( UnpackHelpers ).GetMethod( "UnpackBinary" + suffix ) }, + { typeof( SByte ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackSByteValue ) ) }, + { typeof( SByte? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableSByteValue ) ) }, + { typeof( Int16 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackInt16Value ) ) }, + { typeof( Int16? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableInt16Value ) ) }, + { typeof( Int32 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackInt32Value ) ) }, + { typeof( Int32? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableInt32Value ) ) }, + { typeof( Int64 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackInt64Value ) ) }, + { typeof( Int64? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableInt64Value ) ) }, + { typeof( Byte ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackByteValue ) ) }, + { typeof( Byte? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableByteValue ) ) }, + { typeof( UInt16 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackUInt16Value ) ) }, + { typeof( UInt16? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableUInt16Value ) ) }, + { typeof( UInt32 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackUInt32Value ) ) }, + { typeof( UInt32? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableUInt32Value ) ) }, + { typeof( UInt64 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackUInt64Value ) ) }, + { typeof( UInt64? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableUInt64Value ) ) }, + { typeof( Single ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackSingleValue ) ) }, + { typeof( Single? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableSingleValue ) ) }, + { typeof( Double ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackDoubleValue ) ) }, + { typeof( Double? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableDoubleValue ) ) }, + { typeof( Boolean ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackBooleanValue ) ) }, + { typeof( Boolean? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableBooleanValue ) ) }, + { typeof( string ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackStringValue ) ) }, + { typeof( byte[] ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackBinaryValue ) ) }, }; } +#if FEATURE_TAP + + private static Dictionary GetAsyncDirectUnpackMethods() + { + return + new Dictionary( 14 ) + { + { typeof( SByte ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackSByteValueAsync ) ) }, + { typeof( SByte? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableSByteValueAsync ) ) }, + { typeof( Int16 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackInt16ValueAsync ) ) }, + { typeof( Int16? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableInt16ValueAsync ) ) }, + { typeof( Int32 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackInt32ValueAsync ) ) }, + { typeof( Int32? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableInt32ValueAsync ) ) }, + { typeof( Int64 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackInt64ValueAsync ) ) }, + { typeof( Int64? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableInt64ValueAsync ) ) }, + { typeof( Byte ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackByteValueAsync ) ) }, + { typeof( Byte? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableByteValueAsync ) ) }, + { typeof( UInt16 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackUInt16ValueAsync ) ) }, + { typeof( UInt16? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableUInt16ValueAsync ) ) }, + { typeof( UInt32 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackUInt32ValueAsync ) ) }, + { typeof( UInt32? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableUInt32ValueAsync ) ) }, + { typeof( UInt64 ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackUInt64ValueAsync ) ) }, + { typeof( UInt64? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableUInt64ValueAsync ) ) }, + { typeof( Single ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackSingleValueAsync ) ) }, + { typeof( Single? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableSingleValueAsync ) ) }, + { typeof( Double ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackDoubleValueAsync ) ) }, + { typeof( Double? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableDoubleValueAsync ) ) }, + { typeof( Boolean ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackBooleanValueAsync ) ) }, + { typeof( Boolean? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullableBooleanValueAsync ) ) }, + { typeof( string ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackStringValueAsync ) ) }, + { typeof( byte[] ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackBinaryValueAsync ) ) }, + }; + } +#endif // FEATURE_TAP + public static MethodInfo GetDirectUnpackMethod( Type type, bool forAsync ) { MethodInfo result; @@ -98,4 +122,4 @@ public static MethodInfo GetDirectUnpackMethod( Type type, bool forAsync ) return result; } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.tt b/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.tt index f904b55e4..e2b495d84 100644 --- a/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.tt +++ b/src/MsgPack/Serialization/Metadata/_UnpackHelpers.direct.tt @@ -1,4 +1,4 @@ -<#@ template debug="true" hostSpecific="true" #> +<#@ template debug="true" hostSpecific="true" #> <#@ output extension=".cs" #> <#@ Assembly Name="System.Core.dll" #> <#@ Assembly Name="System.Windows.Forms.dll" #> @@ -22,7 +22,7 @@ Type[] _valueTypes = // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -40,11 +40,11 @@ Type[] _valueTypes = using System; using System.Collections.Generic; -#if CORE_CLR +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // FEATURE_MPCONTRACT using System.Reflection; namespace MsgPack.Serialization.Metadata @@ -54,36 +54,58 @@ namespace MsgPack.Serialization.Metadata partial class _UnpackHelpers { - private static readonly Dictionary _directUnpackMethods = GetDirectUnpackMethods( false ); + private static readonly Dictionary _directUnpackMethods = GetDirectUnpackMethods(); private static readonly Dictionary _asyncDirectUnpackMethods = #if FEATURE_TAP - GetDirectUnpackMethods( true ); + GetAsyncDirectUnpackMethods(); #else _directUnpackMethods; #endif // FEATURE_TAP - private static Dictionary GetDirectUnpackMethods( bool forAsync ) +<# +foreach ( var isAsync in new [] { false, true } ) +{ + var suffix = isAsync ? "ValueAsync" : "Value"; + + if ( isAsync ) + { +#> +#if FEATURE_TAP +<# + } +#> + + private static Dictionary Get<#= isAsync ? "Async" : String.Empty #>DirectUnpackMethods() { - var suffix = forAsync ? "ValueAsync" : "Value"; return new Dictionary( <#= _valueTypes.Length + 3 #> ) { <# -foreach( var type in _valueTypes ) -{ - // NOTE: Allways use nullable version for nil implication. + foreach ( var type in _valueTypes ) + { + // NOTE: Allways use nullable version for nil implication. #> - - { typeof( <#= type.Name #> ), typeof( UnpackHelpers ).GetMethod( "Unpack<#= type.Name #>" + suffix ) }, - { typeof( <#= type.Name #>? ), typeof( UnpackHelpers ).GetMethod( "UnpackNullable<#= type.Name #>" + suffix ) }, + { typeof( <#= type.Name #> ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.Unpack<#= type.Name + suffix #> ) ) }, + { typeof( <#= type.Name #>? ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackNullable<#= type.Name + suffix #> ) ) }, <# -} + } #> - { typeof( string ), typeof( UnpackHelpers ).GetMethod( "UnpackString" + suffix ) }, - { typeof( byte[] ), typeof( UnpackHelpers ).GetMethod( "UnpackBinary" + suffix ) }, + { typeof( string ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackString<#= suffix #> ) ) }, + { typeof( byte[] ), typeof( UnpackHelpers ).GetMethod( nameof( UnpackHelpers.UnpackBinary<#= suffix #> ) ) }, }; } +<# + if ( isAsync ) + { +#> +#endif // FEATURE_TAP +<# + } +#> +<# +} +#> public static MethodInfo GetDirectUnpackMethod( Type type, bool forAsync ) { MethodInfo result; @@ -96,4 +118,4 @@ foreach( var type in _valueTypes ) return result; } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/Metadata/_Unpacker.cs b/src/MsgPack/Serialization/Metadata/_Unpacker.cs index ebceb3c5a..52970dffb 100644 --- a/src/MsgPack/Serialization/Metadata/_Unpacker.cs +++ b/src/MsgPack/Serialization/Metadata/_Unpacker.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,14 +28,14 @@ namespace MsgPack.Serialization.Metadata { internal static partial class _Unpacker { - public static readonly MethodInfo Read = FromExpression.ToMethod( ( Unpacker unpacker ) => unpacker.Read() ); -#if !NETFX_35 - public static readonly PropertyInfo ItemsCount = FromExpression.ToProperty( ( Unpacker unpacker ) => unpacker.ItemsCount ); -#endif // !NETFX_35 - public static readonly PropertyInfo IsArrayHeader = FromExpression.ToProperty( ( Unpacker unpacker ) => unpacker.IsArrayHeader ); - public static readonly PropertyInfo IsMapHeader = FromExpression.ToProperty( ( Unpacker unpacker ) => unpacker.IsMapHeader ); + public static readonly MethodInfo Read = typeof( Unpacker ).GetMethod( nameof( Unpacker.Read ), ReflectionAbstractions.EmptyTypes ); +#if !NET35 + public static readonly PropertyInfo ItemsCount = typeof( Unpacker ).GetProperty( nameof( Unpacker.ItemsCount ) ); +#endif // !NET35 + public static readonly PropertyInfo IsArrayHeader = typeof( Unpacker ).GetProperty( nameof( Unpacker.IsArrayHeader ) ); + public static readonly PropertyInfo IsMapHeader = typeof( Unpacker ).GetProperty( nameof( Unpacker.IsMapHeader ) ); #if FEATURE_TAP - public static readonly MethodInfo ReadAsync = FromExpression.ToMethod( ( Unpacker unpacker, CancellationToken cancellationToken ) => unpacker.ReadAsync( cancellationToken ) ); + public static readonly MethodInfo ReadAsync = typeof( Unpacker ).GetMethod( nameof( Unpacker.ReadAsync ), new[] { typeof( CancellationToken ) } ); #endif // FEATURE_TAP } } diff --git a/src/MsgPack/Serialization/NullTextWriter.cs b/src/MsgPack/Serialization/NullTextWriter.cs new file mode 100644 index 000000000..c5aa0137e --- /dev/null +++ b/src/MsgPack/Serialization/NullTextWriter.cs @@ -0,0 +1,97 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke and contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Contributors: +// Samuel Cragg +// +#endregion -- License Terms -- + +// +// This code was generated by a NullTextWriter.tt. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// + +using System.IO; +using System.Text; + +namespace MsgPack.Serialization +{ + internal sealed class NullTextWriter : TextWriter + { + internal static NullTextWriter Instance = new NullTextWriter(); + + public override Encoding Encoding + { + get { return Encoding.UTF8; } + } + +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + public override void Close() { } +#endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + public override void Flush() { } + public override void Write( char value ) { } + public override void Write( char[] buffer ) { } + public override void Write( char[] buffer, int index, int count ) { } + public override void Write( bool value ) { } + public override void Write( int value ) { } + public override void Write( uint value ) { } + public override void Write( long value ) { } + public override void Write( ulong value ) { } + public override void Write( float value ) { } + public override void Write( double value ) { } + public override void Write( decimal value ) { } + public override void Write( string value ) { } + public override void Write( object value ) { } +#if !NETSTANDARD1_1 + public override void Write( string format, object arg0 ) { } +#endif // !NETSTANDARD1_1 +#if !NETSTANDARD1_1 + public override void Write( string format, object arg0, object arg1 ) { } +#endif // !NETSTANDARD1_1 +#if !SILVERLIGHT && !NETSTANDARD1_1 + public override void Write( string format, object arg0, object arg1, object arg2 ) { } +#endif // !SILVERLIGHT && !NETSTANDARD1_1 + public override void Write( string format, object[] arg ) { } + public override void WriteLine() { } + public override void WriteLine( char value ) { } + public override void WriteLine( char[] buffer ) { } + public override void WriteLine( char[] buffer, int index, int count ) { } + public override void WriteLine( bool value ) { } + public override void WriteLine( int value ) { } + public override void WriteLine( uint value ) { } + public override void WriteLine( long value ) { } + public override void WriteLine( ulong value ) { } + public override void WriteLine( float value ) { } + public override void WriteLine( double value ) { } + public override void WriteLine( decimal value ) { } + public override void WriteLine( string value ) { } + public override void WriteLine( object value ) { } +#if !NETSTANDARD1_1 + public override void WriteLine( string format, object arg0 ) { } +#endif // !NETSTANDARD1_1 +#if !NETSTANDARD1_1 + public override void WriteLine( string format, object arg0, object arg1 ) { } +#endif // !NETSTANDARD1_1 +#if !SILVERLIGHT && !NETSTANDARD1_1 + public override void WriteLine( string format, object arg0, object arg1, object arg2 ) { } +#endif // !SILVERLIGHT && !NETSTANDARD1_1 + public override void WriteLine( string format, object[] arg ) { } + } +} diff --git a/src/MsgPack/Serialization/NullTextWriter.tt b/src/MsgPack/Serialization/NullTextWriter.tt new file mode 100644 index 000000000..4c62bcca3 --- /dev/null +++ b/src/MsgPack/Serialization/NullTextWriter.tt @@ -0,0 +1,140 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.CodeDom" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Reflection" #> +<#@ import namespace="Microsoft.CSharp" #> +<#@ output extension=".cs" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke and contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Contributors: +// Samuel Cragg +// +#endregion -- License Terms -- + +// +// This code was generated by a NullTextWriter.tt. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// + +using System.IO; +using System.Text; + +namespace MsgPack.Serialization +{ + internal sealed class NullTextWriter : TextWriter + { + internal static NullTextWriter Instance = new NullTextWriter(); + + public override Encoding Encoding + { + get { return Encoding.UTF8; } + } + +<# + var notInSLs = + new List> + { + Tuple.Create( "Write", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }), + Tuple.Create( "WriteLine", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }) + }; + var notInNetFxCores = + new List> + { + Tuple.Create("Close", new Type[ 0 ]) + }; + var notInNetStd1_1s = + new List> + { + Tuple.Create("Write", new Type[] { typeof( string ), typeof( object ) }), + Tuple.Create("Write", new Type[] { typeof( string ), typeof( object ), typeof( object ) }), + Tuple.Create("Write", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }), + Tuple.Create("WriteLine", new Type[] { typeof( string ), typeof( object ) }), + Tuple.Create("WriteLine", new Type[] { typeof( string ), typeof( object ), typeof( object ) }), + Tuple.Create("WriteLine", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }), + Tuple.Create("Close", new Type[ 0 ]) + }; + var notInNetStd1_3s = + new List> + { + Tuple.Create("Close", new Type[ 0 ]) + }; + + using (var provider = new CSharpCodeProvider()) + { + IEnumerable methods = + typeof(System.IO.TextWriter).GetMethods() + .Where(m => !m.IsFinal && m.IsVirtual) // A method we can override + .Where(m => m.ReturnType == typeof(void)) // We're generating empty methods only + .Where(m => !m.IsSpecialName); // Exclude properties + + foreach (MethodInfo method in methods) + { + var unsupportedPlatforms = new List(); + if (IsNotIn(method, notInSLs)) + { + unsupportedPlatforms.Add("SILVERLIGHT"); + } + if (IsNotIn(method, notInNetFxCores)) + { + unsupportedPlatforms.Add("NETFX_CORE"); + } + if (IsNotIn(method, notInNetStd1_1s)) + { + unsupportedPlatforms.Add("NETSTANDARD1_1"); + } + if (IsNotIn(method, notInNetStd1_3s)) + { + unsupportedPlatforms.Add("NETSTANDARD1_3"); + } + + if (unsupportedPlatforms.Count > 0 ) + { +#> +#if <#= String.Join( " && ", unsupportedPlatforms.Select(s => "!" + s )) #> +<# + } + + var parameters = + method.GetParameters().Length == 0 + ? "()" + : "( " + String.Join(", ", method.GetParameters().Select(p => provider.GetTypeOutput(new CodeTypeReference(p.ParameterType)) + " " + p.Name) ) + " )"; +#> + public override void <#= method.Name #><#= parameters #> { } +<# + if (unsupportedPlatforms.Count > 0 ) + { +#> +#endif // <#= String.Join( " && ", unsupportedPlatforms.Select(s => "!" + s )) #> +<# + } + } + } +#> + } +} +<#+ +private static bool IsNotIn(MethodInfo method, IList> unavailableMethodSignatures) +{ + return unavailableMethodSignatures.Any(sig => sig.Item1 == method.Name && sig.Item2.SequenceEqual(method.GetParameters().Select(p => p.ParameterType))); +} +#> diff --git a/src/MsgPack/Serialization/PackHelperParameters.cs b/src/MsgPack/Serialization/PackHelperParameters.cs new file mode 100644 index 000000000..965c74844 --- /dev/null +++ b/src/MsgPack/Serialization/PackHelperParameters.cs @@ -0,0 +1,212 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if !UNITY || MSGPACK_UNITY_FULL +using System.ComponentModel; +#endif //!UNITY || MSGPACK_UNITY_FULL +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization +{ + // This file was generated from PackHelperParameters.tt + // DO NET modify this file directly. + + /// + /// Represents parameters of method. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct PackToArrayParameters + { + /// + /// The packer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Packer Packer; + + /// + /// The object to be packed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Target; + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be and 2nd argument will be . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct PackToArrayAsyncParameters + { + /// + /// The packer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Packer Packer; + + /// + /// The object to be packed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Target; + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument will be and returns represents async operation. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + /// + /// Represents parameters of method. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct PackToMapParameters + { + /// + /// The packer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Packer Packer; + + /// + /// The object to be packed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Target; + + /// + /// The which contains dictionary based serialization related options. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public SerializationContext SerializationContext; + + /// + /// Delegates table each ones check whether a member is null. + /// The argument will be and returns true if the argument value is null. + /// This dictionary should not contain for value type members except . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> NullCheckers; + + /// + /// Delegates table each ones unpack single member and their keys correspond to unpacking membmer names. + /// The 1st argument will be and 2nd argument will be . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct PackToMapAsyncParameters + { + /// + /// The packer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Packer Packer; + + /// + /// The object to be packed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Target; + + /// + /// The which contains dictionary based serialization related options. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public SerializationContext SerializationContext; + + /// + /// Delegates table each ones check whether a member is null. + /// The argument will be and returns true if the argument value is null. + /// This dictionary should not contain for value type members except . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> NullCheckers; + + /// + /// Delegates table each ones unpack single member and their keys correspond to unpacking membmer names. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument will be and returns represents async operation. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + +} diff --git a/src/MsgPack/Serialization/PackHelperParameters.tt b/src/MsgPack/Serialization/PackHelperParameters.tt new file mode 100644 index 000000000..5f61a706b --- /dev/null +++ b/src/MsgPack/Serialization/PackHelperParameters.tt @@ -0,0 +1,196 @@ +<#@ template debug="true" hostSpecific="true" #> +<#@ output extension=".cs" #> +<#@ import namespace="System" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if !UNITY || MSGPACK_UNITY_FULL +using System.ComponentModel; +#endif //!UNITY || MSGPACK_UNITY_FULL +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization +{ + // This file was generated from PackHelperParameters.tt + // DO NET modify this file directly. + +<# + WriteParameters( "Array", false, this.WriteArrayMembers ); +#> + +<# + WriteParameters( "Array", true, this.WriteArrayMembers ); +#> + +<# + WriteParameters( "Map", false, this.WriteMapMembers ); +#> + +<# + WriteParameters( "Map", true, this.WriteMapMembers ); +#> + +} +<#+ +void WriteParameters( string suffix, bool isAsync, Action differenceGenerator ) +{ + var methodName = "PackTo" + suffix + ( isAsync ? "Async" : String.Empty ); + if ( isAsync ) + { +#> +#if FEATURE_TAP + +<#+ + } +#> + /// + /// Represents parameters of method. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct <#= methodName #>Parameters + { + /// + /// The packer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Packer Packer; + + /// + /// The object to be packed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Target; +<#+ + differenceGenerator( isAsync ); + + if( isAsync ) + { +#> + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; +<#+ + } +#> + } +<#+ + if( isAsync ) + { +#> + +#endif // FEATURE_TAP +<#+ + } +} + +void WriteArrayMembers( bool isAsync ) +{ + if ( !isAsync ) + { +#> + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be and 2nd argument will be . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; +<#+ + } + else + { +#> + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument will be and returns represents async operation. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; +<#+ + } +} + +void WriteMapMembers( bool isAsync ) +{ +#> + + /// + /// The which contains dictionary based serialization related options. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public SerializationContext SerializationContext; + + /// + /// Delegates table each ones check whether a member is null. + /// The argument will be and returns true if the argument value is null. + /// This dictionary should not contain for value type members except . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> NullCheckers; +<#+ + if ( !isAsync ) + { +#> + + /// + /// Delegates table each ones unpack single member and their keys correspond to unpacking membmer names. + /// The 1st argument will be and 2nd argument will be . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; +<#+ + } + else + { +#> + + /// + /// Delegates table each ones unpack single member and their keys correspond to unpacking membmer names. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument will be and returns represents async operation. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; +<#+ + } +} +#> diff --git a/src/MsgPack/Serialization/PackHelpers.cs b/src/MsgPack/Serialization/PackHelpers.cs index 609c2f529..616aa4ab8 100644 --- a/src/MsgPack/Serialization/PackHelpers.cs +++ b/src/MsgPack/Serialization/PackHelpers.cs @@ -32,11 +32,11 @@ #if !UNITY || MSGPACK_UNITY_FULL using System.ComponentModel; #endif //!UNITY || MSGPACK_UNITY_FULL -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; @@ -68,6 +68,9 @@ public static class PackHelpers /// is null. /// Or, is null. /// +#if DEBUG + [Obsolete( "Use overload with PackToArrayParameters." )] +#endif // DEBUG #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -90,22 +93,63 @@ IList> operations SerializationExceptions.ThrowArgumentNullException( "operations" ); } + var parameter = + new PackToArrayParameters + { + Packer = packer, + Target = target, + Operations = operations + }; + PackToArray( ref parameter ); + } + + /// + /// Packs object to msgpack array. + /// + /// The type of the packing object. + /// The reference of object which represents parameters of this method. + /// The unpacked object. + /// + /// of is null. + /// Or, of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates essentially must be nested generic." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] + public static void PackToArray( + ref PackToArrayParameters parameter + ) + { + if ( parameter.Packer == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Packer" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + #if ASSERT - Contract.Assert( packer != null ); - Contract.Assert( operations != null ); + Contract.Assert( parameter.Packer != null ); + Contract.Assert( parameter.Operations != null ); #endif // ASSERT - packer.PackArrayHeader( operations.Count ); - foreach ( var operation in operations ) + parameter.Packer.PackArrayHeader( parameter.Operations.Count ); + foreach ( var operation in parameter.Operations ) { - operation( packer, target ); + operation( parameter.Packer, parameter.Target ); } } #if FEATURE_TAP /// - /// Packs object to msgpack array. + /// Packs object to msgpack array asynchronously. /// /// The type of the packing object. /// The packer. @@ -121,12 +165,15 @@ IList> operations /// Or, is null. /// #if !UNITY || MSGPACK_UNITY_FULL +#if DEBUG + [Obsolete( "Use overload with PackToArrayAsyncParameters." )] +#endif // DEBUG [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] - public static async Task PackToArrayAsync( + public static Task PackToArrayAsync( Packer packer, TObject target, IList> operations, @@ -143,6 +190,55 @@ CancellationToken cancellationToken SerializationExceptions.ThrowArgumentNullException( "operations" ); } + var parameter = + new PackToArrayAsyncParameters + { + Packer = packer, + Target = target, + Operations = operations, + CancellationToken = cancellationToken + }; + return PackToArrayAsync( ref parameter ); + } + + /// + /// Packs object to msgpack array asynchronously. + /// + /// The type of the packing object. + /// The reference of object which represents parameters of this method. + /// The unpacked object. + /// + /// of is null. + /// Or, of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task PackToArrayAsync( + ref PackToArrayAsyncParameters parameter + ) + { + if ( parameter.Packer == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Packer" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return PackToArrayAsyncCore( parameter.Packer, parameter.Target, parameter.Operations, parameter.CancellationToken ); + } + + private static async Task PackToArrayAsyncCore( + Packer packer, + TObject target, + IList> operations, + CancellationToken cancellationToken + ) + { #if ASSERT Contract.Assert( packer != null ); Contract.Assert( operations != null ); @@ -169,14 +265,17 @@ CancellationToken cancellationToken /// /// /// is null. - /// Or, is null. /// + /// + /// is null. + /// +#if DEBUG + [Obsolete( "Use overload with keyTransformer and nullDetectors." )] +#endif // DEBUG #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates essentially must be nested generic." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )] public static void PackToMap( Packer packer, TObject target, @@ -185,7 +284,7 @@ IDictionary> operations { if ( packer == null ) { - SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + SerializationExceptions.ThrowArgumentNullException( "packer" ); } if ( operations == null ) @@ -193,23 +292,102 @@ IDictionary> operations SerializationExceptions.ThrowArgumentNullException( "operations" ); } + var parameter = + new PackToMapParameters + { + Packer = packer, + Target = target, + Operations = operations + }; + PackToMap( ref parameter ); + } + +#pragma warning disable 618 + /// + /// Packs object to msgpack map. + /// + /// The type of the packing object. + /// The reference of object which represents parameters of this method. + /// + /// of is null. + /// + /// + /// PackToMapAsyncParameters{T}.Operations of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated correctly.")] + public static void PackToMap( + ref PackToMapParameters parameter + ) + { + if ( parameter.Packer == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Packer" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + #if ASSERT - Contract.Assert( packer != null ); - Contract.Assert( operations != null ); + Contract.Assert( parameter.Packer != null ); + Contract.Assert( parameter.Operations != null ); #endif // ASSERT - packer.PackMapHeader( operations.Count ); - foreach ( var operation in operations ) + if ( parameter.NullCheckers != null + && parameter.SerializationContext != null && parameter.SerializationContext.DictionarySerializationOptions.OmitNullEntry ) { - packer.PackString( operation.Key ); - operation.Value( packer, target ); +#if ASSERT + Contract.Assert( !SerializerDebugging.UseLegacyNullMapEntryHandling ); +#endif // ASSERT + + // Skipping causes the entries count header reducing, so count up null entries first. + var nullCount = 0; + foreach ( var nullChecker in parameter.NullCheckers ) + { + if ( nullChecker.Value( parameter.Target ) ) + { + nullCount++; + } + } + + parameter.Packer.PackMapHeader( parameter.Operations.Count - nullCount ); + foreach ( var operation in parameter.Operations ) + { + Func nullChecker; + if ( parameter.NullCheckers.TryGetValue( operation.Key, out nullChecker ) ) + { + if ( nullChecker( parameter.Target ) ) + { + continue; + } + } + + parameter.Packer.PackString( operation.Key ); + operation.Value( parameter.Packer, parameter.Target ); + } + } + else + { + parameter.Packer.PackMapHeader( parameter.Operations.Count ); + // Compatible path + foreach ( var operation in parameter.Operations ) + { + parameter.Packer.PackString( operation.Key ); + operation.Value( parameter.Packer, parameter.Target ); + } } +#pragma warning restore 618 } #if FEATURE_TAP /// - /// Packs object to msgpack map. + /// Packs object to msgpack map asynchronously. /// /// The type of the packing object. /// The packer. @@ -221,15 +399,18 @@ IDictionary> operations /// The token to monitor for cancellation requests. The default value is . /// /// is null. - /// Or, is null. /// + /// + /// is null. + /// +#if DEBUG + [Obsolete( "Use overload with PackToMapParameters." )] +#endif // DEBUG #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates essentially must be nested generic." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] - public static async Task PackToMapAsync( + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )] + public static Task PackToMapAsync( Packer packer, TObject target, IDictionary> operations, @@ -238,7 +419,7 @@ CancellationToken cancellationToken { if ( packer == null ) { - SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + SerializationExceptions.ThrowArgumentNullException( "packer" ); } if ( operations == null ) @@ -246,18 +427,110 @@ CancellationToken cancellationToken SerializationExceptions.ThrowArgumentNullException( "operations" ); } + var parameter = + new PackToMapAsyncParameters + { + Packer = packer, + Target = target, + Operations = operations, + CancellationToken = cancellationToken + }; + return PackToMapAsync( ref parameter ); + } + +#pragma warning disable 618 + /// + /// Packs object to msgpack map asynchronously. + /// + /// The type of the packing object. + /// The reference of object which represents parameters of this method. + /// + /// of is null. + /// + /// + /// of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task PackToMapAsync( + ref PackToMapAsyncParameters parameter + ) + { + if ( parameter.Packer == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Packer" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return PackToMapAsyncCore( parameter.SerializationContext, parameter.Packer, parameter.Target, parameter.Operations, parameter.NullCheckers, parameter.CancellationToken ); + } +#pragma warning restore 618 + + private static async Task PackToMapAsyncCore( + SerializationContext serializationContext, + Packer packer, + TObject target, + IDictionary> operations, + IDictionary> nullCheckers, + CancellationToken cancellationToken + ) + { +#if ASSERT Contract.Assert( packer != null ); Contract.Assert( operations != null ); +#endif // ASSERT - await packer.PackMapHeaderAsync( operations.Count, cancellationToken ).ConfigureAwait( false ); - foreach ( var operation in operations ) + if ( nullCheckers != null + && serializationContext != null && serializationContext.DictionarySerializationOptions.OmitNullEntry ) + { +#if ASSERT + Contract.Assert( !SerializerDebugging.UseLegacyNullMapEntryHandling ); +#endif // ASSERT + // Skipping causes the entries count header reducing, so count up null entries first. + var nullCount = 0; + foreach ( var nullChecker in nullCheckers ) + { + if ( nullChecker.Value( target ) ) + { + nullCount++; + } + } + + await packer.PackMapHeaderAsync( operations.Count - nullCount, cancellationToken ).ConfigureAwait( false ); + foreach ( var operation in operations ) + { + Func nullChecker; + if ( nullCheckers.TryGetValue( operation.Key, out nullChecker ) ) + { + if ( nullChecker( target ) ) + { + continue; + } + } + + await packer.PackStringAsync( operation.Key, cancellationToken ).ConfigureAwait( false ); + await operation.Value( packer, target, cancellationToken ).ConfigureAwait( false ); + } + } + else { - await packer.PackStringAsync( operation.Key, cancellationToken ).ConfigureAwait( false ); - await operation.Value( packer, target, cancellationToken ).ConfigureAwait( false ); + await packer.PackMapHeaderAsync( operations.Count, cancellationToken ).ConfigureAwait( false ); + foreach ( var operation in operations ) + { + // Compat path + await packer.PackStringAsync( operation.Key, cancellationToken ).ConfigureAwait( false ); + await operation.Value( packer, target, cancellationToken ).ConfigureAwait( false ); + } } } #endif // FEATURE_TAP } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/Polymorphic/IPolymorphicHelperAttributes.cs b/src/MsgPack/Serialization/Polymorphic/IPolymorphicHelperAttributes.cs index 0582c1edb..a2fed043e 100644 --- a/src/MsgPack/Serialization/Polymorphic/IPolymorphicHelperAttributes.cs +++ b/src/MsgPack/Serialization/Polymorphic/IPolymorphicHelperAttributes.cs @@ -44,7 +44,8 @@ internal interface IPolymorphicKnownTypeAttribute : IPolymorphicHelperAttribute /// internal interface IPolymorphicRuntimeTypeAttribute : IPolymorphicHelperAttribute { - // nothing + Type VerifierType { get; } + string VerifierMethodName { get; } } /// diff --git a/src/MsgPack/Serialization/Polymorphic/KnownTypePolymorphicMessagePackSerializer`1.cs b/src/MsgPack/Serialization/Polymorphic/KnownTypePolymorphicMessagePackSerializer`1.cs index 65c280823..4eda4c51d 100644 --- a/src/MsgPack/Serialization/Polymorphic/KnownTypePolymorphicMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/Polymorphic/KnownTypePolymorphicMessagePackSerializer`1.cs @@ -46,7 +46,7 @@ internal sealed class KnownTypePolymorphicMessagePackSerializer : MessagePack private readonly IDictionary _typeCodeMap; public KnownTypePolymorphicMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { if ( typeof( T ).GetIsValueType() ) { @@ -78,9 +78,9 @@ private static IDictionary BuildTypeHandleTypeCodeMap String.Join( CultureInfo.CurrentCulture.TextInfo.ListSeparator, typeHandleTypeCodeMapping.Select( kv => kv.Key ) -#if NETFX_35 || UNITY +#if NET35 || UNITY .Select( b => b.ToString( CultureInfo.InvariantCulture ) ).ToArray() -#endif // NETFX_35 || UNITY +#endif // NET35 || UNITY ) ) ); diff --git a/src/MsgPack/Serialization/Polymorphic/PolymorphicSerializerProvider`1.cs b/src/MsgPack/Serialization/Polymorphic/PolymorphicSerializerProvider`1.cs index 5625c17ca..24d2f392b 100644 --- a/src/MsgPack/Serialization/Polymorphic/PolymorphicSerializerProvider`1.cs +++ b/src/MsgPack/Serialization/Polymorphic/PolymorphicSerializerProvider`1.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -30,26 +30,34 @@ namespace MsgPack.Serialization.Polymorphic /// Provides polymorphism for serializers. /// /// - internal sealed class PolymorphicSerializerProvider : MessagePackSerializerProvider +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class PolymorphicSerializerProvider : MessagePackSerializerProvider { // This may be null for abstract typed collection which does not have corresponding concrete type. private readonly MessagePackSerializer _defaultSerializer; + private readonly PolymorphismSchema _defaultSchema; #if !UNITY public PolymorphicSerializerProvider( MessagePackSerializer defaultSerializer ) { this._defaultSerializer = defaultSerializer; + this._defaultSchema = PolymorphismSchema.Create( typeof( T ), null ); } #else public PolymorphicSerializerProvider( SerializationContext context, MessagePackSerializer defaultSerializer ) { this._defaultSerializer = MessagePackSerializer.Wrap( context, defaultSerializer ); + this._defaultSchema = PolymorphismSchema.Create( typeof( T ), null ); } #endif public override object Get( SerializationContext context, object providerParameter ) { - var schema = providerParameter as PolymorphismSchema; + var schema = ( providerParameter ?? this._defaultSchema ) as PolymorphismSchema; if ( schema == null || schema.UseDefault || schema.TargetType != typeof( T ) ) { @@ -73,4 +81,4 @@ public override object Get( SerializationContext context, object providerParamet } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/Polymorphic/RuntimeTypeVerifier.cs b/src/MsgPack/Serialization/Polymorphic/RuntimeTypeVerifier.cs new file mode 100644 index 000000000..b186705d2 --- /dev/null +++ b/src/MsgPack/Serialization/Polymorphic/RuntimeTypeVerifier.cs @@ -0,0 +1,202 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +#if DEBUG +#define ASSERT +#endif // DEBUG + +using System; +using System.Collections.Generic; +#if ASSERT +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +#endif // ASSERT +using System.Globalization; +using System.Reflection; +using System.Runtime.Serialization; +using System.Threading; + +namespace MsgPack.Serialization.Polymorphic +{ + internal static class RuntimeTypeVerifier + { + private const int CacheSize = 1000; + + private static readonly ReaderWriterLockSlim _resultCacheLock = new ReaderWriterLockSlim( LockRecursionPolicy.NoRecursion ); + private static readonly Dictionary, bool> _resultCache = new Dictionary, bool>( CacheSize ); + private static readonly Queue> _histories = new Queue>( CacheSize ); + + public static void Verify( AssemblyName assemblyName, string typeFullName, Func typeVerifier ) + { + var assemblyFullName = assemblyName.FullName; + if ( !VerifyCore( assemblyName, assemblyFullName, typeFullName, typeVerifier ) ) + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Type verifier rejects type '{0}'", typeFullName + ", " + assemblyFullName ) ); + } + } + + private static bool VerifyCore( AssemblyName assemblyName, string assemblyFullName, string typeFullName, Func typeVerifier ) + { + var key =new KeyValuePair( assemblyFullName, typeFullName ); + + _resultCacheLock.EnterReadLock(); + try + { + bool cachedResult; + if ( _resultCache.TryGetValue( key, out cachedResult ) ) + { + return cachedResult; + } + } + finally + { + _resultCacheLock.ExitReadLock(); + } + + bool result = typeVerifier( new PolymorphicTypeVerificationContext( typeFullName, assemblyName, assemblyFullName ) ); + + _resultCacheLock.EnterWriteLock(); + try + { + int count = _resultCache.Count; + _resultCache[ key ] = result; + if ( count < _resultCache.Count && CacheSize < _resultCache.Count ) + { + // Added. Start eviction. + var removalKey = _histories.Dequeue(); + var removed = _resultCache.Remove( removalKey ); +#if ASSERT + Contract.Assert( removed ); +#endif // ASSERT + } + +#if ASSERT + Contract.Assert( _histories.Count < 1000 ); +#endif // ASSERT + _histories.Enqueue( key ); + } + finally + { + _resultCacheLock.ExitWriteLock(); + } + + return result; + } + +#if UNITY && !UNITY_FULL + // from https://github.com/dotnet/corefx/blob/master/src/System.Collections/src/System/Collections/Generic/Queue.cs + private class Queue + { + private T[] _array; + private int _head; // The index from which to dequeue if the queue isn't empty. + private int _tail; // The index at which to enqueue if the queue isn't full. + private int _size; // Number of elements. + + private const int MinimumGrow = 4; + private const int GrowFactor = 200; // double each time + + // Creates a queue with room for capacity objects. The default grow factor + // is used. + // + public Queue( int capacity ) + { + _array = new T[ capacity ]; + } + + public int Count + { + get { return _size; } + } + + // Adds item to the tail of the queue. + // + public void Enqueue( T item ) + { + if ( _size == _array.Length ) + { + int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100); + if ( newcapacity < _array.Length + MinimumGrow ) + { + newcapacity = _array.Length + MinimumGrow; + } + SetCapacity( newcapacity ); + } + + _array[ _tail ] = item; + MoveNext( ref _tail ); + _size++; + } + + // Removes the object at the head of the queue and returns it. If the queue + // is empty, this method simply returns null. + public T Dequeue() + { + if ( _size == 0 ) + throw new InvalidOperationException( "Queue is empty." ); + + T removed = _array[_head]; + _array[ _head ] = default( T ); + MoveNext( ref _head ); + _size--; + return removed; + } + + // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity + // must be >= _size. + private void SetCapacity( int capacity ) + { + T[] newarray = new T[capacity]; + if ( _size > 0 ) + { + if ( _head < _tail ) + { + Array.Copy( _array, _head, newarray, 0, _size ); + } + else + { + Array.Copy( _array, _head, newarray, 0, _array.Length - _head ); + Array.Copy( _array, 0, newarray, _array.Length - _head, _tail ); + } + } + + _array = newarray; + _head = 0; + _tail = ( _size == capacity ) ? 0 : _size; + } + + // Increments the index wrapping it if necessary. + private void MoveNext( ref int index ) + { + // It is tempting to use the remainder operator here but it is actually much slower + // than a simple comparison and a rarely taken branch. + int tmp = index + 1; + index = ( tmp == _array.Length ) ? 0 : tmp; + } + } +#endif // UNITY && !UNITY_FULL + } +} diff --git a/src/MsgPack/Serialization/Polymorphic/TypeEmbedingPolymorphicMessagePackSerializer`1.cs b/src/MsgPack/Serialization/Polymorphic/TypeEmbedingPolymorphicMessagePackSerializer`1.cs index c6f7ed546..d3f581846 100644 --- a/src/MsgPack/Serialization/Polymorphic/TypeEmbedingPolymorphicMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/Polymorphic/TypeEmbedingPolymorphicMessagePackSerializer`1.cs @@ -36,7 +36,7 @@ internal sealed class TypeEmbedingPolymorphicMessagePackSerializer : MessageP private readonly PolymorphismSchema _schema; public TypeEmbedingPolymorphicMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { if ( typeof( T ).GetIsValueType() ) { @@ -73,7 +73,7 @@ protected internal override T UnpackFromCore( Unpacker unpacker ) TypeInfoEncoder.Decode( unpacker, // ReSharper disable once ConvertClosureToMethodGroup - u => TypeInfoEncoder.DecodeRuntimeTypeInfo( u ), // Lamda capture is more efficient. + u => TypeInfoEncoder.DecodeRuntimeTypeInfo( u, this._schema.TypeVerifier ), // Lamda capture is more efficient. ( t, u ) => ( T )this.GetActualTypeSerializer( t ).UnpackFrom( u ) ); } @@ -97,7 +97,7 @@ protected internal override Task UnpackFromAsyncCore( Unpacker unpacker, Canc TypeInfoEncoder.DecodeAsync( unpacker, // ReSharper disable once ConvertClosureToMethodGroup - ( u, c ) => TypeInfoEncoder.DecodeRuntimeTypeInfoAsync( u, c ), // Lamda capture is more efficient. + ( u, c ) => TypeInfoEncoder.DecodeRuntimeTypeInfoAsync( u, this._schema.TypeVerifier, c ), // Lamda capture is more efficient. ( t, u, c ) => this.GetActualTypeSerializer( t ).UnpackFromAsync( u, c ), cancellationToken ); diff --git a/src/MsgPack/Serialization/Polymorphic/TypeInfoEncoder.cs b/src/MsgPack/Serialization/Polymorphic/TypeInfoEncoder.cs index 2777a58a2..592ddef4d 100644 --- a/src/MsgPack/Serialization/Polymorphic/TypeInfoEncoder.cs +++ b/src/MsgPack/Serialization/Polymorphic/TypeInfoEncoder.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015-2016 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -36,7 +36,12 @@ namespace MsgPack.Serialization.Polymorphic /// /// Implements type info encoding for type embedding. /// - internal static class TypeInfoEncoder +#if UNITY && DEBUG + public +#else + internal +#endif + static class TypeInfoEncoder { private const string Elipsis = "."; @@ -95,10 +100,10 @@ public static async Task EncodeAsync( Packer packer, Type type, CancellationToke { var assemblyName = type.GetAssembly().GetName(); - await packer.PackArrayHeaderAsync( 2 , cancellationToken ).ConfigureAwait( false ); - await packer.PackArrayHeaderAsync( 6 , cancellationToken ).ConfigureAwait( false ); + await packer.PackArrayHeaderAsync( 2, cancellationToken ).ConfigureAwait( false ); + await packer.PackArrayHeaderAsync( 6, cancellationToken ).ConfigureAwait( false ); - await packer.PackAsync( ( byte ) TypeInfoEncoding.RawCompressed, cancellationToken ).ConfigureAwait( false ); + await packer.PackAsync( ( byte )TypeInfoEncoding.RawCompressed, cancellationToken ).ConfigureAwait( false ); // Omit namespace prefix when it equals to declaring assembly simple name. var compressedTypeName = @@ -111,7 +116,7 @@ public static async Task EncodeAsync( Packer packer, Type type, CancellationToke Buffer.BlockCopy( BitConverter.GetBytes( assemblyName.Version.Build ), 0, version, 8, 4 ); Buffer.BlockCopy( BitConverter.GetBytes( assemblyName.Version.Revision ), 0, version, 12, 4 ); - await packer.PackStringAsync( compressedTypeName , cancellationToken ).ConfigureAwait( false ); + await packer.PackStringAsync( compressedTypeName, cancellationToken ).ConfigureAwait( false ); await packer.PackStringAsync( assemblyName.Name, cancellationToken ).ConfigureAwait( false ); await packer.PackBinaryAsync( version, cancellationToken ).ConfigureAwait( false ); await packer.PackStringAsync( assemblyName.GetCultureName(), cancellationToken ).ConfigureAwait( false ); @@ -194,7 +199,7 @@ public static async Task DecodeAsync( Unpacker unpacker, Func DecodeAsync( Unpacker unpacker, Func typeVerifier ) { CheckUnpackerForRuntimeTypeInfoDecoding( unpacker ); @@ -272,7 +277,11 @@ public static Type DecodeRuntimeTypeInfo( Unpacker unpacker ) ThrowFailedToDecodeAssemblyKeyToken(); } - return LoadDecodedType( assemblySimpleName, version, culture, publicKeyToken, compressedTypeName ); + var assemblyName = BuildAssemblyName( assemblySimpleName, version, culture, publicKeyToken ); + var typeFullName = DecompressTypeName( assemblyName.Name, compressedTypeName ); + RuntimeTypeVerifier.Verify( assemblyName, typeFullName, typeVerifier ); + + return LoadDecodedType( assemblyName, typeFullName ); } } @@ -310,7 +319,7 @@ private static void ThrowFailedToDecodeAssemblyKeyToken() { throw new SerializationException( "Failed to decode public key token component." ); } - + private static void CheckUnpackerForRuntimeTypeInfoDecoding( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) @@ -334,24 +343,6 @@ private static void ThrowEncodedTypeDoesNotHaveValidArrayItems() throw new SerializationException( "Components count of type info is not valid." ); } - private static Type LoadDecodedType( string assemblySimpleName, byte[] version, string culture, byte[] publicKeyToken, string compressedTypeName ) - { - return - Assembly.Load( - BuildAssemblyName( assemblySimpleName, version, culture, publicKeyToken ) -#if SILVERLIGHT - .ToString() -#endif // SILVERLIGHT - ).GetType( - compressedTypeName.StartsWith( Elipsis, StringComparison.Ordinal ) - ? assemblySimpleName + compressedTypeName - : compressedTypeName -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - , throwOnError: true -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - ); - } - private static AssemblyName BuildAssemblyName( string assemblySimpleName, byte[] version, string culture, byte[] publicKeyToken ) { #if !NETSTANDARD1_1 && !NETSTANDARD1_3 @@ -361,10 +352,10 @@ private static AssemblyName BuildAssemblyName( string assemblySimpleName, byte[] Name = assemblySimpleName, Version = new Version( - BitConverter.ToInt32( version, 0 ), - BitConverter.ToInt32( version, 4 ), - BitConverter.ToInt32( version, 8 ), - BitConverter.ToInt32( version, 12 ) + BitConverter.ToInt32( version, 0 ), + BitConverter.ToInt32( version, 4 ), + BitConverter.ToInt32( version, 8 ), + BitConverter.ToInt32( version, 12 ) ), CultureInfo = String.IsNullOrEmpty( culture ) @@ -397,9 +388,33 @@ private static AssemblyName BuildAssemblyName( string assemblySimpleName, byte[] #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 } + private static string DecompressTypeName( string assemblySimpleName, string compressedTypeName ) + { + return + compressedTypeName.StartsWith( Elipsis, StringComparison.Ordinal ) + ? assemblySimpleName + compressedTypeName + : compressedTypeName; + } + + private static Type LoadDecodedType( AssemblyName assemblyName, string typeFullName ) + { + return + Assembly.Load( + assemblyName +#if SILVERLIGHT + .ToString() +#endif // SILVERLIGHT + ).GetType( + typeFullName +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + , throwOnError: true +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + ); + } + #if FEATURE_TAP - public static async Task DecodeRuntimeTypeInfoAsync( Unpacker unpacker, CancellationToken cancellationToken ) + public static async Task DecodeRuntimeTypeInfoAsync( Unpacker unpacker, Func typeVerifier, CancellationToken cancellationToken ) { CheckUnpackerForRuntimeTypeInfoDecoding( unpacker ); @@ -446,11 +461,13 @@ public static async Task DecodeRuntimeTypeInfoAsync( Unpacker unpacker, Ca ThrowFailedToDecodeAssemblyKeyToken(); } - return LoadDecodedType( assemblySimpleName.Value, version.Value, culture.Value, publicKeyToken.Value, compressedTypeName.Value ); + var assemblyName = BuildAssemblyName( assemblySimpleName.Value, version.Value, culture.Value, publicKeyToken.Value ); + var typeFullName = DecompressTypeName( assemblyName.Name, compressedTypeName.Value ); + RuntimeTypeVerifier.Verify( assemblyName, typeFullName, typeVerifier ); + return LoadDecodedType( assemblyName, typeFullName ); } } #endif // FEATURE_TAP - } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/PolymorphicTypeVerificationContext.cs b/src/MsgPack/Serialization/PolymorphicTypeVerificationContext.cs new file mode 100644 index 000000000..679a40627 --- /dev/null +++ b/src/MsgPack/Serialization/PolymorphicTypeVerificationContext.cs @@ -0,0 +1,176 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +#if DEBUG +#define ASSERT +#endif // DEBUG + +using System; +#if ASSERT +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +#endif // ASSERT +using System.Reflection; + +namespace MsgPack.Serialization +{ + /// + /// Represents and encapsulates context informatino to verify actual type for runtime type polymorphism. + /// + public struct PolymorphicTypeVerificationContext : IEquatable + { + // TODO: Use ref for internal struct on stack. + + private readonly string _loadingTypeFullName; + + /// + /// Gets the full type name including its namespace to be loaded. + /// + /// + /// The full type name including its namespace to be loaded. This value will not be null. + /// + public string LoadingTypeFullName { get { return this._loadingTypeFullName; } } + + private readonly string _loadingAssemblyFullName; + + /// + /// Gets the full name of the loading assembly. + /// + /// + /// The full name of the loading assembly. + /// + public string LoadingAssemblyFullName { get { return this._loadingAssemblyFullName; } } + + private readonly AssemblyName _loadingAssemblyName; + + /// + /// Gets the name of the loading assembly. + /// + /// + /// The name of the loading assembly. + /// + public AssemblyName LoadingAssemblyName { get { return this._loadingAssemblyName; } } + + internal PolymorphicTypeVerificationContext( string loadingTypeFullName, AssemblyName loadingAssemblyName, string loadingAssemblyFullName ) + { +#if ASSERT + Contract.Assert( loadingTypeFullName != null ); + Contract.Assert( loadingAssemblyName != null ); +#endif // ASSERT + this._loadingTypeFullName = loadingTypeFullName; + this._loadingAssemblyName = loadingAssemblyName; + this._loadingAssemblyFullName = loadingAssemblyFullName; + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + if ( this._loadingTypeFullName == null ) + { + return String.Empty; + } + + return this._loadingTypeFullName + ", " + this._loadingAssemblyFullName; + } + + /// + /// Determines whether the specified is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals( object obj ) + { + if ( !( obj is PolymorphicTypeVerificationContext ) ) + { + return false; + } + + return this.Equals( ( PolymorphicTypeVerificationContext ) obj ); + } + + /// + /// Determines whether the specified is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public bool Equals( PolymorphicTypeVerificationContext other ) + { + return this._loadingTypeFullName == other._loadingTypeFullName && this._loadingAssemblyFullName == other._loadingAssemblyFullName; + } + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() + { + if ( this._loadingTypeFullName == null ) + { + return 0; + } + + return this._loadingTypeFullName.GetHashCode() ^ this._loadingAssemblyFullName.GetHashCode(); + } + + /// + /// Determines whether the specified s are equal. + /// + /// The . + /// The . + /// + /// true if the specified s are equal to each other; otherwise, false. + /// + public static bool operator ==( PolymorphicTypeVerificationContext left, PolymorphicTypeVerificationContext right ) + { + return left.Equals( right ); + } + + /// + /// Determines whether the specified s are not equal. + /// + /// The . + /// The . + /// + /// true if the specified s are not equal; otherwise, false. + /// + public static bool operator !=( PolymorphicTypeVerificationContext left, PolymorphicTypeVerificationContext right ) + { + return !left.Equals( right ); + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/PolymorphismSchema.Constructors.cs b/src/MsgPack/Serialization/PolymorphismSchema.Constructors.cs index 7e01fbfcd..cce22f106 100644 --- a/src/MsgPack/Serialization/PolymorphismSchema.Constructors.cs +++ b/src/MsgPack/Serialization/PolymorphismSchema.Constructors.cs @@ -1,7 +1,7 @@ #region -- License Terms -- // MessagePack for CLI // -// Copyright (C) 2015-2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,9 +23,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -#if !UNITY || MSGPACK_UNITY_FULL -using System.ComponentModel; -#endif // !UNITY || MSGPACK_UNITY_FULL using System.Linq; namespace MsgPack.Serialization @@ -55,12 +52,15 @@ private PolymorphismSchema() private PolymorphismSchema( Type targetType, PolymorphismType polymorphismType, + Func typeVerifier, PolymorphismSchemaChildrenType childrenType, - params PolymorphismSchema[] childItemSchemaList ) + params PolymorphismSchema[] childItemSchemaList + ) : this( targetType, polymorphismType, new ReadOnlyDictionary( EmptyMap ), + typeVerifier, childrenType, new ReadOnlyCollection( ( childItemSchemaList ?? EmptyChildren ).Select( x => x ?? Default ).ToArray() @@ -71,12 +71,15 @@ private PolymorphismSchema( Type targetType, PolymorphismType polymorphismType, IDictionary codeTypeMapping, + Func typeVerifier, PolymorphismSchemaChildrenType childrenType, - params PolymorphismSchema[] childItemSchemaList ) + params PolymorphismSchema[] childItemSchemaList + ) : this( targetType, polymorphismType, new ReadOnlyDictionary( codeTypeMapping ), + typeVerifier, childrenType, new ReadOnlyCollection( ( childItemSchemaList ?? EmptyChildren ).Select( x => x ?? Default ).ToArray() @@ -87,8 +90,10 @@ private PolymorphismSchema( Type targetType, PolymorphismType polymorphismType, ReadOnlyDictionary codeTypeMapping, + Func typeVerifier, PolymorphismSchemaChildrenType childrenType, - ReadOnlyCollection childItemSchemaList ) + ReadOnlyCollection childItemSchemaList + ) { if ( targetType == null ) { @@ -100,6 +105,7 @@ private PolymorphismSchema( this._codeTypeMapping = codeTypeMapping; this.ChildrenType = childrenType; this._children = childItemSchemaList; + this.TypeVerifier = typeVerifier ?? DefaultTypeVerfiier; } // Plane @@ -110,12 +116,21 @@ private PolymorphismSchema( /// The type of the serialization target. /// A new instance of the class for non-collection object which uses type embedding based polymorphism. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForPolymorphicObject( Type targetType ) { - return new PolymorphismSchema( targetType, PolymorphismType.RuntimeType, PolymorphismSchemaChildrenType.None ); + return new PolymorphismSchema( targetType, PolymorphismType.RuntimeType, DefaultTypeVerfiier, PolymorphismSchemaChildrenType.None ); + } + + /// + /// Creates a new instance of the class for non-collection object which uses type embedding based polymorphism. + /// + /// The type of the serialization target. + /// The delegate which verifies loading type in runtime type polymorphism. + /// A new instance of the class for non-collection object which uses type embedding based polymorphism. + /// is null. + public static PolymorphismSchema ForPolymorphicObject( Type targetType, Func typeVerifier ) + { + return new PolymorphismSchema( targetType, PolymorphismType.RuntimeType, typeVerifier, PolymorphismSchemaChildrenType.None ); } /// @@ -125,9 +140,6 @@ public static PolymorphismSchema ForPolymorphicObject( Type targetType ) /// The code-type mapping which maps between ext-type codes and .NET s. /// A new instance of the class for non-collection object which uses ext-type code mapping based polymorphism. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForPolymorphicObject( Type targetType, IDictionary codeTypeMapping ) { return @@ -135,6 +147,7 @@ public static PolymorphismSchema ForPolymorphicObject( Type targetType, IDiction targetType, PolymorphismType.KnownTypes, codeTypeMapping, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.None ); } @@ -148,15 +161,13 @@ public static PolymorphismSchema ForPolymorphicObject( Type targetType, IDiction /// The schema for collection items of the serialization target collection. /// A new instance of the class for collection object which uses declared type or context specified concrete type. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForContextSpecifiedCollection( Type targetType, PolymorphismSchema itemSchema ) { return new PolymorphismSchema( targetType, PolymorphismType.None, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.CollectionItems, itemSchema ); @@ -169,15 +180,33 @@ public static PolymorphismSchema ForContextSpecifiedCollection( Type targetType, /// The schema for collection items of the serialization target collection. /// A new instance of the class for collection object which uses type embedding based polymorphism. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForPolymorphicCollection( Type targetType, PolymorphismSchema itemSchema ) { return new PolymorphismSchema( targetType, PolymorphismType.RuntimeType, + DefaultTypeVerfiier, + PolymorphismSchemaChildrenType.CollectionItems, + itemSchema + ); + } + + /// + /// Creates a new instance of the class for collection object which uses type embedding based polymorphism. + /// + /// The type of the serialization target. + /// The schema for collection items of the serialization target collection. + /// The delegate which verifies loading type in runtime type polymorphism. + /// A new instance of the class for collection object which uses type embedding based polymorphism. + /// is null. + public static PolymorphismSchema ForPolymorphicCollection( Type targetType, PolymorphismSchema itemSchema, Func typeVerifier ) + { + return + new PolymorphismSchema( + targetType, + PolymorphismType.RuntimeType, + typeVerifier, PolymorphismSchemaChildrenType.CollectionItems, itemSchema ); @@ -191,13 +220,10 @@ public static PolymorphismSchema ForPolymorphicCollection( Type targetType, Poly /// The schema for collection items of the serialization target collection. /// A new instance of the class for collection object which uses ext-type code mapping based polymorphism. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForPolymorphicCollection( Type targetType, IDictionary codeTypeMapping, - PolymorphismSchema itemSchema + PolymorphismSchema itemSchema ) { return @@ -205,6 +231,7 @@ PolymorphismSchema itemSchema targetType, PolymorphismType.KnownTypes, codeTypeMapping, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.CollectionItems, itemSchema ); @@ -220,18 +247,17 @@ PolymorphismSchema itemSchema /// The schema for dictionary values of the serialization target dictionary. /// A new instance of the class for dictionary object which uses declared type or context specified concrete type. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForContextSpecifiedDictionary( Type targetType, PolymorphismSchema keySchema, - PolymorphismSchema valueSchema ) + PolymorphismSchema valueSchema + ) { return new PolymorphismSchema( targetType, PolymorphismType.None, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.DictionaryKeyValues, keySchema, valueSchema @@ -246,9 +272,6 @@ public static PolymorphismSchema ForContextSpecifiedDictionary( /// The schema for dictionary values of the serialization target dictionary. /// A new instance of the class for dictionary object which uses type embedding based polymorphism. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForPolymorphicDictionary( Type targetType, PolymorphismSchema keySchema, @@ -259,6 +282,34 @@ PolymorphismSchema valueSchema new PolymorphismSchema( targetType, PolymorphismType.RuntimeType, + DefaultTypeVerfiier, + PolymorphismSchemaChildrenType.DictionaryKeyValues, + keySchema, + valueSchema + ); + } + + /// + /// Creates a new instance of the class for dictionary object which uses type embedding based polymorphism. + /// + /// The type of the serialization target. + /// The schema for dictionary keys of the serialization target dictionary. + /// The schema for dictionary values of the serialization target dictionary. + /// The delegate which verifies loading type in runtime type polymorphism. + /// A new instance of the class for dictionary object which uses type embedding based polymorphism. + /// is null. + public static PolymorphismSchema ForPolymorphicDictionary( + Type targetType, + PolymorphismSchema keySchema, + PolymorphismSchema valueSchema, + Func typeVerifier + ) + { + return + new PolymorphismSchema( + targetType, + PolymorphismType.RuntimeType, + typeVerifier, PolymorphismSchemaChildrenType.DictionaryKeyValues, keySchema, valueSchema @@ -274,14 +325,11 @@ PolymorphismSchema valueSchema /// The schema for dictionary values of the serialization target dictionary. /// A new instance of the class for dictionary object which uses ext-type code mapping based polymorphism. /// is null. -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL public static PolymorphismSchema ForPolymorphicDictionary( Type targetType, IDictionary codeTypeMapping, PolymorphismSchema keySchema, - PolymorphismSchema valueSchema + PolymorphismSchema valueSchema ) { return @@ -289,13 +337,14 @@ PolymorphismSchema valueSchema targetType, PolymorphismType.KnownTypes, codeTypeMapping, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.DictionaryKeyValues, keySchema, valueSchema ); } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY // Tuple items /// @@ -306,7 +355,6 @@ PolymorphismSchema valueSchema /// A new instance of the class for object. /// is null. /// A count of does not match for an arity of the tuple type specified as . - [EditorBrowsable( EditorBrowsableState.Never )] public static PolymorphismSchema ForPolymorphicTuple( Type targetType, PolymorphismSchema[] itemSchemaList ) { VerifyArity( targetType, itemSchemaList ); @@ -314,6 +362,7 @@ public static PolymorphismSchema ForPolymorphicTuple( Type targetType, Polymorph new PolymorphismSchema( targetType, PolymorphismType.None, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.TupleItems, itemSchemaList ); @@ -332,7 +381,7 @@ private static void VerifyArity( Type tupleType, ICollection throw new ArgumentException( "An arity of itemSchemaList does not match for an arity of the tuple.", "itemSchemaList" ); } } -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY internal PolymorphismSchema FilterSelf() { @@ -341,7 +390,7 @@ internal PolymorphismSchema FilterSelf() return this; } - return new PolymorphismSchema( this.TargetType, PolymorphismType.None, this._codeTypeMapping, this.ChildrenType, this._children ); + return new PolymorphismSchema( this.TargetType, PolymorphismType.None, this._codeTypeMapping, this.TypeVerifier, this.ChildrenType, this._children ); } } } \ No newline at end of file diff --git a/src/MsgPack/Serialization/PolymorphismSchema.Internals.cs b/src/MsgPack/Serialization/PolymorphismSchema.Internals.cs index 1d4e95251..df29d8e02 100644 --- a/src/MsgPack/Serialization/PolymorphismSchema.Internals.cs +++ b/src/MsgPack/Serialization/PolymorphismSchema.Internals.cs @@ -1,7 +1,7 @@ -#region -- License Terms -- +#region -- License Terms -- // MessagePack for CLI // -// Copyright (C) 2015-2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2018 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,6 +14,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -22,11 +26,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; using System.Reflection; @@ -39,10 +43,17 @@ namespace MsgPack.Serialization { partial class PolymorphismSchema { + private static readonly Func DefaultTypeVerfiier = _ => true; + /// /// Default instance (null object). /// - internal static readonly PolymorphismSchema Default = new PolymorphismSchema(); +#if UNITY && DEBUG + public +#else + internal +#endif + static readonly PolymorphismSchema Default = new PolymorphismSchema(); /// /// ForPolymorphicObject( Type targetType ) @@ -92,13 +103,13 @@ partial class PolymorphismSchema internal static readonly MethodInfo ForPolymorphicDictionaryCodeTypeMappingMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicDictionary", new[] { typeof( Type ), typeof( IDictionary ), typeof( PolymorphismSchema ), typeof( PolymorphismSchema ) } ); -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY /// /// ForPolymorphicTuple( Type targetType, PolymorphismSchema[] itemSchemaList ) /// internal static readonly MethodInfo ForPolymorphicTupleMethod = typeof( PolymorphismSchema ).GetMethod( "ForPolymorphicTuple", new[] { typeof( Type ), typeof( PolymorphismSchema[]) } ); -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY internal static readonly ConstructorInfo CodeTypeMapConstructor = typeof( Dictionary<,> ).MakeGenericType( typeof( string ), typeof( Type ) ) @@ -162,7 +173,7 @@ private void ToDebugString( StringBuilder buffer ) break; } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY case PolymorphismSchemaChildrenType.TupleItems: { buffer.Append( ", TupleItemsSchema:[" ); @@ -190,7 +201,7 @@ private void ToDebugString( StringBuilder buffer ) break; } -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY } buffer.Append( '}' ); @@ -203,18 +214,50 @@ internal static PolymorphismSchema Create( #else SerializingMember memberMayBeNull #endif // !UNITY - ) + ) { if ( type.GetIsValueType() ) { + SerializerDebugging.TracePolimorphicSchemaEvent( + "Returns default because '{0}' is value type: {1}", + memberMayBeNull == null +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + ? type +#else + ? type.GetTypeInfo() +#endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !UNITY + : memberMayBeNull.Value.Member, +#else + : memberMayBeNull.Member, +#endif + Default + ); // Value types will never be polymorphic. return Default; } if ( memberMayBeNull == null ) { - // Using default for collection/tuple items. - return Default; + var schema = + CreateCore( +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + type, +#else + type.GetTypeInfo(), +#endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + Default + ); + SerializerDebugging.TracePolimorphicSchemaEvent( + "Returns root type schema for '{0}': {1}", +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + type, +#else + type.GetTypeInfo(), +#endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + schema + ); + return schema; } #if !UNITY @@ -223,28 +266,48 @@ SerializingMember memberMayBeNull var member = memberMayBeNull; #endif // !UNITY - var table = TypeTable.Create( member.Member ); + return + CreateCore( + member.Member, + CreateCore( +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + type, +#else + type.GetTypeInfo(), +#endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + Default + ) + ); + } + + private static PolymorphismSchema CreateCore( MemberInfo member, PolymorphismSchema defaultSchema ) + { + var table = TypeTable.Create( member, defaultSchema ); - var traits = member.Member.GetMemberValueType().GetCollectionTraits( CollectionTraitOptions.None ); + var traits = member.GetMemberValueType().GetCollectionTraits( CollectionTraitOptions.None, allowNonCollectionEnumerableTypes: false ); switch ( traits.CollectionType ) { case CollectionKind.Array: { if ( !table.Member.Exists && !table.CollectionItem.Exists ) { - return Default; + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have own nor items schema: {1}", member, defaultSchema ); + return defaultSchema; } + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns collection schema for '{0}': {1}", member, defaultSchema ); return new PolymorphismSchema( - member.Member.GetMemberValueType(), + member.GetMemberValueType(), table.Member.PolymorphismType, table.Member.CodeTypeMapping, + table.Member.TypeVerifier, PolymorphismSchemaChildrenType.CollectionItems, new PolymorphismSchema( traits.ElementType, table.CollectionItem.PolymorphismType, table.CollectionItem.CodeTypeMapping, + table.CollectionItem.TypeVerifier, PolymorphismSchemaChildrenType.None ) ); @@ -253,71 +316,83 @@ SerializingMember memberMayBeNull { if ( !table.Member.Exists && !table.DictionaryKey.Exists && !table.CollectionItem.Exists ) { - return Default; + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have own, keys, nor items schema: {1}", member, defaultSchema ); + return defaultSchema; } + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns dictionary schema for '{0}': {1}", member, defaultSchema ); return new PolymorphismSchema( - member.Member.GetMemberValueType(), + member.GetMemberValueType(), table.Member.PolymorphismType, table.Member.CodeTypeMapping, + table.Member.TypeVerifier, PolymorphismSchemaChildrenType.DictionaryKeyValues, new PolymorphismSchema( traits.ElementType.GetGenericArguments()[ 0 ], table.DictionaryKey.PolymorphismType, table.DictionaryKey.CodeTypeMapping, + table.DictionaryKey.TypeVerifier, PolymorphismSchemaChildrenType.None ), new PolymorphismSchema( traits.ElementType.GetGenericArguments()[ 1 ], table.CollectionItem.PolymorphismType, table.CollectionItem.CodeTypeMapping, + table.CollectionItem.TypeVerifier, PolymorphismSchemaChildrenType.None ) ); } default: { -#if !NETFX_35 && !UNITY - if ( TupleItems.IsTuple( member.Member.GetMemberValueType() ) ) +#if !NET35 && !UNITY + if ( TupleItems.IsTuple( member.GetMemberValueType() ) ) { if ( table.TupleItems.Count == 0 ) { - return Default; + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have any tuple items schema: {1}", member, defaultSchema ); + return defaultSchema; } - var tupleItemTypes = TupleItems.GetTupleItemTypes( member.Member.GetMemberValueType() ); + var tupleItemTypes = TupleItems.GetTupleItemTypes( member.GetMemberValueType() ); + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns tuple items schema for '{0}': {1}", member, defaultSchema ); return new PolymorphismSchema( - member.Member.GetMemberValueType(), + member.GetMemberValueType(), PolymorphismType.None, EmptyMap, + DefaultTypeVerfiier, PolymorphismSchemaChildrenType.TupleItems, table.TupleItems - .Zip(tupleItemTypes, (e,t) => new { Entry = e, ItemType = t }) + .Zip( tupleItemTypes, ( e, t ) => new { Entry = e, ItemType = t } ) .Select( e => new PolymorphismSchema( e.ItemType, - e.Entry.PolymorphismType, + e.Entry.PolymorphismType, e.Entry.CodeTypeMapping, + e.Entry.TypeVerifier, PolymorphismSchemaChildrenType.None ) ).ToArray() ); } else -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY { if ( !table.Member.Exists ) { - return Default; + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns default because '{0}' does not have own schema: {1}", member, defaultSchema ); + return defaultSchema; } + SerializerDebugging.TracePolimorphicSchemaEvent( "Returns type of member schema for '{0}'.", member, defaultSchema ); return new PolymorphismSchema( - member.Member.GetMemberValueType(), + member.GetMemberValueType(), table.Member.PolymorphismType, table.Member.CodeTypeMapping, + table.Member.TypeVerifier, PolymorphismSchemaChildrenType.None ); } @@ -330,46 +405,46 @@ private struct TypeTable public readonly TypeTableEntry Member; public readonly TypeTableEntry CollectionItem; public readonly TypeTableEntry DictionaryKey; -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY public readonly IList TupleItems; -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY private TypeTable( TypeTableEntry member, TypeTableEntry collectionItem, TypeTableEntry dictionaryKey -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY , IList tupleItems -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY ) { this.Member = member; this.CollectionItem = collectionItem; this.DictionaryKey = dictionaryKey; -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY this.TupleItems = tupleItems; -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY } - public static TypeTable Create( MemberInfo member ) + public static TypeTable Create( MemberInfo member, PolymorphismSchema defaultSchema ) { return new TypeTable( - TypeTableEntry.Create( member, PolymorphismTarget.Member ), - TypeTableEntry.Create( member, PolymorphismTarget.CollectionItem ), - TypeTableEntry.Create( member, PolymorphismTarget.DictionaryKey ) -#if !NETFX_35 && !UNITY + TypeTableEntry.Create( member, PolymorphismTarget.Member, defaultSchema ), + TypeTableEntry.Create( member, PolymorphismTarget.CollectionItem, defaultSchema.TryGetItemSchema() ), + TypeTableEntry.Create( member, PolymorphismTarget.DictionaryKey, defaultSchema.TryGetKeySchema() ) +#if !NET35 && !UNITY , TypeTableEntry.CreateTupleItems( member ) -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY ); } } private sealed class TypeTableEntry { -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY private static readonly TypeTableEntry[] EmptyEntries = new TypeTableEntry[ 0 ]; -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY private readonly Dictionary _knownTypeMapping = new Dictionary(); @@ -392,11 +467,14 @@ public PolymorphismType PolymorphismType public bool Exists { get { return this._useTypeEmbedding || this._knownTypeMapping.Count > 0; } } + public Func TypeVerifier { get; private set; } + private TypeTableEntry() { } - public static TypeTableEntry Create( MemberInfo member, PolymorphismTarget targetType ) + public static TypeTableEntry Create( MemberInfo member, PolymorphismTarget targetType, PolymorphismSchema defaultSchema ) { var result = new TypeTableEntry(); + var memberName = member.ToString(); foreach ( var attribute in member.GetCustomAttributes( false ) @@ -404,13 +482,20 @@ var attribute in .Where( a => a.Target == targetType ) ) { - result.Interpret( attribute, member.ToString(), -1 ); + // TupleItem schema should never come here, so passing -1 as tupleItemNumber is OK. + result.Interpret( attribute, memberName, -1 ); + } + + if ( defaultSchema != null ) + { + // TupleItem schema should never come here, so passing -1 as tupleItemNumber is OK. + result.SetDefault( targetType, memberName, -1, defaultSchema ); } return result; } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY public static TypeTableEntry[] CreateTupleItems( MemberInfo member ) { if ( !TupleItems.IsTuple( member.GetMemberValueType() ) ) @@ -419,7 +504,7 @@ public static TypeTableEntry[] CreateTupleItems( MemberInfo member ) } var tupleItems = TupleItems.GetTupleItemTypes( member.GetMemberValueType() ); - var result = Enumerable.Repeat( default( object ), tupleItems.Count ).Select( _ => new TypeTableEntry() ).ToArray(); + var result = tupleItems.Select( _ => new TypeTableEntry() ).ToArray(); foreach ( var attribute in member.GetCustomAttributes( false ) @@ -432,32 +517,15 @@ var attribute in return result; } -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY private void Interpret( IPolymorphicHelperAttribute attribute, string memberName, int tupleItemNumber ) { var asKnown = attribute as IPolymorphicKnownTypeAttribute; if ( asKnown != null ) { - if ( this._useTypeEmbedding ) - { - throw new SerializationException( - GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( attribute, memberName, tupleItemNumber ) - ); - } - - var typeCode = asKnown.TypeCode; - try - { - this._knownTypeMapping.Add( typeCode, asKnown.BindingType ); - return; - } - catch ( ArgumentException ) - { - throw new SerializationException( - GetCannotDuplicateKnownTypeCodeErrorMessage( attribute, typeCode, memberName, tupleItemNumber ) - ); - } + this.SetKnownType( attribute.Target, memberName, tupleItemNumber, asKnown.TypeCode, asKnown.BindingType ); + return; } #if DEBUG @@ -479,19 +547,73 @@ private void Interpret( IPolymorphicHelperAttribute attribute, string memberName ); } + this.SetRuntimeType( attribute.Target, memberName, tupleItemNumber, GetVerifier( attribute as IPolymorphicRuntimeTypeAttribute ) ); + } + + private void SetDefault( PolymorphismTarget target, string memberName, int tupleItemNumber, PolymorphismSchema defaultSchema ) + { + if ( this._useTypeEmbedding || this._knownTypeMapping.Count > 0 ) + { + // Default is not required. + return; + } + + switch ( defaultSchema.PolymorphismType ) + { + case PolymorphismType.KnownTypes: + { + foreach ( var typeMapping in defaultSchema.CodeTypeMapping ) + { + this.SetKnownType( target, memberName, tupleItemNumber, typeMapping.Key, typeMapping.Value ); + } + + break; + } + case PolymorphismType.RuntimeType: + { + this.SetRuntimeType( target, memberName, tupleItemNumber, defaultSchema.TypeVerifier ); + break; + } + } + } + + private void SetKnownType( PolymorphismTarget target, string memberName, int tupleItemNumber, string typeCode, Type bindingType ) + { + if ( this._useTypeEmbedding ) + { + throw new SerializationException( + GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( target, memberName, tupleItemNumber ) + ); + } + + try + { + this._knownTypeMapping.Add( typeCode, bindingType ); + this.TypeVerifier = DefaultTypeVerfiier; + } + catch ( ArgumentException ) + { + throw new SerializationException( + GetCannotDuplicateKnownTypeCodeErrorMessage( target, typeCode, memberName, tupleItemNumber ) + ); + } + } + + private void SetRuntimeType( PolymorphismTarget target, string memberName, int tupleItemNumber, Func typeVerifier ) + { if ( this._knownTypeMapping.Count > 0 ) { throw new SerializationException( - GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( attribute, memberName, tupleItemNumber ) + GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( target, memberName, tupleItemNumber ) ); } + this.TypeVerifier = typeVerifier; this._useTypeEmbedding = true; } - - private static string GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( IPolymorphicHelperAttribute attribute, string memberName, int tupleItemNumber ) + private static string GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( PolymorphismTarget target, string memberName, int? tupleItemNumber ) { - switch ( attribute.Target ) + switch ( target ) { case PolymorphismTarget.CollectionItem: { @@ -541,9 +663,9 @@ private static string GetCannotSpecifyKnownTypeAndRuntimeTypeErrorMessage( IPoly } } - private static string GetCannotDuplicateKnownTypeCodeErrorMessage( IPolymorphicHelperAttribute attribute, string typeCode, string memberName, int tupleItemNumber ) + private static string GetCannotDuplicateKnownTypeCodeErrorMessage( PolymorphismTarget target, string typeCode, string memberName, int tupleItemNumber ) { - switch ( attribute.Target ) + switch ( target ) { case PolymorphismTarget.CollectionItem: { @@ -588,6 +710,52 @@ private static string GetCannotDuplicateKnownTypeCodeErrorMessage( IPolymorphicH } } } + + private static Func GetVerifier( IPolymorphicRuntimeTypeAttribute attribute ) + { + if ( attribute.VerifierType == null ) + { + // Use default. + return DefaultTypeVerfiier; + } + + if ( String.IsNullOrEmpty( attribute.VerifierMethodName ) ) + { + throw new SerializationException( "VerifierMethodName cannot be null nor empty if VerifierType is specified." ); + } + + // Explore [static] bool X(PolymorphicTypeVerificationContext) + var method = attribute.VerifierType.GetRuntimeMethods().SingleOrDefault( m => IsVerificationMethod( m, attribute.VerifierMethodName ) ); + if ( method == null ) + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "A public static or instance method named '{0}' with single parameter typed PolymorphicTypeVerificationContext in type '{1}'.", attribute.VerifierMethodName, attribute.VerifierMethodName ) ); + } + + if ( method.IsStatic ) + { + return method.CreateDelegate( typeof( Func ) ) as Func; + } + else + { + return method.CreateDelegate( typeof( Func ), Activator.CreateInstance( attribute.VerifierType ) ) as Func; + } + } + + private static bool IsVerificationMethod( MethodInfo method, string name ) + { + if ( method.ReturnType != typeof( bool ) ) + { + return false; + } + + if ( method.Name != name ) + { + return false; + } + + var parameters = method.GetParameters(); + return parameters.Length == 1 && parameters[ 0 ].ParameterType.IsAssignableFrom( typeof( PolymorphicTypeVerificationContext ) ); + } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/PolymorphismSchema.cs b/src/MsgPack/Serialization/PolymorphismSchema.cs index 3fe048ab2..8fc7648a7 100644 --- a/src/MsgPack/Serialization/PolymorphismSchema.cs +++ b/src/MsgPack/Serialization/PolymorphismSchema.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,25 +25,14 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -#if !UNITY || MSGPACK_UNITY_FULL -using System.ComponentModel; -#endif // !UNITY || MSGPACK_UNITY_FULL using System.Diagnostics; using System.Linq; namespace MsgPack.Serialization { /// - /// - /// This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - /// - /// - /// A provider parameter to support polymorphism. - /// + /// A provider parameter to support polymorphism. /// -#if !UNITY || MSGPACK_UNITY_FULL - [EditorBrowsable( EditorBrowsableState.Never )] -#endif // !UNITY || MSGPACK_UNITY_FULL [DebuggerDisplay("{DebugString}")] public sealed partial class PolymorphismSchema { @@ -74,8 +63,11 @@ public sealed partial class PolymorphismSchema internal IDictionary CodeTypeMapping { get { return this._codeTypeMapping; } } internal bool UseDefault { get { return this.PolymorphismType == PolymorphismType.None; } } + internal bool UseTypeEmbedding { get { return this.PolymorphismType == PolymorphismType.RuntimeType; } } + internal Func TypeVerifier { get; private set; } + internal PolymorphismSchemaChildrenType ChildrenType { get; private set; } private readonly ReadOnlyCollection _children; @@ -123,6 +115,25 @@ internal PolymorphismSchema ItemSchema } } + private PolymorphismSchema TryGetItemSchema() + { + switch ( this.ChildrenType ) + { + case PolymorphismSchemaChildrenType.CollectionItems: + { + return this._children.FirstOrDefault(); + } + case PolymorphismSchemaChildrenType.DictionaryKeyValues: + { + return this._children.Skip( 1 ).FirstOrDefault(); + } + default: + { + return null; + } + } + } + /// /// Gets the schema for dictionary keys of the serialization target collection. /// @@ -150,7 +161,20 @@ internal PolymorphismSchema KeySchema } } } -#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY || CORE_CLR + + private PolymorphismSchema TryGetKeySchema() + { + if ( this.ChildrenType == PolymorphismSchemaChildrenType.DictionaryKeyValues ) + { + return this._children.FirstOrDefault(); + } + else + { + return null; + } + } + +#if NET35 || NET40 || SILVERLIGHT || UNITY || CORE_CLR || NETSTANDARD1_1 private sealed class ReadOnlyDictionary : IDictionary { private readonly IDictionary _underlying; @@ -244,6 +268,6 @@ bool ICollection>.Remove( KeyValuePair throw new NotSupportedException(); } } -#endif // NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY +#endif // NET35 || NET40 || SILVERLIGHT || UNITY } } \ No newline at end of file diff --git a/src/MsgPack/Serialization/PolymorphismSchemaChildrenType.cs b/src/MsgPack/Serialization/PolymorphismSchemaChildrenType.cs index 2d1b14516..d74afa34b 100644 --- a/src/MsgPack/Serialization/PolymorphismSchemaChildrenType.cs +++ b/src/MsgPack/Serialization/PolymorphismSchemaChildrenType.cs @@ -40,11 +40,11 @@ internal enum PolymorphismSchemaChildrenType /// DictionaryKeyValues, -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY /// /// Tuple items, so chidren count is equal to tuple's arity. /// TupleItems -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY } } \ No newline at end of file diff --git a/src/MsgPack/Serialization/Reflection/GenericTypeExtensions.cs b/src/MsgPack/Serialization/Reflection/GenericTypeExtensions.cs index f64902500..4c0d638b6 100644 --- a/src/MsgPack/Serialization/Reflection/GenericTypeExtensions.cs +++ b/src/MsgPack/Serialization/Reflection/GenericTypeExtensions.cs @@ -24,11 +24,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; #if NETFX_CORE using System.Reflection; @@ -97,11 +97,11 @@ public static string GetName( this Type source ) String.Concat( source.Name, '[', -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY String.Join( ", ", source.GetGenericArguments().Select( t => t.GetName() ) ), #else String.Join( ", ", source.GetGenericArguments().Select( t => t.GetName() ).ToArray() ), -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY ']' ); } @@ -134,6 +134,11 @@ public static string GetFullName( this Type source ) } } + if ( source.IsByRef ) + { + return source.GetElementType().GetFullName() + "&"; + } + if ( !source.GetIsGenericType() ) { return source.FullName; @@ -145,11 +150,11 @@ public static string GetFullName( this Type source ) ReflectionAbstractions.TypeDelimiter, source.Name, '[', -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY String.Join( ", ", source.GetGenericArguments().Select( t => t.GetFullName() ) ), #else String.Join( ", ", source.GetGenericArguments().Select( t => t.GetFullName() ).ToArray() ), -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY ']' ); } diff --git a/src/MsgPack/Serialization/Reflection/ReflectionExtensions.cs b/src/MsgPack/Serialization/Reflection/ReflectionExtensions.cs index b3cd2c0a7..322688145 100644 --- a/src/MsgPack/Serialization/Reflection/ReflectionExtensions.cs +++ b/src/MsgPack/Serialization/Reflection/ReflectionExtensions.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Reflection; using System.Text; @@ -62,6 +62,7 @@ public static bool IsAssignableTo( this Type source, Type target ) return target.IsAssignableFrom( source ); } +#if DEBUG /// /// Get IL friendly attributes string. /// @@ -239,15 +240,16 @@ public static string ToILString( this MethodImplAttributes source ) AddString( result, source, MethodImplAttributes.InternalCall, "internalcall" ); AddString( result, source, MethodImplAttributes.Synchronized, "synchronized" ); AddString( result, source, MethodImplAttributes.NoInlining, "noinlining" ); +#if !UNITY AddString( result, source, MethodImplAttributes.NoOptimization, "nooptimization" ); -#if !NETFX_35 && !NETFX_40 && !UNITY +#if !NET35 && !NET40 AddString( result, source, MethodImplAttributes.AggressiveInlining, "aggressiveinlining" ); -#endif // !NETFX_35 && !NETFX_40 && !UNITY +#endif // !NET35 && !NET40 +#endif // !UNITY return result.ToString(); } - private static void AddString( StringBuilder buffer, MethodImplAttributes source, MethodImplAttributes flag, string stringified ) { // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags @@ -256,5 +258,6 @@ private static void AddString( StringBuilder buffer, MethodImplAttributes source buffer.Append( ' ' ).Append( stringified ); } } +#endif // DEBUG } } diff --git a/src/MsgPack/Serialization/Reflection/TracingILGenerator.conveniences.cs b/src/MsgPack/Serialization/Reflection/TracingILGenerator.conveniences.cs index 88fe68ae1..87dac5541 100644 --- a/src/MsgPack/Serialization/Reflection/TracingILGenerator.conveniences.cs +++ b/src/MsgPack/Serialization/Reflection/TracingILGenerator.conveniences.cs @@ -19,7 +19,11 @@ #endregion -- License Terms -- using System; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Globalization; using System.Reflection; using System.Reflection.Emit; @@ -171,7 +175,7 @@ public void EmitStringFormat( int temporaryLocalArrayIndex, Type resource, strin { Contract.Assert( resource != null ); Contract.Assert( resourceKey != null ); -#if !NETFX_35 +#if !NET35 Contract.Assert( !String.IsNullOrWhiteSpace( resourceKey ) ); #else Contract.Assert( !String.IsNullOrEmpty( resourceKey ) ); @@ -233,7 +237,7 @@ public void EmitStringFormatInvariant( int temporaryLocalArrayIndex, Type resour { Contract.Assert( resource != null ); Contract.Assert( resourceKey != null ); -#if !NETFX_35 +#if !NET35 Contract.Assert( !String.IsNullOrWhiteSpace( resourceKey ) ); #else Contract.Assert( !String.IsNullOrEmpty( resourceKey ) ); diff --git a/src/MsgPack/Serialization/Reflection/TracingILGenerator.cs b/src/MsgPack/Serialization/Reflection/TracingILGenerator.cs index aa85f8dab..c03df546f 100644 --- a/src/MsgPack/Serialization/Reflection/TracingILGenerator.cs +++ b/src/MsgPack/Serialization/Reflection/TracingILGenerator.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // NLiblet // -// Copyright (C) 2011-2016 FUJIWARA, Yusuke +// Copyright (C) 2011-2017 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,16 +16,19 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR +#if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR +#endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.IO; using System.Reflection; @@ -41,9 +44,7 @@ namespace MsgPack.Serialization.Reflection internal sealed partial class TracingILGenerator : IDisposable { private readonly ILGenerator _underlying; - private readonly TextWriter _realTrace; private readonly TextWriter _trace; - private readonly StringBuilder _traceBuffer; private readonly Dictionary _localDeclarations = new Dictionary(); private readonly Dictionary _labels = new Dictionary(); @@ -199,20 +200,19 @@ public TracingILGenerator( MethodBuilder methodBuilder, TextWriter traceWriter ) { Contract.Assert( methodBuilder != null ); } +#endif // DEBUG -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 /// /// Initializes a new instance of the class. /// /// The dynamic method. /// The trace writer. - public TracingILGenerator( DynamicMethod dynamicMethod, TextWriter traceWriter ) - : this( dynamicMethod != null ? dynamicMethod.GetILGenerator() : null, true, traceWriter, false ) + /// true if the underlying builders are debuggable; othersie false. + public TracingILGenerator( DynamicMethod dynamicMethod, TextWriter traceWriter, bool isDebuggable ) + : this( dynamicMethod != null ? dynamicMethod.GetILGenerator() : null, true, traceWriter, isDebuggable ) { Contract.Assert( dynamicMethod != null ); } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 -#endif // DEBUG // TODO: NLIblet @@ -244,9 +244,7 @@ public TracingILGenerator( ConstructorBuilder constructorBuilder, TextWriter tra private TracingILGenerator( ILGenerator underlying, bool isInDynamicMethod, TextWriter traceWriter, bool isDebuggable ) { this._underlying = underlying; - this._realTrace = traceWriter ?? TextWriter.Null; - this._traceBuffer = traceWriter != null ? new StringBuilder() : null; - this._trace = traceWriter != null ? new StringWriter( this._traceBuffer, CultureInfo.InvariantCulture ) : TextWriter.Null; + this._trace = traceWriter ?? NullTextWriter.Instance; this._isInDynamicMethod = isInDynamicMethod; this._endOfMethod = underlying == null ? default( Label ) : underlying.DefineLabel(); this._isDebuggable = isDebuggable; @@ -276,18 +274,11 @@ public void EmitRet() public void FlushTrace() { - if ( this._traceBuffer != null && this._traceBuffer.Length > 0 ) - { - this.TraceLocals(); - this._trace.Flush(); - this._realTrace.Write( this._traceBuffer ); - this._traceBuffer.Clear(); - } + this._trace.Flush(); } #region -- Locals -- -#if DEBUG /// /// Declare local without pinning and name for debugging. /// @@ -302,6 +293,7 @@ public LocalBuilder DeclareLocal( Type localType ) return this.DeclareLocalCore( localType, null ); } +#if DEBUG /// /// Declare local without name for debugging. /// @@ -360,7 +352,7 @@ private LocalBuilder DeclareLocalCore( Type localType, string name ) var result = this._underlying.DeclareLocal( localType ); this._localDeclarations.Add( result, name ); // TODO: NLiblet -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( !this._isInDynamicMethod && this._isDebuggable ) { try @@ -372,7 +364,7 @@ private LocalBuilder DeclareLocalCore( Type localType, string name ) this._isInDynamicMethod = true; } } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 return result; } @@ -382,7 +374,7 @@ private LocalBuilder DeclareLocalCore( Type localType, string name, bool pinned var result = this._underlying.DeclareLocal( localType, pinned ); this._localDeclarations.Add( result, name ); // TODO: NLiblet -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( !this._isInDynamicMethod && this._isDebuggable ) { try @@ -394,44 +386,11 @@ private LocalBuilder DeclareLocalCore( Type localType, string name, bool pinned this._isInDynamicMethod = true; } } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 return result; } #endif // DEBUG - private void TraceLocals() - { - Contract.Assert( this._realTrace != null ); - // TOOD: without init? - this._realTrace.WriteLine( ".locals init (" ); - - foreach ( var local in this._localDeclarations ) - { - this.WriteIndent( this._realTrace, 1 ); - - this._realTrace.Write( "[" ); - this._realTrace.Write( local.Key.LocalIndex ); - this._realTrace.Write( "] " ); - - WriteType( this._realTrace, local.Key.LocalType ); - - if ( local.Key.IsPinned ) - { - this._realTrace.Write( "(pinned)" ); - } - - if ( local.Value != null ) - { - this._realTrace.Write( " " ); - this._realTrace.Write( local.Value ); - } - - this._realTrace.WriteLine(); - } - - this._realTrace.WriteLine( ")" ); - } - #endregion #region -- Exceptions -- @@ -704,7 +663,7 @@ public void MarkLabel( Label label ) #region -- Calli -- #if DEBUG -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 /// /// Emit 'calli' instruction for indirect unmanaged function call. /// @@ -751,7 +710,7 @@ public void EmitCalli( CallingConventions managedCallingConventions, Type return this._underlying.EmitCalli( OpCodes.Calli, managedCallingConventions, returnType, requiredParameterTypes, optionalParameterTypes ); } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 #endif // DEBUG #endregion #endif // !SILVERLIGHT @@ -850,7 +809,7 @@ public void EmitTailCallVirt( MethodInfo target ) this.EmitRet(); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETSTANDARD2_0 /// /// Emit 'calli' instruction for indirect unmanaged function call as tail call. /// @@ -908,7 +867,7 @@ public void EmitTailCalli( CallingConventions managedCallingConventions, Type re this.EmitCalli( managedCallingConventions, returnType, requiredParameterTypes, optionalParameterTypes ); this.EmitRet(); } -#endif // SILVERLIGHT +#endif // SILVERLIGHT && !NETSTANDARD2_0 #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // DEBUG @@ -1037,6 +996,10 @@ private void TraceType( Type type ) private static void WriteType( TextWriter writer, Type type ) { Contract.Assert( writer != null ); + if ( writer == NullTextWriter.Instance ) + { + return; + } if ( type == null || type == typeof( void ) ) { @@ -1281,6 +1244,10 @@ private void TraceMethod( MethodBase method ) private static void WriteCallingConventions( TextWriter writer, CallingConventions? managedCallingConverntions, CallingConvention? unamangedCallingConvention ) { Contract.Assert( writer != null ); + if ( writer == NullTextWriter.Instance ) + { + return; + } bool needsSpace = false; if ( managedCallingConverntions != null ) @@ -1360,7 +1327,7 @@ private void TraceOperand( double value ) private void TraceOperand( string value ) { // QSTRING - this._trace.Write( String.Format( CultureInfo.InvariantCulture, "\"{0:L}\"", value ) ); + this._trace.Write( "\"{0:L}\"", value ); } private void TraceOperand( Label value ) @@ -1427,9 +1394,7 @@ private void TraceOperandToken( MethodBase target ) #if !NETSTANDARD1_1 && !NETSTANDARD1_3 private void TraceOperandTokenValue( int value ) { - this._trace.Write( "<" ); - this._trace.Write( value.ToString( "x8", CultureInfo.InvariantCulture ) ); - this._trace.Write( ">" ); + this._trace.Write( "<{0:x8}>", value ); } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 diff --git a/src/MsgPack/Serialization/Reflection/TracingILGenerator.emits.cs b/src/MsgPack/Serialization/Reflection/TracingILGenerator.emits.cs index beac332c5..c7f9c205c 100644 --- a/src/MsgPack/Serialization/Reflection/TracingILGenerator.emits.cs +++ b/src/MsgPack/Serialization/Reflection/TracingILGenerator.emits.cs @@ -23,7 +23,11 @@ using System; using System.Diagnostics.CodeAnalysis; +#if NETSTANDARD1_1 +using Contract = MsgPack.MPContract; +#else using System.Diagnostics.Contracts; +#endif // NETSTANDARD1_1 using System.Linq; using System.Reflection.Emit; using System.Runtime.CompilerServices; @@ -1939,6 +1943,7 @@ public void EmitUnbox( System.Type type ) this._underlying.Emit( OpCodes.Unbox, type ); } +#endif // DEBUG /// /// Emit 'throw' instruction with specified arguments. @@ -1953,7 +1958,6 @@ public void EmitThrow() this._underlying.Emit( OpCodes.Throw ); } -#endif // DEBUG /// /// Emit 'ldfld' instruction with specified arguments. diff --git a/src/MsgPack/Serialization/ReflectionExtensions.CollectionTraits.cs b/src/MsgPack/Serialization/ReflectionExtensions.CollectionTraits.cs new file mode 100644 index 000000000..7ab397a1a --- /dev/null +++ b/src/MsgPack/Serialization/ReflectionExtensions.CollectionTraits.cs @@ -0,0 +1,829 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Contributors: +// Samuel Cragg +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections; +using System.Collections.Generic; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Linq; +using System.Reflection; + +using MsgPack.Serialization.Reflection; + +namespace MsgPack.Serialization +{ + partial class ReflectionExtensions + { + internal static CollectionTraits GetCollectionTraits( this Type source, CollectionTraitOptions options, bool allowNonCollectionEnumerableTypes ) + { +#if DEBUG + Contract.Assert( !source.GetContainsGenericParameters(), "!source.GetContainsGenericParameters()" ); +#endif // DEBUG + /* + * SPEC + * If the object has single public method TEnumerator GetEnumerator() ( where TEnumerator implements IEnumerator), + * then the object is considered as the collection of TItem. + * When the object is considered as the collection of TItem, TItem is KeyValuePair, + * and the object implements IDictionary, then the object is considered as dictionary of TKey and TValue. + * Else, if the object has single public method IEnumerator GetEnumerator(), then the object is considered as the collection of Object. + * When it also implements IDictionary, however, it is considered dictionary of Object and Object. + * Otherwise, that means it implements multiple collection interface, is following. + * First, if the object implements IDictionary, then it is considered as MPO dictionary. + * Second, if the object implements IEnumerable, then it is considered as MPO dictionary. + * Third, if the object implement SINGLE IDictionary and multiple IEnumerable, then it is considered as dictionary of TKey and TValue. + * Fourth, the object is considered as UNSERIALIZABLE member. This behavior similer to DataContract serialization behavor + * (see http://msdn.microsoft.com/en-us/library/aa347850.aspx ). + */ + + if ( !source.IsAssignableTo( typeof( IEnumerable ) ) ) + { + return CollectionTraits.NotCollection; + } + + if ( source.IsArray ) + { + return + new CollectionTraits( + CollectionDetailedKind.Array, + source.GetElementType(), + null, // Never used for array. + null, // Never used for array. + null // Never used for array. + ); + } + + // If the type is an interface then a concrete collection has to be + // made for it (if the interface is a collection type), therefore, + // ignore the check for an add method + if ( !source.GetIsInterface() && allowNonCollectionEnumerableTypes ) + { + options = options | CollectionTraitOptions.AllowNonCollectionEnumerableTypes; + } + + MethodInfo getEnumerator = source.GetMethod( "GetEnumerator", ReflectionAbstractions.EmptyTypes ); + if ( getEnumerator != null && getEnumerator.ReturnType.IsAssignableTo( typeof( IEnumerator ) ) ) + { + // If public 'GetEnumerator' is found, it is primary collection traits. + CollectionTraits result; + if ( TryCreateCollectionTraitsForHasGetEnumeratorType( source, options, getEnumerator, out result ) ) + { + return result; + } + } + + GenericCollectionTypes genericTypes = new GenericCollectionTypes(); + Type ienumerable = null; + Type icollection = null; + Type ilist = null; + Type idictionary = null; + + var sourceInterfaces = source.FindInterfaces( FilterCollectionType, null ); + if ( source.GetIsInterface() && FilterCollectionType( source, null ) ) + { + var originalSourceInterfaces = sourceInterfaces.ToArray(); + var concatenatedSourceInterface = new Type[ originalSourceInterfaces.Length + 1 ]; + concatenatedSourceInterface[ 0 ] = source; + for ( int i = 0; i < originalSourceInterfaces.Length; i++ ) + { + concatenatedSourceInterface[ i + 1 ] = originalSourceInterfaces[ i ]; + } + + sourceInterfaces = concatenatedSourceInterface; + } + + foreach ( var type in sourceInterfaces ) + { + CollectionTraits result; + if ( TryCreateGenericCollectionTraits( source, type, options, out result ) ) + { + return result; + } + + if ( !DetermineCollectionInterfaces( + type, + ref genericTypes, + ref idictionary, + ref ilist, + ref icollection, + ref ienumerable + ) + ) + { + return CollectionTraits.Unserializable; + } + } + + if ( genericTypes.IDictionaryT != null ) + { + var genericArguments = genericTypes.IDictionaryT.GetGenericArguments(); + var elementType = typeof( KeyValuePair<,> ).MakeGenericType( genericArguments ); + + return + new CollectionTraits( + CollectionDetailedKind.GenericDictionary, + elementType, + GetGetEnumeratorMethodFromElementType( source, elementType, options ), + GetAddMethod( source, genericArguments[ 0 ], genericArguments[ 1 ], options ), + GetCountGetterMethod( source, elementType, options ) + ); + } + +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + if ( genericTypes.IReadOnlyDictionaryT != null ) + { + var elementType = typeof( KeyValuePair<,> ).MakeGenericType( genericTypes.IReadOnlyDictionaryT.GetGenericArguments() ); + return + new CollectionTraits( + CollectionDetailedKind.GenericReadOnlyDictionary, + elementType, + GetGetEnumeratorMethodFromElementType( source, elementType, options ), + null, // add + GetCountGetterMethod( source, elementType, options ) + ); + } +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + + if ( genericTypes.IEnumerableT != null ) + { + CollectionTraits traits; + if ( TryCreateCollectionTraitsForIEnumerableT( source, genericTypes, options, null, out traits ) ) + { + return traits; + } + } + + if ( idictionary != null ) + { + return + new CollectionTraits( + CollectionDetailedKind.NonGenericDictionary, + typeof( object ), + GetGetEnumeratorMethodFromEnumerableType( source, idictionary, options ), + GetAddMethod( source, typeof( object ), typeof( object ), options ), + GetCountGetterMethod( source, typeof( object ), options ) + ); + } + + if ( ienumerable != null ) + { + var addMethod = GetAddMethod( source, typeof( object ), options | CollectionTraitOptions.WithAddMethod ); + if ( addMethod != null || ( ( options & CollectionTraitOptions.AllowNonCollectionEnumerableTypes ) == 0 ) ) + { + // This should be appendable or unappendable collection + return + new CollectionTraits( + ( ilist != null ) + ? CollectionDetailedKind.NonGenericList + : ( icollection != null ) + ? CollectionDetailedKind.NonGenericCollection + : CollectionDetailedKind.NonGenericEnumerable, + typeof( object ), + GetGetEnumeratorMethodFromEnumerableType( source, ienumerable, options ), + addMethod, + GetCountGetterMethod( source, typeof( object ), options ) + ); + } + } + + return CollectionTraits.NotCollection; + } + + private static bool TryCreateCollectionTraitsForIEnumerableT( + Type source, + GenericCollectionTypes genericTypes, + CollectionTraitOptions options, + MethodInfo getMethod, + out CollectionTraits result + ) + { + var elementType = genericTypes.IEnumerableT.GetGenericArguments()[ 0 ]; + var addMethod = GetAddMethod( source, elementType, options ); + if ( addMethod == null && ( ( options & CollectionTraitOptions.AllowNonCollectionEnumerableTypes ) != 0 ) ) + { + // This should be non collection object isntead of "unappendable" collection. + result = default( CollectionTraits ); + return false; + } + + CollectionDetailedKind kind = CollectionDetailedKind.GenericEnumerable; + if ( genericTypes.IListT != null ) + { + kind = CollectionDetailedKind.GenericList; + } +#if !NET35 && !UNITY + else if ( genericTypes.ISetT != null ) + { + kind = CollectionDetailedKind.GenericSet; + } +#endif // !NET35 && !UNITY + else if ( genericTypes.ICollectionT != null ) + { + kind = CollectionDetailedKind.GenericCollection; + } +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + else if ( genericTypes.IReadOnlyListT != null ) + { + kind = CollectionDetailedKind.GenericReadOnlyList; + } + else if ( genericTypes.IReadOnlyCollectionT != null ) + { + kind = CollectionDetailedKind.GenericReadOnlyCollection; + } +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + + result = + new CollectionTraits( + kind, + elementType, + getMethod ?? GetGetEnumeratorMethodFromElementType( source, elementType, options ), + addMethod, + GetCountGetterMethod( source, elementType, options ) + ); + return true; + } + + private static bool TryCreateCollectionTraitsForHasGetEnumeratorType( + Type source, + CollectionTraitOptions options, + MethodInfo getEnumerator, + out CollectionTraits result + ) + { + if ( source.Implements( typeof( IDictionary<,> ) ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + || source.Implements( typeof( IReadOnlyDictionary<,> ) ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + ) + { + var ienumetaorT = + getEnumerator.ReturnType.GetInterfaces() + .FirstOrDefault( @interface => + @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ) + ); + if ( ienumetaorT != null ) + { + var elementType = ienumetaorT.GetGenericArguments()[ 0 ]; + var elementTypeGenericArguments = elementType.GetGenericArguments(); + + result = + new CollectionTraits( +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + source.Implements( typeof( IDictionary<,> ) ) + ? CollectionDetailedKind.GenericDictionary + : CollectionDetailedKind.GenericReadOnlyDictionary, +#else + CollectionDetailedKind.GenericDictionary, +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + elementType, + getEnumerator, + GetAddMethod( source, elementTypeGenericArguments[ 0 ], elementTypeGenericArguments [ 1 ], options ), + GetCountGetterMethod( source, elementType, options ) + ); + + return true; + } + } + + if ( source.IsAssignableTo( typeof( IDictionary ) ) ) + { + result = + new CollectionTraits( + CollectionDetailedKind.NonGenericDictionary, + typeof( DictionaryEntry ), + getEnumerator, + GetAddMethod( source, typeof( object ), typeof( object ), options ), + GetCountGetterMethod( source, typeof( object ), options ) + ); + + return true; + } + + // Block to limit variable scope + { + var ienumetaorT = + IsIEnumeratorT( getEnumerator.ReturnType ) + ? getEnumerator.ReturnType + : getEnumerator.ReturnType.GetInterfaces().FirstOrDefault( IsIEnumeratorT ); + + if ( ienumetaorT != null ) + { + // Get the open generic types once + Type[] genericInterfaces = + source.GetInterfaces() + .Where( i => i.GetIsGenericType() ) + .Select( i => i.GetGenericTypeDefinition() ) + .ToArray(); + + var genericTypes = new GenericCollectionTypes(); + genericTypes.IEnumerableT = ienumetaorT; + genericTypes.ICollectionT = genericInterfaces.FirstOrDefault( i => i == typeof(ICollection<>) ); + genericTypes.IListT = genericInterfaces.FirstOrDefault( i => i == typeof(IList<>) ); + +#if !NET35 && !UNITY + genericTypes.ISetT = genericInterfaces.FirstOrDefault( i => i == typeof(ISet<>) ); +#endif // !NET35 && !UNITY +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + genericTypes.IReadOnlyCollectionT = genericInterfaces.FirstOrDefault( i => i == typeof(IReadOnlyCollection<>) ); + genericTypes.IReadOnlyListT = genericInterfaces.FirstOrDefault( i => i == typeof(IReadOnlyList<>) ); +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + + return TryCreateCollectionTraitsForIEnumerableT( source, genericTypes, options, getEnumerator, out result ); + } + } + + result = default( CollectionTraits ); + return false; + } + + + private static bool TryCreateGenericCollectionTraits( Type source, Type type, CollectionTraitOptions options, out CollectionTraits result ) + { + if ( type == typeof( IDictionary ) +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + || type == typeof( IReadOnlyDictionary ) +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + ) + { + result = + new CollectionTraits( +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + ( source == typeof( IDictionary ) || source.Implements( typeof( IDictionary ) ) ) + ? CollectionDetailedKind.GenericDictionary + : CollectionDetailedKind.GenericReadOnlyDictionary, +#else + CollectionDetailedKind.GenericDictionary, +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + typeof( KeyValuePair ), + GetGetEnumeratorMethodFromEnumerableType( source, typeof( IEnumerable> ), options ), + GetAddMethod( source, typeof( MessagePackObject ), typeof( MessagePackObject ), options ), + GetCountGetterMethod( source, typeof( KeyValuePair ), options ) + ); + + return true; + } + + if ( type == typeof( IEnumerable ) ) + { + var addMethod = GetAddMethod( source, typeof( MessagePackObject ), options | CollectionTraitOptions.WithAddMethod ); + if ( addMethod != null ) + { + { + result = + new CollectionTraits( + ( source == typeof( IList ) || source.Implements( typeof( IList ) ) ) + ? CollectionDetailedKind.GenericList +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + : ( source == typeof( IReadOnlyList ) || source.Implements( typeof( IReadOnlyList ) ) ) + ? CollectionDetailedKind.GenericReadOnlyList +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY + : ( source == typeof( ISet ) || source.Implements( typeof( ISet ) ) ) + ? CollectionDetailedKind.GenericSet +#endif // !NET35 && !UNITY + : ( source == typeof( ICollection ) || + source.Implements( typeof( ICollection ) ) ) + ? CollectionDetailedKind.GenericCollection +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + : ( source == typeof( IReadOnlyCollection ) || source.Implements( typeof( IReadOnlyCollection ) ) ) + ? CollectionDetailedKind.GenericReadOnlyCollection +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + : CollectionDetailedKind.GenericEnumerable, + typeof( MessagePackObject ), + GetGetEnumeratorMethodFromEnumerableType( source, typeof( IEnumerable ), options ), + addMethod, + GetCountGetterMethod( source, typeof( MessagePackObject ), options ) + ); + + return true; + } + } + } + + result = default( CollectionTraits ); + return false; + } + + private static bool DetermineCollectionInterfaces( + Type type, + ref GenericCollectionTypes genericTypes, + ref Type idictionary, + ref Type ilist, + ref Type icollection, + ref Type ienumerable + ) + { + if ( type.GetIsGenericType() ) + { + var genericTypeDefinition = type.GetGenericTypeDefinition(); + if ( genericTypeDefinition == typeof( IDictionary<,> ) ) + { + if ( genericTypes.IDictionaryT != null ) + { + return false; + } + + genericTypes.IDictionaryT = type; + } +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + else if ( genericTypeDefinition == typeof( IReadOnlyDictionary<,> ) ) + { + if ( genericTypes.IReadOnlyDictionaryT != null ) + { + return false; + } + + genericTypes.IReadOnlyDictionaryT = type; + } +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + else if ( genericTypeDefinition == typeof( IList<> ) ) + { + if ( genericTypes.IListT != null ) + { + return false; + } + + genericTypes.IListT = type; + } +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + else if ( genericTypeDefinition == typeof( IReadOnlyList<> ) ) + { + if ( genericTypes.IReadOnlyListT != null ) + { + return false; + } + + genericTypes.IReadOnlyListT = type; + } +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#if !NET35 && !UNITY + else if ( genericTypeDefinition == typeof( ISet<> ) ) + { + if ( genericTypes.ISetT != null ) + { + return false; + } + + genericTypes.ISetT = type; + } +#endif // !NET35 && !UNITY + else if ( genericTypeDefinition == typeof( ICollection<> ) ) + { + if ( genericTypes.ICollectionT != null ) + { + return false; + } + + genericTypes.ICollectionT = type; + } +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + else if ( genericTypeDefinition == typeof( IReadOnlyCollection<> ) ) + { + if ( genericTypes.IReadOnlyCollectionT != null ) + { + return false; + } + + genericTypes.IReadOnlyCollectionT = type; + } +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + else if ( genericTypeDefinition == typeof( IEnumerable<> ) ) + { + if ( genericTypes.IEnumerableT != null ) + { + return false; + } + + genericTypes.IEnumerableT = type; + } + } + else + { + if ( type == typeof( IDictionary ) ) + { + idictionary = type; + } + else if ( type == typeof( IList ) ) + { + ilist = type; + } + else if ( type == typeof( ICollection ) ) + { + icollection = type; + } + else if ( type == typeof( IEnumerable ) ) + { + ienumerable = type; + } + } + + return true; + } + + private static MethodInfo GetGetEnumeratorMethodFromElementType( Type targetType, Type elementType, CollectionTraitOptions options ) + { + if ( ( options | CollectionTraitOptions.WithGetEnumeratorMethod ) == 0 ) + { + return null; + } + + return FindInterfaceMethod( targetType, typeof( IEnumerable<> ).MakeGenericType( elementType ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ); + } + + private static MethodInfo GetGetEnumeratorMethodFromEnumerableType( Type targetType, Type enumerableType, CollectionTraitOptions options ) + { + if ( ( options | CollectionTraitOptions.WithGetEnumeratorMethod ) == 0 ) + { + return null; + } + + return FindInterfaceMethod( targetType, enumerableType, "GetEnumerator", ReflectionAbstractions.EmptyTypes ); + } + + private static MethodInfo FindInterfaceMethod( Type targetType, Type interfaceType, string name, Type[] parameterTypes ) + { + if ( targetType.GetIsInterface() ) + { + return targetType.FindInterfaces( ( type, _ ) => type == interfaceType, null ).Single().GetMethod( name, parameterTypes ); + } + + var map = targetType.GetInterfaceMap( interfaceType ); + +#if !SILVERLIGHT || WINDOWS_PHONE + int index = Array.FindIndex( map.InterfaceMethods, method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) ); +#else + int index = map.InterfaceMethods.FindIndex( method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) ); +#endif + + if ( index < 0 ) + { +#if DEBUG +#if !NET35 && !UNITY + Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join( ", ", parameterTypes ) + ") is not found in " + targetType ); +#else + Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join( ", ", parameterTypes.Select( t => t.ToString() ).ToArray() ) + ") is not found in " + targetType ); +#endif // !NET35 +#endif // DEBUG + // ReSharper disable once HeuristicUnreachableCode + return null; + } + + return map.TargetMethods[ index ]; + } + + private static MethodInfo GetAddMethod( Type targetType, Type argumentType, CollectionTraitOptions options ) + { + if ( ( options | CollectionTraitOptions.WithAddMethod ) == 0 ) + { + return null; + } + + var argumentTypes = new[] { argumentType }; + var typedAdd = targetType.GetMethod( "Add", argumentTypes ); + if ( typedAdd != null ) + { + return typedAdd; + } + + var icollectionT = typeof( ICollection<> ).MakeGenericType( argumentType ); + if ( targetType.IsAssignableTo( icollectionT ) ) + { + return icollectionT.GetMethod( "Add", argumentTypes ); + } + + // It ensures .NET Framework and .NET Core compatibility and provides "natural" feel. + var objectAdd = targetType.GetMethod( "Add", ObjectAddParameterTypes ); + if ( objectAdd != null ) + { + return objectAdd; + } + + if ( targetType.IsAssignableTo( typeof( IList ) ) ) + { + return typeof( IList ).GetMethod( "Add", ObjectAddParameterTypes ); + } + + return null; + } + + // ReSharper disable UnusedParameter.Local + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "targetType", Justification = "For Unity compatibility" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "elementType", Justification = "For Unity compatibility" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "options", Justification = "For Unity compatibility" )] + private static MethodInfo GetCountGetterMethod( Type targetType, Type elementType, CollectionTraitOptions options ) + // ReSharper restore UnusedParameter.Local + { +#if !UNITY + // get_Count is not used other than Unity. + return null; +#else + if ( ( options | CollectionTraitOptions.WithCountPropertyGetter ) == 0 ) + { + return null; + } + + var result = targetType.GetProperty( "Count" ); + if ( result != null && result.GetHasPublicGetter() ) + { + return result.GetGetMethod(); + } + + var icollectionT = typeof( ICollection<> ).MakeGenericType( elementType ); + if ( targetType.IsAssignableTo( icollectionT ) ) + { + return icollectionT.GetProperty( "Count" ).GetGetMethod(); + } + +#if !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + var ireadOnlyCollectionT = typeof( IReadOnlyCollection<> ).MakeGenericType( elementType ); + if ( targetType.IsAssignableTo( ireadOnlyCollectionT ) ) + { + return ireadOnlyCollectionT.GetProperty( "Count" ).GetGetMethod(); + } +#endif // !NET35 && !UNITY && !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + + if ( targetType.IsAssignableTo( typeof( ICollection ) ) ) + { + return typeof( ICollection ).GetProperty( "Count" ).GetGetMethod(); + } + + return null; +#endif // !UNITY + } + + private static MethodInfo GetAddMethod( Type targetType, Type keyType, Type valueType, CollectionTraitOptions options ) + { + if ( ( options | CollectionTraitOptions.WithAddMethod ) == 0 ) + { + return null; + } + + var argumentTypes = new[] { keyType, valueType }; + var result = targetType.GetMethod( "Add", argumentTypes ); + if ( result != null ) + { + return result; + } + + return typeof( IDictionary<,> ).MakeGenericType( argumentTypes ).GetMethod( "Add", argumentTypes ); + } + + private static bool FilterCollectionType( Type type, object filterCriteria ) + { +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if DEBUG + Contract.Assert( type.GetIsInterface(), "type.IsInterface" ); +#endif // DEBUG + return type.GetAssembly().Equals( typeof( Array ).GetAssembly() ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" ); +#else + var typeInfo = type.GetTypeInfo(); + Contract.Assert( typeInfo.IsInterface ); + return typeInfo.Assembly.Equals( typeof( Array ).GetTypeInfo().Assembly ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" ); +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + } + + private static bool IsIEnumeratorT( Type @interface ) + { + return @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ); + } +#if WINDOWS_PHONE + public static IEnumerable FindInterfaces( this Type source, Func filter, object criterion ) + { + foreach ( var @interface in source.GetInterfaces() ) + { + if ( filter( @interface, criterion ) ) + { + yield return @interface; + } + } + } +#endif + + public static bool GetHasPublicGetter( this MemberInfo source ) + { + PropertyInfo asProperty; + FieldInfo asField; + if ( ( asProperty = source as PropertyInfo ) != null ) + { +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + return asProperty.GetGetMethod() != null; +#else + return ( asProperty.GetMethod != null && asProperty.GetMethod.IsPublic ); +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + } + else if ( ( asField = source as FieldInfo ) != null ) + { + return asField.IsPublic; + } + else + { + throw new NotSupportedException( source.GetType() + " is not supported." ); + } + } + + public static bool GetHasPublicSetter( this MemberInfo source ) + { + PropertyInfo asProperty; + FieldInfo asField; + if ( ( asProperty = source as PropertyInfo ) != null ) + { +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + return asProperty.GetSetMethod() != null; +#else + return ( asProperty.SetMethod != null && asProperty.SetMethod.IsPublic ); +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + } + else if ( ( asField = source as FieldInfo ) != null ) + { + return asField.IsPublic && !asField.IsInitOnly && !asField.IsLiteral; + } + else + { + throw new NotSupportedException( source.GetType() + " is not supported." ); + } + } + + public static bool GetIsPublic( this MemberInfo source ) + { + PropertyInfo asProperty; + FieldInfo asField; + MethodBase asMethod; +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + Type asType; +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + if ( ( asProperty = source as PropertyInfo ) != null ) + { +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + return asProperty.GetAccessors( true ).Where( a => a.ReturnType != typeof( void ) ).All( a => a.IsPublic ); +#else + return + ( asProperty.GetMethod == null || asProperty.GetMethod.IsPublic ); +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + } + else if ( ( asField = source as FieldInfo ) != null ) + { + return asField.IsPublic; + } + else if ( ( asMethod = source as MethodBase ) != null ) + { + return asMethod.IsPublic; + } +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + else if ( ( asType = source as Type ) != null ) + { + return asType.IsPublic; + } +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + else + { + throw new NotSupportedException( source.GetType() + " is not supported." ); + } + } + + private struct GenericCollectionTypes + { + // ReSharper disable InconsistentNaming + internal Type IEnumerableT; + internal Type ICollectionT; + internal Type IListT; + internal Type IDictionaryT; + +#if !NET35 && !UNITY + internal Type ISetT; +#if !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) + internal Type IReadOnlyCollectionT; + internal Type IReadOnlyListT; + internal Type IReadOnlyDictionaryT; +#endif // !NET40 && !( SILVERLIGHT && !WINDOWS_PHONE ) +#endif // !NET35 && !UNITY + // ReSharper restore InconsistentNaming + } + } +} diff --git a/src/MsgPack/Serialization/ReflectionExtensions.ConstructorDelegate.cs b/src/MsgPack/Serialization/ReflectionExtensions.ConstructorDelegate.cs new file mode 100644 index 000000000..edb877716 --- /dev/null +++ b/src/MsgPack/Serialization/ReflectionExtensions.ConstructorDelegate.cs @@ -0,0 +1,67 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Reflection; +using System.Reflection.Emit; + +using MsgPack.Serialization.Reflection; + +namespace MsgPack.Serialization +{ + partial class ReflectionExtensions + { + public static TDelegate CreateConstructorDelegate( this ConstructorInfo constructor ) + { + return ( TDelegate )CreateDelegate( typeof( TDelegate ), constructor.DeclaringType, constructor, constructor.GetParameterTypes() ); + } + + private static object CreateDelegate( Type delegateType, Type targetType, ConstructorInfo constructor, Type[] parameterTypes ) + { + var dynamicMethod = +#if !SILVERLIGHT + new DynamicMethod( "Create" + targetType.Name, targetType, parameterTypes, restrictedSkipVisibility: true ); +#else + new DynamicMethod( "Create" + targetType.Name, targetType, parameterTypes ); +#endif // !SILVERLIGHT + var il = new TracingILGenerator( dynamicMethod, NullTextWriter.Instance, isDebuggable: false ); + if ( constructor == null ) + { + // Value type's init. + il.DeclareLocal( targetType ); + il.EmitAnyLdloca( 0 ); + il.EmitInitobj( targetType ); + il.EmitAnyLdloc( 0 ); + } + else + { + for ( var i = 0; i < parameterTypes.Length; i++ ) + { + il.EmitAnyLdarg( i ); + } + + il.EmitNewobj( constructor ); + } + + il.EmitRet(); + return dynamicMethod.CreateDelegate( delegateType ); + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/ReflectionExtensions.InvokePreservingExtension.cs b/src/MsgPack/Serialization/ReflectionExtensions.InvokePreservingExtension.cs new file mode 100644 index 000000000..f39bfdc27 --- /dev/null +++ b/src/MsgPack/Serialization/ReflectionExtensions.InvokePreservingExtension.cs @@ -0,0 +1,132 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Diagnostics; +using System.Reflection; + +namespace MsgPack.Serialization +{ + partial class ReflectionExtensions + { + public static object InvokePreservingExceptionType( this ConstructorInfo source, params object[] parameters ) + { + try + { + return source.Invoke( parameters ); + } + catch ( TargetInvocationException ex ) + { + var rethrowing = HoistUpInnerException( ex ); + if ( rethrowing == null ) + { + // ctor.Invoke threw exception, so rethrow original TIE. + throw; + } + else + { + throw rethrowing; + } + } + } + + public static object InvokePreservingExceptionType( this MethodInfo source, object instance, params object[] parameters ) + { + try + { + return source.Invoke( instance, parameters ); + } + catch ( TargetInvocationException ex ) + { + var rethrowing = HoistUpInnerException( ex ); + if ( rethrowing == null ) + { + // ctor.Invoke threw exception, so rethrow original TIE. + throw; + } + else + { + throw rethrowing; + } + } + } + + public static T CreateInstancePreservingExceptionType( Type instanceType, params object[] constructorParameters ) + { + return ( T ) CreateInstancePreservingExceptionType( instanceType, constructorParameters ); + } + + public static object CreateInstancePreservingExceptionType( Type type, params object[] constructorParameters ) + { + try + { + return Activator.CreateInstance( type, constructorParameters ); + } + catch ( TargetInvocationException ex ) + { + var rethrowing = HoistUpInnerException( ex ); + if ( rethrowing == null ) + { + // ctor.Invoke threw exception, so rethrow original TIE. + throw; + } + else + { + throw rethrowing; + } + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This method should swallow exception in restoring inner exception of TargetInvocationException." )] + private static Exception HoistUpInnerException( TargetInvocationException targetInvocationException ) + { + if ( targetInvocationException.InnerException == null ) + { + return null; + } + + var ctor = targetInvocationException.InnerException.GetType().GetConstructor( ExceptionConstructorWithInnerParameterTypes ); + if ( ctor == null ) + { + return null; + } + + try + { + return ctor.Invoke( new object[] { targetInvocationException.InnerException.Message, targetInvocationException } ) as Exception; + } +#if !UNITY || MSGPACK_UNITY_FULL + catch ( Exception ex ) +#else + catch ( Exception ) +#endif // !UNITY || MSGPACK_UNITY_FULL + { +#if !UNITY || MSGPACK_UNITY_FULL + Debug.WriteLine( "HoistUpInnerException:" + ex ); +#endif // !UNITY || MSGPACK_UNITY_FULL + return null; + } + } + } +} diff --git a/src/MsgPack/Serialization/ReflectionExtensions.cs b/src/MsgPack/Serialization/ReflectionExtensions.cs index 08fa92093..e195da43b 100644 --- a/src/MsgPack/Serialization/ReflectionExtensions.cs +++ b/src/MsgPack/Serialization/ReflectionExtensions.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -23,124 +26,36 @@ #endif using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; -using System.Linq; using System.Reflection; -using MsgPack.Serialization.Reflection; - namespace MsgPack.Serialization { - internal static class ReflectionExtensions +#if UNITY && DEBUG + public +#else + internal +#endif + static partial class ReflectionExtensions { private static readonly Type[] ExceptionConstructorWithInnerParameterTypes = { typeof( string ), typeof( Exception ) }; private static readonly Type[] ObjectAddParameterTypes = { typeof( object ) }; - public static object InvokePreservingExceptionType( this ConstructorInfo source, params object[] parameters ) - { - try - { - return source.Invoke( parameters ); - } - catch ( TargetInvocationException ex ) - { - var rethrowing = HoistUpInnerException( ex ); - if ( rethrowing == null ) - { - // ctor.Invoke threw exception, so rethrow original TIE. - throw; - } - else - { - throw rethrowing; - } - } - } - - public static object InvokePreservingExceptionType( this MethodInfo source, object instance, params object[] parameters ) + public static Type[] GetParameterTypes( this MethodBase source ) { - try - { - return source.Invoke( instance, parameters ); - } - catch ( TargetInvocationException ex ) - { - var rethrowing = HoistUpInnerException( ex ); - if ( rethrowing == null ) - { - // ctor.Invoke threw exception, so rethrow original TIE. - throw; - } - else - { - throw rethrowing; - } - } - } - - public static T CreateInstancePreservingExceptionType( Type instanceType, params object[] constructorParameters ) - { - return ( T )CreateInstancePreservingExceptionType( instanceType, constructorParameters ); - } - - public static object CreateInstancePreservingExceptionType( Type type, params object[] constructorParameters ) - { - try - { - return Activator.CreateInstance( type, constructorParameters ); - } - catch ( TargetInvocationException ex ) - { - var rethrowing = HoistUpInnerException( ex ); - if ( rethrowing == null ) - { - // ctor.Invoke threw exception, so rethrow original TIE. - throw; - } - else - { - throw rethrowing; - } - } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This method should swallow exception in restoring inner exception of TargetInvocationException." )] - private static Exception HoistUpInnerException( TargetInvocationException targetInvocationException ) - { - if ( targetInvocationException.InnerException == null ) - { - return null; - } - - var ctor = targetInvocationException.InnerException.GetType().GetConstructor( ExceptionConstructorWithInnerParameterTypes ); - if ( ctor == null ) + var parameters = source.GetParameters(); + Type[] parameterTypes = new Type[ parameters.Length ]; + for ( var i = 0; i < parameters.Length; i++ ) { - return null; + parameterTypes[ i ] = parameters[ i ].ParameterType; } - try - { - return ctor.Invoke( new object[] { targetInvocationException.InnerException.Message, targetInvocationException } ) as Exception; - } -#if !UNITY || MSGPACK_UNITY_FULL - catch ( Exception ex ) -#else - catch ( Exception ) -#endif // !UNITY || MSGPACK_UNITY_FULL - { -#if !UNITY || MSGPACK_UNITY_FULL - Debug.WriteLine( "HoistUpInnerException:" + ex ); -#endif // !UNITY || MSGPACK_UNITY_FULL - return null; - } + return parameterTypes; } public static Type GetMemberValueType( this MemberInfo source ) @@ -150,787 +65,35 @@ public static Type GetMemberValueType( this MemberInfo source ) throw new ArgumentNullException( "source" ); } - var asProperty = source as PropertyInfo; - var asField = source as FieldInfo; - - if ( asProperty == null && asField == null ) - { - throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}'({1}) is not field nor property.", source, source.GetType() ) ); - } - - return asProperty != null ? asProperty.PropertyType : asField.FieldType; - } - - public static CollectionTraits GetCollectionTraits( this Type source, CollectionTraitOptions options ) - { -#if DEBUG - Contract.Assert( !source.GetContainsGenericParameters(), "!source.GetContainsGenericParameters()" ); -#endif // DEBUG - /* - * SPEC - * If the object has single public method TEnumerator GetEnumerator() ( where TEnumerator implements IEnumerator), - * then the object is considered as the collection of TItem. - * When the object is considered as the collection of TItem, TItem is KeyValuePair, - * and the object implements IDictionary, then the object is considered as dictionary of TKey and TValue. - * Else, if the object has single public method IEnumerator GetEnumerator(), then the object is considered as the collection of Object. - * When it also implements IDictionary, however, it is considered dictionary of Object and Object. - * Otherwise, that means it implements multiple collection interface, is following. - * First, if the object implements IDictionary, then it is considered as MPO dictionary. - * Second, if the object implements IEnumerable, then it is considered as MPO dictionary. - * Third, if the object implement SINGLE IDictionary and multiple IEnumerable, then it is considered as dictionary of TKey and TValue. - * Fourth, the object is considered as UNSERIALIZABLE member. This behavior similer to DataContract serialization behavor - * (see http://msdn.microsoft.com/en-us/library/aa347850.aspx ). - */ - - if ( !source.IsAssignableTo( typeof( IEnumerable ) ) ) - { - return CollectionTraits.NotCollection; - } - - if ( source.IsArray ) - { - return - new CollectionTraits( - CollectionDetailedKind.Array, - source.GetElementType(), - null, // Never used for array. - null, // Never used for array. - null // Never used for array. - ); - } - - MethodInfo getEnumerator = source.GetMethod( "GetEnumerator", ReflectionAbstractions.EmptyTypes ); - if ( getEnumerator != null && getEnumerator.ReturnType.IsAssignableTo( typeof( IEnumerator ) ) ) - { - // If public 'GetEnumerator' is found, it is primary collection traits. - CollectionTraits result; - if ( TryCreateCollectionTraitsForHasGetEnumeratorType( source, options, getEnumerator, out result ) ) - { - return result; - } - } - - Type ienumerableT = null; - Type icollectionT = null; -#if !NETFX_35 && !UNITY - Type isetT = null; -#endif // !NETFX_35 && !UNITY - Type ilistT = null; - Type idictionaryT = null; -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - Type ireadOnlyCollectionT = null; - Type ireadOnlyListT = null; - Type ireadOnlyDictionaryT = null; -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - Type ienumerable = null; - Type icollection = null; - Type ilist = null; - Type idictionary = null; - - var sourceInterfaces = source.FindInterfaces( FilterCollectionType, null ); - if ( source.GetIsInterface() && FilterCollectionType( source, null ) ) - { - var originalSourceInterfaces = sourceInterfaces.ToArray(); - var concatenatedSourceInterface = new Type[ originalSourceInterfaces.Length + 1 ]; - concatenatedSourceInterface[ 0 ] = source; - for ( int i = 0; i < originalSourceInterfaces.Length; i++ ) - { - concatenatedSourceInterface[ i + 1 ] = originalSourceInterfaces[ i ]; - } - - sourceInterfaces = concatenatedSourceInterface; - } - - foreach ( var type in sourceInterfaces ) - { - CollectionTraits result; - if ( TryCreateGenericCollectionTraits( source, type, options, out result ) ) - { - return result; - } - - if ( !DetermineCollectionInterfaces( - type, - ref idictionaryT, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref ireadOnlyDictionaryT, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref ilistT, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref ireadOnlyListT, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY - ref isetT, -#endif // !NETFX_35 && !UNITY - ref icollectionT, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref ireadOnlyCollectionT, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref ienumerableT, - ref idictionary, - ref ilist, - ref icollection, - ref ienumerable - ) - ) - { - return CollectionTraits.Unserializable; - } - } - - if ( idictionaryT != null ) - { - var elementType = typeof( KeyValuePair<,> ).MakeGenericType( idictionaryT.GetGenericArguments() ); - var genericArguments = idictionaryT.GetGenericArguments(); - - return - new CollectionTraits( - CollectionDetailedKind.GenericDictionary, - elementType, - GetGetEnumeratorMethodFromElementType( source, elementType, options ), - GetAddMethod( source, genericArguments[ 0 ], genericArguments[ 1 ], options ), - GetCountGetterMethod( source, elementType, options ) - ); - } - -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - if ( ireadOnlyDictionaryT != null ) - { - var elementType = typeof( KeyValuePair<,> ).MakeGenericType( ireadOnlyDictionaryT.GetGenericArguments() ); - return - new CollectionTraits( - CollectionDetailedKind.GenericReadOnlyDictionary, - elementType, - GetGetEnumeratorMethodFromElementType( source, elementType, options ), - null, // add - GetCountGetterMethod( source, elementType, options ) - ); - } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - - if ( ienumerableT != null ) - { - var elementType = ienumerableT.GetGenericArguments()[ 0 ]; - return - new CollectionTraits( - ( ilistT != null ) - ? CollectionDetailedKind.GenericList -#if !NETFX_35 && !UNITY - : ( isetT != null ) - ? CollectionDetailedKind.GenericSet -#endif // !NETFX_35 && !UNITY - : ( icollectionT != null ) - ? CollectionDetailedKind.GenericCollection -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : ( ireadOnlyListT != null ) - ? CollectionDetailedKind.GenericReadOnlyList -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : ( ireadOnlyCollectionT != null ) - ? CollectionDetailedKind.GenericReadOnlyCollection -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : CollectionDetailedKind.GenericEnumerable, - elementType, - GetGetEnumeratorMethodFromEnumerableType( source, ienumerableT, options ), - GetAddMethod( source, elementType, options ), - GetCountGetterMethod( source, elementType, options ) - ); - - } - - if ( idictionary != null ) - { - return - new CollectionTraits( - CollectionDetailedKind.NonGenericDictionary, - typeof( object ), - GetGetEnumeratorMethodFromEnumerableType( source, idictionary, options ), - GetAddMethod( source, typeof( object ), typeof( object ), options ), - GetCountGetterMethod( source, typeof( object ), options ) - ); - } - - if ( ienumerable != null ) - { - var addMethod = GetAddMethod( source, typeof( object ), options | CollectionTraitOptions.WithAddMethod ); - if ( addMethod != null ) - { - return - new CollectionTraits( - ( ilist != null ) - ? CollectionDetailedKind.NonGenericList - : ( icollection != null ) - ? CollectionDetailedKind.NonGenericCollection - : CollectionDetailedKind.NonGenericEnumerable, - typeof( object ), - GetGetEnumeratorMethodFromEnumerableType( source, ienumerable, options ), - addMethod, - GetCountGetterMethod( source, typeof( object ), options ) - ); - } - } - - return CollectionTraits.NotCollection; - } - - private static bool TryCreateCollectionTraitsForHasGetEnumeratorType( - Type source, - CollectionTraitOptions options, - MethodInfo getEnumerator, - out CollectionTraits result - ) - { - if ( source.Implements( typeof( IDictionary<,> ) ) -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - || source.Implements( typeof( IReadOnlyDictionary<,> ) ) -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ) - { - var ienumetaorT = - getEnumerator.ReturnType.GetInterfaces() - .FirstOrDefault( @interface => - @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ) - ); - if ( ienumetaorT != null ) - { - var elementType = ienumetaorT.GetGenericArguments()[ 0 ]; - var elementTypeGenericArguments = elementType.GetGenericArguments(); - - result = - new CollectionTraits( -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - source.Implements( typeof( IDictionary<,> ) ) - ? CollectionDetailedKind.GenericDictionary - : CollectionDetailedKind.GenericReadOnlyDictionary, -#else - CollectionDetailedKind.GenericDictionary, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - elementType, - getEnumerator, - GetAddMethod( source, elementTypeGenericArguments[ 0 ], elementTypeGenericArguments [ 1 ], options ), - GetCountGetterMethod( source, elementType, options ) - ); - - return true; - } - } - - if ( source.IsAssignableTo( typeof( IDictionary ) ) ) - { - result = - new CollectionTraits( - CollectionDetailedKind.NonGenericDictionary, - typeof( DictionaryEntry ), - getEnumerator, - GetAddMethod( source, typeof( object ), typeof( object ), options ), - GetCountGetterMethod( source, typeof( object ), options ) - ); - - return true; - } - - // Block to limit variable scope - { - var ienumetaorT = - IsIEnumeratorT( getEnumerator.ReturnType ) - ? getEnumerator.ReturnType - : getEnumerator.ReturnType.GetInterfaces().FirstOrDefault( IsIEnumeratorT ); - - if ( ienumetaorT != null ) - { - var elementType = ienumetaorT.GetGenericArguments()[ 0 ]; - { - result = - new CollectionTraits( - source.Implements( typeof( IList<> ) ) - ? CollectionDetailedKind.GenericList -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : source.Implements( typeof( IReadOnlyList<> ) ) - ? CollectionDetailedKind.GenericReadOnlyList -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY - : source.Implements( typeof( ISet<> ) ) - ? CollectionDetailedKind.GenericSet -#endif // !NETFX_35 && !UNITY - : source.Implements( typeof( ICollection<> ) ) - ? CollectionDetailedKind.GenericCollection -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : source.Implements( typeof( IReadOnlyCollection<> ) ) - ? CollectionDetailedKind.GenericReadOnlyCollection -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : CollectionDetailedKind.GenericEnumerable, - elementType, - getEnumerator, - GetAddMethod( source, elementType, options ), - GetCountGetterMethod( source, elementType, options ) - ); - - return true; - } - } - } - - result = default( CollectionTraits ); - return false; - } - - - private static bool TryCreateGenericCollectionTraits( Type source, Type type, CollectionTraitOptions options, out CollectionTraits result ) - { - if ( type == typeof( IDictionary ) -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - || type == typeof( IReadOnlyDictionary ) -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ) - { - result = - new CollectionTraits( -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ( source == typeof( IDictionary ) || source.Implements( typeof( IDictionary ) ) ) - ? CollectionDetailedKind.GenericDictionary - : CollectionDetailedKind.GenericReadOnlyDictionary, -#else - CollectionDetailedKind.GenericDictionary, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - typeof( KeyValuePair ), - GetGetEnumeratorMethodFromEnumerableType( source, typeof( IEnumerable> ), options ), - GetAddMethod( source, typeof( MessagePackObject ), typeof( MessagePackObject ), options ), - GetCountGetterMethod( source, typeof( KeyValuePair ), options ) - ); - - return true; - } - - if ( type == typeof( IEnumerable ) ) - { - var addMethod = GetAddMethod( source, typeof( MessagePackObject ), options | CollectionTraitOptions.WithAddMethod ); - if ( addMethod != null ) - { - { - result = - new CollectionTraits( - ( source == typeof( IList ) || source.Implements( typeof( IList ) ) ) - ? CollectionDetailedKind.GenericList -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : ( source == typeof( IReadOnlyList ) || source.Implements( typeof( IReadOnlyList ) ) ) - ? CollectionDetailedKind.GenericReadOnlyList -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY - : ( source == typeof( ISet ) || source.Implements( typeof( ISet ) ) ) - ? CollectionDetailedKind.GenericSet -#endif // !NETFX_35 && !UNITY - : ( source == typeof( ICollection ) || - source.Implements( typeof( ICollection ) ) ) - ? CollectionDetailedKind.GenericCollection -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : ( source == typeof( IReadOnlyCollection ) || source.Implements( typeof( IReadOnlyCollection ) ) ) - ? CollectionDetailedKind.GenericReadOnlyCollection -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - : CollectionDetailedKind.GenericEnumerable, - typeof( MessagePackObject ), - GetGetEnumeratorMethodFromEnumerableType( source, typeof( IEnumerable ), options ), - addMethod, - GetCountGetterMethod( source, typeof( MessagePackObject ), options ) - ); - - return true; - } - } - } - - result = default( CollectionTraits ); - return false; - } - - private static bool DetermineCollectionInterfaces( - Type type, - ref Type idictionaryT, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref Type ireadOnlyDictionaryT, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref Type ilistT, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref Type ireadOnlyListT, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY - ref Type isetT, -#endif // !NETFX_35 && !UNITY - ref Type icollectionT, -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref Type ireadOnlyCollectionT, -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - ref Type ienumerableT, - ref Type idictionary, - ref Type ilist, - ref Type icollection, - ref Type ienumerable - ) - { - if ( type.GetIsGenericType() ) - { - var genericTypeDefinition = type.GetGenericTypeDefinition(); - if ( genericTypeDefinition == typeof( IDictionary<,> ) ) - { - if ( idictionaryT != null ) - { - return false; - } - - idictionaryT = type; - } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - else if ( genericTypeDefinition == typeof( IReadOnlyDictionary<,> ) ) - { - if ( ireadOnlyDictionaryT != null ) - { - return false; - } - - ireadOnlyDictionaryT = type; - } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - else if ( genericTypeDefinition == typeof( IList<> ) ) - { - if ( ilistT != null ) - { - return false; - } - - ilistT = type; - } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - else if ( genericTypeDefinition == typeof( IReadOnlyList<> ) ) - { - if ( ireadOnlyListT != null ) - { - return false; - } - - ireadOnlyListT = type; - } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) -#if !NETFX_35 && !UNITY - else if ( genericTypeDefinition == typeof( ISet<> ) ) - { - if ( isetT != null ) - { - return false; - } - - isetT = type; - } -#endif // !NETFX_35 && !UNITY - else if ( genericTypeDefinition == typeof( ICollection<> ) ) - { - if ( icollectionT != null ) - { - return false; - } - - icollectionT = type; - } -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - else if ( genericTypeDefinition == typeof( IReadOnlyCollection<> ) ) - { - if ( ireadOnlyCollectionT != null ) - { - return false; - } - - ireadOnlyCollectionT = type; - } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - else if ( genericTypeDefinition == typeof( IEnumerable<> ) ) - { - if ( ienumerableT != null ) - { - return false; - } - - ienumerableT = type; - } - } - else - { - if ( type == typeof( IDictionary ) ) - { - idictionary = type; - } - else if ( type == typeof( IList ) ) - { - ilist = type; - } - else if ( type == typeof( ICollection ) ) - { - icollection = type; - } - else if ( type == typeof( IEnumerable ) ) - { - ienumerable = type; - } - } - - return true; - } - - private static MethodInfo GetGetEnumeratorMethodFromElementType( Type targetType, Type elementType, CollectionTraitOptions options ) - { - if ( ( options | CollectionTraitOptions.WithGetEnumeratorMethod ) == 0 ) - { - return null; - } - - return FindInterfaceMethod( targetType, typeof( IEnumerable<> ).MakeGenericType( elementType ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ); - } - - private static MethodInfo GetGetEnumeratorMethodFromEnumerableType( Type targetType, Type enumerableType, CollectionTraitOptions options ) - { - if ( ( options | CollectionTraitOptions.WithGetEnumeratorMethod ) == 0 ) - { - return null; - } - - return FindInterfaceMethod( targetType, enumerableType, "GetEnumerator", ReflectionAbstractions.EmptyTypes ); - } - - private static MethodInfo FindInterfaceMethod( Type targetType, Type interfaceType, string name, Type[] parameterTypes ) - { - if ( targetType.GetIsInterface() ) - { - return targetType.FindInterfaces( ( type, _ ) => type == interfaceType, null ).Single().GetMethod( name, parameterTypes ); - } - - var map = targetType.GetInterfaceMap( interfaceType ); - -#if !SILVERLIGHT || WINDOWS_PHONE - int index = Array.FindIndex( map.InterfaceMethods, method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) ); -#else - int index = map.InterfaceMethods.FindIndex( method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) ); -#endif - - if ( index < 0 ) - { -#if DEBUG -#if !NETFX_35 && !UNITY - Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join( ", ", parameterTypes ) + ") is not found in " + targetType ); -#else - Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join( ", ", parameterTypes.Select( t => t.ToString() ).ToArray() ) + ") is not found in " + targetType ); -#endif // !NETFX_35 -#endif // DEBUG - // ReSharper disable once HeuristicUnreachableCode - return null; - } - - return map.TargetMethods[ index ]; - } - - private static MethodInfo GetAddMethod( Type targetType, Type argumentType, CollectionTraitOptions options ) - { - if ( ( options | CollectionTraitOptions.WithAddMethod ) == 0 ) - { - return null; - } - - var argumentTypes = new[] { argumentType }; - var typedAdd = targetType.GetMethod( "Add", argumentTypes ); - if ( typedAdd != null ) +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + var asType = source as Type; + if ( asType != null ) { - return typedAdd; + // Nested type. + return asType; } - - var icollectionT = typeof( ICollection<> ).MakeGenericType( argumentType ); - if ( targetType.IsAssignableTo( icollectionT ) ) - { - return icollectionT.GetMethod( "Add", argumentTypes ); - } - - // It ensures .NET Framework and .NET Core compatibility and provides "natural" feel. - var objectAdd = targetType.GetMethod( "Add", ObjectAddParameterTypes ); - if ( objectAdd != null ) - { - return objectAdd; - } - - if ( targetType.IsAssignableTo( typeof( IList ) ) ) - { - return typeof( IList ).GetMethod( "Add", ObjectAddParameterTypes ); - } - - return null; - } - - // ReSharper disable UnusedParameter.Local - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "targetType", Justification = "For Unity compatibility" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "elementType", Justification = "For Unity compatibility" )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "options", Justification = "For Unity compatibility" )] - private static MethodInfo GetCountGetterMethod( Type targetType, Type elementType, CollectionTraitOptions options ) - // ReSharper restore UnusedParameter.Local - { -#if !UNITY - // get_Count is not used other than Unity. - return null; #else - if ( ( options | CollectionTraitOptions.WithCountPropertyGetter ) == 0 ) - { - return null; - } - - var result = targetType.GetProperty( "Count" ); - if ( result != null && result.GetHasPublicGetter() ) - { - return result.GetGetMethod(); - } - - var icollectionT = typeof( ICollection<> ).MakeGenericType( elementType ); - if ( targetType.IsAssignableTo( icollectionT ) ) - { - return icollectionT.GetProperty( "Count" ).GetGetMethod(); - } - -#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - var ireadOnlyCollectionT = typeof( IReadOnlyCollection<> ).MakeGenericType( elementType ); - if ( targetType.IsAssignableTo( ireadOnlyCollectionT ) ) - { - return ireadOnlyCollectionT.GetProperty( "Count" ).GetGetMethod(); - } -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE ) - - if ( targetType.IsAssignableTo( typeof( ICollection ) ) ) - { - return typeof( ICollection ).GetProperty( "Count" ).GetGetMethod(); - } - - return null; -#endif // !UNITY - } - - private static MethodInfo GetAddMethod( Type targetType, Type keyType, Type valueType, CollectionTraitOptions options ) - { - if ( ( options | CollectionTraitOptions.WithAddMethod ) == 0 ) - { - return null; - } - - var argumentTypes = new[] { keyType, valueType }; - var result = targetType.GetMethod( "Add", argumentTypes ); - if ( result != null ) - { - return result; - } - - return typeof( IDictionary<,> ).MakeGenericType( argumentTypes ).GetMethod( "Add", argumentTypes ); - } - - private static bool FilterCollectionType( Type type, object filterCriteria ) - { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 #if DEBUG - Contract.Assert( type.GetIsInterface(), "type.IsInterface" ); + Contract.Assert( typeof( MemberInfo ).IsAssignableFrom( typeof( Type ) ), "Type is assginable to MemberInfo on this platform, so should not step in this line." ); + Contract.Assert( typeof( Type ).IsAssignableFrom( typeof( TypeInfo ) ), "TypeInfo is assginable to Type on this platform, so should not step in this line." ); #endif // DEBUG - return type.GetAssembly().Equals( typeof( Array ).GetAssembly() ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" ); -#else - var typeInfo = type.GetTypeInfo(); - Contract.Assert( typeInfo.IsInterface ); - return typeInfo.Assembly.Equals( typeof( Array ).GetTypeInfo().Assembly ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - } - - private static bool IsIEnumeratorT( Type @interface ) - { - return @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> ); - } -#if WINDOWS_PHONE - public static IEnumerable FindInterfaces( this Type source, Func filter, object criterion ) - { - foreach ( var @interface in source.GetInterfaces() ) + var asTypeInfo = source as TypeInfo; + if ( asTypeInfo != null ) { - if ( filter( @interface, criterion ) ) - { - yield return @interface; - } + // Nested type. + return asTypeInfo.AsType(); } - } -#endif +#endif // !NETFX_CORE - public static bool GetHasPublicGetter( this MemberInfo source ) - { - PropertyInfo asProperty; - FieldInfo asField; - if ( ( asProperty = source as PropertyInfo ) != null ) - { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - return asProperty.GetGetMethod() != null; -#else - return ( asProperty.GetMethod != null && asProperty.GetMethod.IsPublic ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - } - else if ( ( asField = source as FieldInfo ) != null ) - { - return asField.IsPublic; - } - else - { - throw new NotSupportedException( source.GetType() + " is not supported." ); - } - } + var asProperty = source as PropertyInfo; + var asField = source as FieldInfo; - public static bool GetHasPublicSetter( this MemberInfo source ) - { - PropertyInfo asProperty; - FieldInfo asField; - if ( ( asProperty = source as PropertyInfo ) != null ) - { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - return asProperty.GetSetMethod() != null; -#else - return ( asProperty.SetMethod != null && asProperty.SetMethod.IsPublic ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - } - else if ( ( asField = source as FieldInfo ) != null ) - { - return asField.IsPublic && !asField.IsInitOnly && !asField.IsLiteral; - } - else + if ( asProperty == null && asField == null ) { - throw new NotSupportedException( source.GetType() + " is not supported." ); + throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}'({1}) is not field nor property.", source, source.GetType() ) ); } - } - public static bool GetIsPublic( this MemberInfo source ) - { - PropertyInfo asProperty; - FieldInfo asField; - MethodBase asMethod; -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - Type asType; -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - if ( ( asProperty = source as PropertyInfo ) != null ) - { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - return asProperty.GetAccessors( true ).Where( a => a.ReturnType != typeof( void ) ).All( a => a.IsPublic ); -#else - return - ( asProperty.GetMethod == null || asProperty.GetMethod.IsPublic ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - } - else if ( ( asField = source as FieldInfo ) != null ) - { - return asField.IsPublic; - } - else if ( ( asMethod = source as MethodBase ) != null ) - { - return asMethod.IsPublic; - } -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - else if ( ( asType = source as Type ) != null ) - { - return asType.IsPublic; - } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 - else - { - throw new NotSupportedException( source.GetType() + " is not supported." ); - } + return asProperty != null ? asProperty.PropertyType : asField.FieldType; } } } diff --git a/src/MsgPack/Serialization/ReflectionHelpers.cs b/src/MsgPack/Serialization/ReflectionHelpers.cs index 6eacafc55..bd8bcb539 100644 --- a/src/MsgPack/Serialization/ReflectionHelpers.cs +++ b/src/MsgPack/Serialization/ReflectionHelpers.cs @@ -1,4 +1,4 @@ - + #region -- License Terms -- // // MessagePack for CLI @@ -28,11 +28,11 @@ using System; using System.Linq; -#if UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // UNITY +#endif // FEATURE_MPCONTRACT #if !UNITY || MSGPACK_UNITY_FULL using System.ComponentModel; #endif //!UNITY || MSGPACK_UNITY_FULL @@ -143,4 +143,4 @@ public static FieldInfo GetField( Type type, string name ) return null; } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionCollectionMessagePackSerializer`2.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionCollectionMessagePackSerializer`2.cs index be8f8c4d8..dea07da33 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionCollectionMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionCollectionMessagePackSerializer`2.cs @@ -61,11 +61,21 @@ internal sealed class ReflectionCollectionMessagePackSerializer : UnityCollectio public ReflectionCollectionMessagePackSerializer( SerializationContext ownerContext, Type targetType, - PolymorphismSchema itemsSchema + CollectionTraits collectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); #if FEATURE_TAP @@ -78,12 +88,21 @@ public ReflectionCollectionMessagePackSerializer( SerializationContext ownerContext, Type abstractType, Type concreteType, - CollectionTraits traits, - PolymorphismSchema itemsSchema + CollectionTraits concreteTypeCollectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, traits, itemsSchema ) + : base( ownerContext, abstractType, concreteTypeCollectionTraits, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, traits.ElementType ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, concreteTypeCollectionTraits.ElementType, targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionDictionaryMessagePackSerializer`3.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionDictionaryMessagePackSerializer`3.cs index 8a574fa6f..81a5b6e12 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionDictionaryMessagePackSerializer`3.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionDictionaryMessagePackSerializer`3.cs @@ -60,11 +60,21 @@ internal sealed class ReflectionDictionaryMessagePackSerializer : UnityDictionar public ReflectionDictionaryMessagePackSerializer( SerializationContext ownerContext, Type targetType, - PolymorphismSchema itemsSchema + CollectionTraits collectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TDictionary ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TDictionary ) ); #if FEATURE_TAP @@ -79,12 +89,21 @@ public ReflectionDictionaryMessagePackSerializer( Type concreteType, Type keyType, Type valueType, - CollectionTraits traits, - PolymorphismSchema itemsSchema + CollectionTraits concreteTypeCollectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, keyType, valueType, traits, itemsSchema ) + : base( ownerContext, abstractType, keyType, valueType, concreteTypeCollectionTraits, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, keyType ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, keyType, targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionEnumerableMessagePackSerializer`2.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionEnumerableMessagePackSerializer`2.cs index 2c40dcb14..91e60341b 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionEnumerableMessagePackSerializer`2.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionEnumerableMessagePackSerializer`2.cs @@ -63,12 +63,22 @@ public ReflectionEnumerableMessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits collectionTraits, - PolymorphismSchema itemsSchema + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); - this._addItem = ReflectionSerializerHelper.GetAddItem( targetType, collectionTraits ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + this._addItem = ReflectionSerializerHelper.GetAddItem( targetType, collectionTraits ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); #if FEATURE_TAP @@ -81,13 +91,23 @@ public ReflectionEnumerableMessagePackSerializer( SerializationContext ownerContext, Type abstractType, Type concreteType, - CollectionTraits traits, - PolymorphismSchema itemsSchema + CollectionTraits concreteTypeCollectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, traits, itemsSchema ) + : base( ownerContext, abstractType, concreteTypeCollectionTraits, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, traits.ElementType ); - this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, traits ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, concreteTypeCollectionTraits.ElementType, targetInfo.DeserializationConstructor ); + this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, concreteTypeCollectionTraits ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricCollectionMessagePackSerializer`1.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricCollectionMessagePackSerializer`1.cs index 09fe19745..a27618954 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricCollectionMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricCollectionMessagePackSerializer`1.cs @@ -63,12 +63,22 @@ public ReflectionNonGenericCollectionMessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits collectionTraits, - PolymorphismSchema itemsSchema + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); - this._addItem = ReflectionSerializerHelper.GetAddItem( targetType, collectionTraits ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + this._addItem = ReflectionSerializerHelper.GetAddItem( targetType, collectionTraits ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); #if FEATURE_TAP @@ -82,12 +92,22 @@ public ReflectionNonGenericCollectionMessagePackSerializer( Type abstractType, Type concreteType, CollectionTraits concreteTypeCollectionTraits, - PolymorphismSchema itemsSchema + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, itemsSchema ) + : base( ownerContext, abstractType, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ) ); - this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, concreteTypeCollectionTraits ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ), targetInfo.DeserializationConstructor ); + this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, concreteTypeCollectionTraits ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs index e35146a29..a8e1c4ed0 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGeenricEnumerableMessagePackSerializer`1.cs @@ -63,12 +63,22 @@ public ReflectionNonGenericEnumerableMessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits collectionTraits, - PolymorphismSchema itemsSchema + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); - this._addItem = ReflectionSerializerHelper.GetAddItem( targetType, collectionTraits ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + this._addItem = ReflectionSerializerHelper.GetAddItem( targetType, collectionTraits ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TCollection ) ); #if FEATURE_TAP @@ -82,12 +92,22 @@ public ReflectionNonGenericEnumerableMessagePackSerializer( Type abstractType, Type concreteType, CollectionTraits concreteTypeCollectionTraits, - PolymorphismSchema itemsSchema + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, itemsSchema ) + : base( ownerContext, abstractType, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ) ); - this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, concreteTypeCollectionTraits ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ), targetInfo.DeserializationConstructor ); + this._addItem = ReflectionSerializerHelper.GetAddItem( concreteType, concreteTypeCollectionTraits ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + this._addItem = ( c, x ) => { throw SerializationExceptions.NewUnpackFromIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericDictionaryMessagePackSerializer`1.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericDictionaryMessagePackSerializer`1.cs index 26b335776..dea76c537 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericDictionaryMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericDictionaryMessagePackSerializer`1.cs @@ -60,11 +60,21 @@ internal sealed class ReflectionNonGenericDictionaryMessagePackSerializer : Unit public ReflectionNonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, Type targetType, - PolymorphismSchema itemsSchema + CollectionTraits collectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TDictionary ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TDictionary ) ); #if FEATURE_TAP @@ -77,11 +87,21 @@ public ReflectionNonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, Type abstractType, Type concreteType, - PolymorphismSchema itemsSchema + CollectionTraits concreteTypeCollectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, itemsSchema ) + : base( ownerContext, abstractType, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ) ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ), targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericListMessagePackSerializer`1.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericListMessagePackSerializer`1.cs index 6a770ea8a..761582804 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericListMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionNonGenericListMessagePackSerializer`1.cs @@ -61,11 +61,21 @@ internal sealed class ReflectionNonGenericListMessagePackSerializer : UnityNonGe public ReflectionNonGenericListMessagePackSerializer( SerializationContext ownerContext, Type targetType, - PolymorphismSchema itemsSchema + CollectionTraits collectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, itemsSchema ) + : base( ownerContext, itemsSchema, targetInfo.GetCapabilitiesForCollection( collectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetType ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( targetType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( targetType ?? typeof( TList ) ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( targetType ?? typeof( TList ) ); #if FEATURE_TAP @@ -78,11 +88,21 @@ public ReflectionNonGenericListMessagePackSerializer( SerializationContext ownerContext, Type abstractType, Type concreteType, - PolymorphismSchema itemsSchema + CollectionTraits concreteTypeCollectionTraits, + PolymorphismSchema itemsSchema, + SerializationTarget targetInfo ) - : base( ownerContext, abstractType, itemsSchema ) + : base( ownerContext, abstractType, itemsSchema, targetInfo.GetCapabilitiesForCollection( concreteTypeCollectionTraits ) ) { - this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ) ); + if ( targetInfo.CanDeserialize ) + { + this._factory = ReflectionSerializerHelper.CreateCollectionInstanceFactory( abstractType, concreteType, typeof( object ), targetInfo.DeserializationConstructor ); + } + else + { + this._factory = _ => { throw SerializationExceptions.NewCreateInstanceIsNotSupported( concreteType ); }; + } + this._isPackable = typeof( IPackable ).IsAssignableFrom( concreteType ?? abstractType ); this._isUnpackable = typeof( IUnpackable ).IsAssignableFrom( concreteType ?? abstractType ); } diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionObjectMessagePackSerializer`1.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionObjectMessagePackSerializer`1.cs index af8f4cf43..bb060346c 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionObjectMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionObjectMessagePackSerializer`1.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014-2016 FUJIWARA, Yusuke +// Copyright (C) 2014-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -25,11 +28,11 @@ using System; using System.Collections; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; using System.Reflection; #if FEATURE_TAP @@ -54,17 +57,16 @@ internal class ReflectionObjectMessagePackSerializer : MessagePackSerializer< private readonly ParameterInfo[] _constructorParameters; private readonly Dictionary _constructorArgumentIndexes; - public ReflectionObjectMessagePackSerializer( SerializationContext context ) - : base( context ) + public ReflectionObjectMessagePackSerializer( SerializationContext context, SerializationTarget target, SerializerCapabilities capabilities ) + : base( context, capabilities ) { - SerializationTarget.VerifyType( typeof( T ) ); - var target = SerializationTarget.Prepare( context, typeof( T ) ); ReflectionSerializerHelper.GetMetadata( typeof( T ), target.Members, context, out this._getters, out this._setters, out this._memberInfos, out this._contracts, out this._serializers ); this._memberIndexes = this._contracts .Select( ( contract, index ) => new KeyValuePair( contract.Name, index ) ) .Where( kv => kv.Key != null ) - .ToDictionary( kv => kv.Key, kv => kv.Value ); + // Set key as transformed. + .ToDictionary( kv => context.DictionarySerializationOptions.SafeKeyTransformer( kv.Key ), kv => kv.Value ); this._constructorParameters = ( !typeof( IUnpackable ).IsAssignableFrom( typeof( T ) ) && target.IsConstructorDeserialization ) ? target.DeserializationConstructor.GetParameters() @@ -110,15 +112,60 @@ protected internal override void PackToCore( Packer packer, T objectTree ) } else { - packer.PackMapHeader( this._serializers.Length ); - for ( int i = 0; i < this._serializers.Length; i++ ) + if ( this.OwnerContext.DictionarySerializationOptions.OmitNullEntry +#if DEBUG + && !SerializerDebugging.UseLegacyNullMapEntryHandling +#endif // DEBUG + ) { - packer.PackString( this._contracts[ i ].Name ); - this.PackMemberValue( packer, objectTree, i ); + // Skipping causes the entries count header reducing, so count up null entries first. + var nullCount = 0; + for ( int i = 0; i < this._serializers.Length; i++ ) + { + // Set key as transformed. + if ( this.IsNull( objectTree, i ) ) + { + nullCount++; + } + } + + packer.PackMapHeader( this._serializers.Length - nullCount ); + for ( int i = 0; i < this._serializers.Length; i++ ) + { + if ( this.IsNull( objectTree, i ) ) + { + continue; + } + + // Set key as transformed. + packer.PackString( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ) ); + this.PackMemberValue( packer, objectTree, i ); + } + } + else + { + packer.PackMapHeader( this._serializers.Length ); + for ( int i = 0; i < this._serializers.Length; i++ ) + { + // Set key as transformed. + packer.PackString( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ) ); + this.PackMemberValue( packer, objectTree, i ); + } } } } + private bool IsNull( T objectTree, int index ) + { + if ( this._getters[ index ] == null ) + { + // missing member should be treated as nil. + return true; + } + + return this._getters[ index ]( objectTree ) == null; + } + private void PackMemberValue( Packer packer, T objectTree, int index ) { if ( this._getters[ index ] == null ) @@ -167,11 +214,45 @@ protected internal override async Task PackToAsyncCore( Packer packer, T objectT } else { - await packer.PackMapHeaderAsync( this._serializers.Length, cancellationToken ).ConfigureAwait( false ); - for ( int i = 0; i < this._serializers.Length; i++ ) + if ( this.OwnerContext.DictionarySerializationOptions.OmitNullEntry +#if DEBUG + && !SerializerDebugging.UseLegacyNullMapEntryHandling +#endif // DEBUG + ) { - await packer.PackStringAsync( this._contracts[ i ].Name, cancellationToken ).ConfigureAwait( false ); - await this.PackMemberValueAsync( packer, objectTree, i, cancellationToken ).ConfigureAwait( false ); + // Skipping causes the entries count header reducing, so count up null entries first. + var nullCount = 0; + for ( int i = 0; i < this._serializers.Length; i++ ) + { + // Set key as transformed. + if ( this.IsNull( objectTree, i ) ) + { + nullCount++; + } + } + + await packer.PackMapHeaderAsync( this._serializers.Length - nullCount, cancellationToken ).ConfigureAwait( false ); + for ( int i = 0; i < this._serializers.Length; i++ ) + { + if ( this.IsNull( objectTree, i ) ) + { + continue; + } + + // Set key as transformed. + await packer.PackStringAsync( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ), cancellationToken ).ConfigureAwait( false ); + await this.PackMemberValueAsync( packer, objectTree, i, cancellationToken ).ConfigureAwait( false ); + } + } + else + { + await packer.PackMapHeaderAsync( this._serializers.Length, cancellationToken ).ConfigureAwait( false ); + for ( int i = 0; i < this._serializers.Length; i++ ) + { + // Set key as transformed. + await packer.PackStringAsync( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ), cancellationToken ).ConfigureAwait( false ); + await this.PackMemberValueAsync( packer, objectTree, i, cancellationToken ).ConfigureAwait( false ); + } } } } @@ -307,7 +388,7 @@ private object UnpackMemberValue( object objectGraph, Unpacker unpacker, int ite { nullable = this.UnpackSingleValue( unpacker, index ); } - else if ( this._getters[ index ] != null ) // null getter supposes undeclared member (should be treated as nil) + else if ( index < this._getters.Length && this._getters[ index ] != null ) // null getter supposes undeclared member (should be treated as nil) { this.UnpackAndAddCollectionItem( objectGraph, unpacker, index ); } @@ -388,7 +469,7 @@ private void UnpackAndAddCollectionItem( object objectGraph, Unpacker unpacker, throw SerializationExceptions.NewReadOnlyMemberItemsMustNotBeNull( this._contracts[ index ].Name ); } - var traits = destination.GetType().GetCollectionTraits( CollectionTraitOptions.WithAddMethod ); + var traits = destination.GetType().GetCollectionTraits( CollectionTraitOptions.WithAddMethod, this.OwnerContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); if ( traits.AddMethod == null ) { throw SerializationExceptions.NewUnpackToIsNotSupported( destination.GetType(), null ); @@ -637,7 +718,7 @@ private async Task UnpackAndAddCollectionItemAsync( object objectGraph, Unpacker throw SerializationExceptions.NewReadOnlyMemberItemsMustNotBeNull( this._contracts[ index ].Name ); } - var traits = destination.GetType().GetCollectionTraits( CollectionTraitOptions.WithAddMethod ); + var traits = destination.GetType().GetCollectionTraits( CollectionTraitOptions.WithAddMethod, this.OwnerContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); if ( traits.AddMethod == null ) { throw SerializationExceptions.NewUnpackToIsNotSupported( destination.GetType(), null ); diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionSerializerHelper.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionSerializerHelper.cs index 5febbe482..eebd583a8 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionSerializerHelper.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionSerializerHelper.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014-2016 FUJIWARA, Yusuke +// Copyright (C) 2014-2018 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -27,11 +30,11 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Reflection; using System.Runtime.Serialization; @@ -43,7 +46,12 @@ namespace MsgPack.Serialization.ReflectionSerializers /// /// Helper static methods for reflection serializers. /// - internal static class ReflectionSerializerHelper +#if UNITY && DEBUG + public +#else + internal +#endif + static class ReflectionSerializerHelper { internal static readonly PropertyInfo DictionaryEntryKeyProperty = typeof( DictionaryEntry ).GetProperty( "Key" ); internal static readonly PropertyInfo DictionaryEntryValueProperty = typeof( DictionaryEntry ).GetProperty( "Value" ); @@ -54,7 +62,7 @@ public static MessagePackSerializer CreateReflectionEnumMessagePackSerializer return ReflectionExtensions.CreateInstancePreservingExceptionType>( typeof( ReflectionEnumMessagePackSerializer<> ).MakeGenericType( typeof( T ) ), - context + context ); #else return MessagePackSerializer.Wrap( context, new ReflectionEnumMessagePackSerializer( context, typeof( T ) ) ); @@ -72,6 +80,8 @@ public static MessagePackSerializer CreateCollectionSerializer( PolymorphismSchema schema ) { + var targetInfo = UnpackHelpers.DetermineCollectionSerializationStrategy( targetType, context.CompatibilityOptions.AllowAsymmetricSerializer ); + switch ( traits.DetailedCollectionType ) { case CollectionDetailedKind.Array: @@ -79,9 +89,9 @@ PolymorphismSchema schema return ArraySerializer.Create( context, schema ); } case CollectionDetailedKind.GenericList: -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY case CollectionDetailedKind.GenericSet: -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY case CollectionDetailedKind.GenericCollection: { return @@ -89,9 +99,9 @@ PolymorphismSchema schema ( MessagePackSerializer ) ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( CollectionSerializerFactory<,> ).MakeGenericType( typeof( T ), traits.ElementType ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else - new ReflectionCollectionMessagePackSerializer( context, typeof( T ), targetType, traits, schema ); + new ReflectionCollectionMessagePackSerializer( context, typeof( T ), targetType, traits, schema, targetInfo ); #endif // !UNITY } case CollectionDetailedKind.GenericEnumerable: @@ -101,9 +111,9 @@ PolymorphismSchema schema ( MessagePackSerializer ) ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( EnumerableSerializerFactory<,> ).MakeGenericType( typeof( T ), traits.ElementType ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else - new ReflectionEnumerableMessagePackSerializer( context, typeof( T ), targetType, traits, schema ); + new ReflectionEnumerableMessagePackSerializer( context, typeof( T ), targetType, traits, schema, targetInfo ); #endif // !Enumerable } case CollectionDetailedKind.GenericDictionary: @@ -118,7 +128,7 @@ PolymorphismSchema schema genericArgumentOfKeyValuePair[ 0 ], genericArgumentOfKeyValuePair[ 1 ] ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else new ReflectionDictionaryMessagePackSerializer( context, @@ -127,7 +137,8 @@ genericArgumentOfKeyValuePair[ 1 ] genericArgumentOfKeyValuePair[ 0 ], genericArgumentOfKeyValuePair[ 1 ], traits, - schema + schema, + targetInfo ); #endif // !UNITY } @@ -138,9 +149,9 @@ genericArgumentOfKeyValuePair[ 1 ] ( MessagePackSerializer ) ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( NonGenericListSerializerFactory<> ).MakeGenericType( typeof( T ) ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else - new ReflectionNonGenericListMessagePackSerializer( context, typeof( T ), targetType, schema ); + new ReflectionNonGenericListMessagePackSerializer( context, typeof( T ), targetType, traits, schema, targetInfo ); #endif // !UNITY } case CollectionDetailedKind.NonGenericCollection: @@ -150,9 +161,9 @@ genericArgumentOfKeyValuePair[ 1 ] ( MessagePackSerializer ) ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( NonGenericCollectionSerializerFactory<> ).MakeGenericType( typeof( T ) ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else - new ReflectionNonGenericCollectionMessagePackSerializer( context, typeof( T ), targetType, targetType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod ), schema ); + new ReflectionNonGenericCollectionMessagePackSerializer( context, typeof( T ), targetType, traits, schema, targetInfo ); #endif // !UNITY } case CollectionDetailedKind.NonGenericEnumerable: @@ -162,9 +173,9 @@ genericArgumentOfKeyValuePair[ 1 ] ( MessagePackSerializer ) ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( NonGenericEnumerableSerializerFactory<> ).MakeGenericType( typeof( T ) ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else - new ReflectionNonGenericEnumerableMessagePackSerializer( context, typeof( T ), targetType, targetType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod ), schema ); + new ReflectionNonGenericEnumerableMessagePackSerializer( context, typeof( T ), targetType, traits, schema, targetInfo ); #endif // !UNITY } case CollectionDetailedKind.NonGenericDictionary: @@ -174,9 +185,9 @@ genericArgumentOfKeyValuePair[ 1 ] ( MessagePackSerializer ) ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( NonGenericDictionarySerializerFactory<> ).MakeGenericType( typeof( T ) ) - ).Create( context, targetType, traits, schema ); + ).Create( context, targetType, traits, schema, targetInfo ); #else - new ReflectionNonGenericDictionaryMessagePackSerializer( context, typeof( T ), targetType, schema ); + new ReflectionNonGenericDictionaryMessagePackSerializer( context, typeof( T ), targetType, traits, schema, targetInfo ); #endif // !UNITY } default: @@ -195,7 +206,7 @@ public static Action GetAddItem( Type targetType, CollectionTrai { if ( collectionTraits.AddMethod == null ) { - throw new NotSupportedException( + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Reflection based serializer only supports collection types which implement interface to add new item such as '{0}' and '{1}'", @@ -207,18 +218,18 @@ public static Action GetAddItem( Type targetType, CollectionTrai // CreateDelegate causes AOT error. // So use reflection in AOT environment. -#if !AOT || AOT_CHECK - try +#if !UNITY + if ( SerializerOptions.CanEmit ) { - return collectionTraits.AddMethod.CreateDelegate( typeof( Action ) ) as Action; + try + { + return collectionTraits.AddMethod.CreateDelegate( typeof( Action ) ) as Action; + } + catch ( ArgumentException ) { } } - catch ( ArgumentException ) - { -#endif // !AOT || AOT_CHECK +#endif //! UNITY + return ( collection, item ) => collectionTraits.AddMethod.InvokePreservingExceptionType( collection, item ); -#if !AOT || AOT_CHECK - } -#endif // !AOT || AOT_CHECK } public static void GetMetadata( @@ -229,8 +240,65 @@ public static void GetMetadata( out Action[] setters, out MemberInfo[] memberInfos, out DataMemberContract[] contracts, - out MessagePackSerializer[] serializers ) + out MessagePackSerializer[] serializers + ) { + SerializationTarget.VerifyCanSerializeTargetType( context, targetType ); + + if ( members.Count == 0 ) + { + if ( !typeof( IPackable ).IsAssignableFrom( targetType ) ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "At least one serializable member is required because type '{0}' does not implement IPackable interface.", + targetType + ) + ); + } + + if ( !typeof( IUnpackable ).IsAssignableFrom( targetType ) ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "At least one serializable member is required because type '{0}' does not implement IUnpackable interface.", + targetType + ) + ); + } + +#if FEATURE_TAP + if ( context.SerializerOptions.WithAsync ) + { + if ( !typeof( IAsyncPackable ).IsAssignableFrom( targetType ) ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "At least one serializable member is required because type '{0}' does not implement IAsyncPackable interface.", + targetType + ) + ); + } + + if ( !typeof( IAsyncUnpackable ).IsAssignableFrom( targetType ) ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "At least one serializable member is required because type '{0}' does not implement IAsyncUnpackable interface.", + targetType + ) + ); + } + } + +#endif // FEATURE_TAP + + } + getters = new Func[ members.Count ]; setters = new Action[ members.Count ]; memberInfos = new MemberInfo[ members.Count ]; @@ -253,8 +321,16 @@ public static void GetMetadata( FieldInfo asField; if ( ( asField = member.Member as FieldInfo ) != null ) { + if ( context.SerializerOptions.DisablePrivilegedAccess && !asField.GetIsPublic() ) + { + continue; + } + getters[ i ] = asField.GetValue; - setters[ i ] = asField.SetValue; + if ( !asField.IsInitOnly ) + { + setters[ i ] = asField.SetValue; + } } else { @@ -262,6 +338,11 @@ public static void GetMetadata( #if DEBUG Contract.Assert( property != null, "member.Member is PropertyInfo" ); #endif // DEBUG + if ( context.SerializerOptions.DisablePrivilegedAccess && !property.GetIsPublic() ) + { + continue; + } + var getter = property.GetGetMethod( true ); if ( getter == null ) { @@ -270,7 +351,7 @@ public static void GetMetadata( getters[ i ] = target => getter.InvokePreservingExceptionType( target, null ); var setter = property.GetSetMethod( true ); - if ( setter != null ) + if ( setter != null && ( !context.SerializerOptions.DisablePrivilegedAccess || setter.GetIsPublic() ) ) { setters[ i ] = ( target, value ) => setter.InvokePreservingExceptionType( target, new[] { value } ); } @@ -331,19 +412,19 @@ private static void ThrowMissingGetterException( Type targetType, int number, Pr } #if !UNITY - public static Func CreateCollectionInstanceFactory( Type targetType ) + public static Func CreateCollectionInstanceFactory( ConstructorInfo constructor ) #else - public static Func CreateCollectionInstanceFactory( Type abstractType, Type targetType, Type comparisonType ) + public static Func CreateCollectionInstanceFactory( Type abstractType, Type targetType, Type comparisonType, ConstructorInfo constructor ) #endif // !UNITY { - var constructor = UnpackHelpers.GetCollectionConstructor( targetType ); + // ReSharper disable once PossibleNullReferenceException var parameters = constructor.GetParameters(); switch ( parameters.Length ) { case 0: { - return _ => + return _ => #if !UNITY ( T ) #endif // !UNITY @@ -421,99 +502,139 @@ public static Func CreateCollectionInstanceFactory( Type abstractTy /// /// Defines non-generic factory method for 'universal' serializers which use general collection features. /// - private interface IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + interface IVariantReflectionSerializerFactory { - MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ); + MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ); } // ReSharper disable MemberHidesStaticFromOuterClass [Preserve( AllMembers = true )] - private sealed class NonGenericEnumerableSerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericEnumerableSerializerFactory : IVariantReflectionSerializerFactory where T : IEnumerable { public NonGenericEnumerableSerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { - return new ReflectionNonGenericEnumerableMessagePackSerializer( context, targetType, collectionTraits, schema ); + return new ReflectionNonGenericEnumerableMessagePackSerializer( context, targetType, collectionTraits, schema, targetInfo ); } } [Preserve( AllMembers = true )] - private sealed class NonGenericCollectionSerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericCollectionSerializerFactory : IVariantReflectionSerializerFactory where T : ICollection { public NonGenericCollectionSerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { - return new ReflectionNonGenericCollectionMessagePackSerializer( context, targetType, collectionTraits, schema ); + return new ReflectionNonGenericCollectionMessagePackSerializer( context, targetType, collectionTraits, schema, targetInfo ); } } [Preserve( AllMembers = true )] - private sealed class NonGenericListSerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericListSerializerFactory : IVariantReflectionSerializerFactory where T : IList { public NonGenericListSerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { - return new ReflectionNonGenericListMessagePackSerializer( context, targetType, schema ); + return new ReflectionNonGenericListMessagePackSerializer( context, targetType, collectionTraits, schema, targetInfo ); } } [Preserve( AllMembers = true )] - private sealed class NonGenericDictionarySerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class NonGenericDictionarySerializerFactory : IVariantReflectionSerializerFactory where T : IDictionary { public NonGenericDictionarySerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { - return new ReflectionNonGenericDictionaryMessagePackSerializer( context, targetType, schema ); + return new ReflectionNonGenericDictionaryMessagePackSerializer( context, targetType, collectionTraits, schema, targetInfo ); } } [Preserve( AllMembers = true )] - private sealed class EnumerableSerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class EnumerableSerializerFactory : IVariantReflectionSerializerFactory where TCollection : IEnumerable { public EnumerableSerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { var itemSchema = schema ?? PolymorphismSchema.Default; - return new ReflectionEnumerableMessagePackSerializer( context, targetType, collectionTraits, itemSchema ); + return new ReflectionEnumerableMessagePackSerializer( context, targetType, collectionTraits, itemSchema, targetInfo ); } } [Preserve( AllMembers = true )] - private sealed class CollectionSerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class CollectionSerializerFactory : IVariantReflectionSerializerFactory where TCollection : ICollection { public CollectionSerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { var itemSchema = schema ?? PolymorphismSchema.Default; - return new ReflectionCollectionMessagePackSerializer( context, targetType, itemSchema ); + return new ReflectionCollectionMessagePackSerializer( context, targetType, collectionTraits, itemSchema, targetInfo ); } } [Preserve( AllMembers = true )] - private sealed class DictionarySerializerFactory : IVariantReflectionSerializerFactory +#if SILVERLIGHT + internal +#else + private +#endif // SILVERLIGHT + sealed class DictionarySerializerFactory : IVariantReflectionSerializerFactory where TDictionary : IDictionary { public DictionarySerializerFactory() { } - public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema ) + public MessagePackSerializer Create( SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo ) { - return new ReflectionDictionaryMessagePackSerializer( context, targetType, schema ); + return new ReflectionDictionaryMessagePackSerializer( context, targetType, collectionTraits, schema, targetInfo ); } } // ReSharper restore MemberHidesStaticFromOuterClass #endif // !UNITY } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionTupleMessagePackSerializer`1.cs b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionTupleMessagePackSerializer`1.cs index 24768abb8..899de1c7e 100644 --- a/src/MsgPack/Serialization/ReflectionSerializers/ReflectionTupleMessagePackSerializer`1.cs +++ b/src/MsgPack/Serialization/ReflectionSerializers/ReflectionTupleMessagePackSerializer`1.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2014-2016 FUJIWARA, Yusuke +// Copyright (C) 2014-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,11 +24,11 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; using System.Reflection; #if FEATURE_TAP @@ -47,62 +47,95 @@ internal class ReflectionTupleMessagePackSerializer : MessagePackSerializer _tupleTypes; private readonly IList _tupleConstructors; - private readonly IList> _getters; + private readonly IList> _getters; private readonly IList _itemSerializers; public ReflectionTupleMessagePackSerializer( SerializationContext ownerContext, IList itemSchemas ) - : base( ownerContext ) + : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) { var itemTypes = TupleItems.GetTupleItemTypes( typeof( T ) ); this._itemSerializers = itemTypes.Select( ( itemType, i ) => ownerContext.GetSerializer( itemType, itemSchemas.Count == 0 ? null : itemSchemas[ i ] ) ).ToArray(); - this._tupleTypes = TupleItems.CreateTupleTypeList( itemTypes ); - this._tupleConstructors = this._tupleTypes.Select( tupleType => tupleType.GetConstructors().Single() ).ToArray(); - this._getters = GetGetters( itemTypes, this._tupleTypes ).ToArray(); + this._tupleTypes = TupleItems.CreateTupleTypeList( typeof( T ) ); + this._tupleConstructors = this._tupleTypes.Select( tupleType => tupleType.GetConstructors().SingleOrDefault() ).ToArray(); + this._getters = + typeof( T ).GetIsValueType() + ? GetGetters( + itemTypes, + this._tupleTypes, + ( type, name ) => type.GetField( name ), + f => f, + getters => + tuple => + { + object current = tuple; + foreach ( var getter in getters ) + { + current = getter.GetValue( current ); + } + + return current; + } + ).ToArray() + : GetGetters( + itemTypes, + this._tupleTypes, + ( type, name ) => type.GetProperty( name ), + p => p.GetGetMethod(), + getters => + tuple => + { + object current = tuple; + foreach ( var getter in getters ) + { + current = getter.InvokePreservingExceptionType( current ); + } + + return current; + } + ).ToArray(); } - private static IEnumerable> GetGetters( IList itemTypes, IList tupleTypes ) + private static IEnumerable> GetGetters( + IList itemTypes, + IList tupleTypes, + Func metadataFactory, + Func accessorFactory, + Func, Func> chainedGetterFactory + ) { var depth = -1; - var propertyInvocationChain = new List( itemTypes.Count % 7 + 1 ); - for ( int i = 0; i < itemTypes.Count; i++ ) + var memberInvocationChain = new List( itemTypes.Count % 7 + 1 ); + for ( var i = 0; i < itemTypes.Count; i++ ) { if ( i % 7 == 0 ) { depth++; } - for ( int j = 0; j < depth; j++ ) + for ( var j = 0; j < depth; j++ ) { // .TRest.TRest ... - var restProperty = tupleTypes[ j ].GetProperty( "Rest" ); - Contract.Assert( restProperty != null, "restProperty != null" ); - propertyInvocationChain.Add( restProperty ); + var restMember = metadataFactory( tupleTypes[ j ], "Rest" ); +#if DEBUG + Contract.Assert( restMember != null, "restMember != null" ); +#endif // DEBUG + memberInvocationChain.Add( restMember ); } - var itemNProperty = tupleTypes[ depth ].GetProperty( "Item" + ( ( i % 7 ) + 1 ) ); - propertyInvocationChain.Add( itemNProperty ); + var itemNMember = metadataFactory( tupleTypes[ depth ], "Item" + ( ( i % 7 ) + 1 ) ); + memberInvocationChain.Add( itemNMember ); #if DEBUG Contract.Assert( - itemNProperty != null, + itemNMember != null, tupleTypes[ depth ].GetFullName() + "::Item" + ( ( i % 7 ) + 1 ) + " [ " + depth + " ] @ " + i ); #endif // DEBUG - var getters = propertyInvocationChain.Select( property => property.GetGetMethod() ).ToArray(); - yield return - tuple => - { - object current = tuple; - foreach ( var getter in getters ) - { - current = getter.InvokePreservingExceptionType( current ); - } - - return current; - }; - - propertyInvocationChain.Clear(); + var getters = memberInvocationChain.Select( accessorFactory ).ToArray(); + yield return chainedGetterFactory( getters ); + + memberInvocationChain.Clear(); } } @@ -111,7 +144,7 @@ protected internal override void PackToCore( Packer packer, T objectTree ) { // Put cardinality as array length. packer.PackArrayHeader( this._itemSerializers.Count ); - for ( int i = 0; i < this._itemSerializers.Count; i++ ) + for ( var i = 0; i < this._itemSerializers.Count; i++ ) { this._itemSerializers[ i ].PackTo( packer, this._getters[ i ]( objectTree ) ); } @@ -123,7 +156,7 @@ protected internal override async Task PackToAsyncCore( Packer packer, T objectT { // Put cardinality as array length. await packer.PackArrayHeaderAsync( this._itemSerializers.Count, cancellationToken ).ConfigureAwait( false ); - for ( int i = 0; i < this._itemSerializers.Count; i++ ) + for ( var i = 0; i < this._itemSerializers.Count; i++ ) { await this._itemSerializers[ i ].PackToAsync( packer, this._getters[ i ]( objectTree ), cancellationToken ).ConfigureAwait( false ); } @@ -197,7 +230,7 @@ protected internal override async Task UnpackFromAsyncCore( Unpacker unpacker private T CreateTuple( IList unpackedItems ) { object currentTuple = null; - for ( int nest = this._tupleTypes.Count - 1; nest >= 0; nest-- ) + for ( var nest = this._tupleTypes.Count - 1; nest >= 0; nest-- ) { var items = unpackedItems.Skip( nest * 7 ).Take( Math.Min( unpackedItems.Count, 7 ) ).ToList(); if ( currentTuple != null ) @@ -206,7 +239,9 @@ private T CreateTuple( IList unpackedItems ) } currentTuple = - this._tupleConstructors[ nest ].InvokePreservingExceptionType( items.ToArray() ); + this._tupleConstructors[ nest ] == null + ? ReflectionExtensions.CreateInstancePreservingExceptionType( this._tupleTypes[ nest ] ) + : this._tupleConstructors[ nest ].InvokePreservingExceptionType( items.ToArray() ); } return ( T )currentTuple; diff --git a/src/MsgPack/Serialization/ResolveSerializerEventArgs.cs b/src/MsgPack/Serialization/ResolveSerializerEventArgs.cs index b911cb5f1..eed03eb46 100644 --- a/src/MsgPack/Serialization/ResolveSerializerEventArgs.cs +++ b/src/MsgPack/Serialization/ResolveSerializerEventArgs.cs @@ -24,11 +24,11 @@ using System; #if DEBUG -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // DEBUG using System.Globalization; diff --git a/src/MsgPack/Serialization/SerializationCompatibilityLevel.cs b/src/MsgPack/Serialization/SerializationCompatibilityLevel.cs new file mode 100644 index 000000000..3232cf851 --- /dev/null +++ b/src/MsgPack/Serialization/SerializationCompatibilityLevel.cs @@ -0,0 +1,46 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2018 FUJIWARA, Yusuke and contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Contributors: +// Samuel Cragg +// +#endregion -- License Terms -- + +namespace MsgPack.Serialization +{ + /// + /// Represents compatibility level. + /// + public enum SerializationCompatibilityLevel + { + /// + /// Use latest feature. Almost backward compatible, but some compatibities are broken. + /// + Latest = 0, + + /// + /// Compatible for version 0.5.x or former. + /// + Version0_5, + + /// + /// Compatible for version 0.6.x, 0.7.x, 0.8.x, and 0.9.x. + /// + Version0_9 + } +} diff --git a/src/MsgPack/Serialization/SerializationCompatibilityOptions.cs b/src/MsgPack/Serialization/SerializationCompatibilityOptions.cs index 1a52ce485..c6fa54869 100644 --- a/src/MsgPack/Serialization/SerializationCompatibilityOptions.cs +++ b/src/MsgPack/Serialization/SerializationCompatibilityOptions.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT @@ -32,11 +35,12 @@ namespace MsgPack.Serialization /// public sealed class SerializationCompatibilityOptions { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT private volatile bool _oneBoundDataMemberOrder; #else private bool _oneBoundDataMemberOrder; -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT + /// /// Gets or sets a value indicating whether System.Runtime.Serialization.DataMemberAttribute.Order should be started with 1 instead of 0. /// @@ -51,19 +55,19 @@ public bool OneBoundDataMemberOrder { get { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT return this._oneBoundDataMemberOrder; #else return Volatile.Read( ref this._oneBoundDataMemberOrder ); -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT } set { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT this._oneBoundDataMemberOrder = value; #else Volatile.Write( ref this._oneBoundDataMemberOrder, value ); -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT } } @@ -88,21 +92,21 @@ public PackerCompatibilityOptions PackerCompatibilityOptions set { Volatile.Write( ref this._packerCompatibilityOptions, ( int )value ); } } -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT private volatile bool _ignorePackabilityForCollection; #else private bool _ignorePackabilityForCollection; -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT /// /// Gets or sets a value indicating whether serializer generator ignores packability interfaces for collections or not. /// /// - /// true if serializer generator ignores packability interfaces for collections; otherwise, false. The default is true. + /// true if serializer generator ignores packability interfaces for collections; otherwise, false. The default is false. /// /// /// Historically, MessagePack for CLI ignored packability interfaces (, , - /// and ) for collection which implements (except and its kinds). + /// IAsyncPackable" and IAsyncUnpackable) for collection which implements (except and its kinds). /// As of 0.7, the generator respects such interfaces even if the target type is collection. /// Although this behavior is desirable and correct, setting this property true turn out the new behavior for backward compatibility. /// @@ -110,19 +114,95 @@ public bool IgnorePackabilityForCollection { get { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT return this._ignorePackabilityForCollection; #else return Volatile.Read( ref this._ignorePackabilityForCollection ); -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT } set { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT this._ignorePackabilityForCollection = value; #else Volatile.Write( ref this._ignorePackabilityForCollection, value ); -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT + } + } + +#if !FEATURE_CONCURRENT + private volatile bool _allowNonCollectionEnumerableTypes; +#else + private bool _allowNonCollectionEnumerableTypes; +#endif // !FEATURE_CONCURRENT + + /// + /// Gets or sets a value indicating whether the serializer generator should serialize types that implement IEnumerable but do not have an Add method. + /// + /// + /// true if serializer generator should serialize a type implementing IEnumerable as a normal type if a public Add method is not found; otherwise, false. The default is true. + /// + /// + /// Historically, MessagePack for CLI always tried to serialize any type that implemented IEnumerable as a collection, throwing an exception + /// if an Add method could not be found. However, for types that implement IEnumerable but don't have an Add method the generator will now + /// serialize the type as a non-collection type. To restore the old behavior for backwards compatibility, set this option to false. + /// + public bool AllowNonCollectionEnumerableTypes + { + get + { +#if !FEATURE_CONCURRENT + return this._allowNonCollectionEnumerableTypes; +#else + return Volatile.Read( ref this._allowNonCollectionEnumerableTypes ); +#endif // !FEATURE_CONCURRENT + } + set + { +#if !FEATURE_CONCURRENT + this._allowNonCollectionEnumerableTypes = value; +#else + Volatile.Write( ref this._allowNonCollectionEnumerableTypes, value ); +#endif // !FEATURE_CONCURRENT + } + } + + +#if !FEATURE_CONCURRENT + private volatile bool _allowAsymmetricSerializer; +#else + private bool _allowAsymmetricSerializer; +#endif // !FEATURE_CONCURRENT + + /// + /// Gets or sets a value indicating whether the serializer generator generates serializer types even when the generator determines that feature complete serializer cannot be generated due to lack of some requirement. + /// + /// + /// true if the serializer generator generates serializer types even when the generator determines that feature complete serializer cannot be generated due to lack of some requirement; otherwise, false. The default is false. + /// + /// + /// Currently, the lack of constructor (default or parameterized) or lack of settable members are considerd as "cannot generate feature complete serializer". + /// Therefore, you can get serialization only serializer if this property is set to true. + /// This is useful for logging, telemetry injestion, or so. + /// You can investigate serializer capability via property. + /// + public bool AllowAsymmetricSerializer + { + get + { +#if !FEATURE_CONCURRENT + return this._allowAsymmetricSerializer; +#else + return Volatile.Read( ref this._allowAsymmetricSerializer ); +#endif // !FEATURE_CONCURRENT + } + set + { +#if !FEATURE_CONCURRENT + this._allowAsymmetricSerializer = value; +#else + Volatile.Write( ref this._allowAsymmetricSerializer, value ); +#endif // !FEATURE_CONCURRENT } } @@ -132,6 +212,8 @@ internal SerializationCompatibilityOptions() { this.PackerCompatibilityOptions = PackerCompatibilityOptions.None; this.IgnorePackabilityForCollection = false; + this.AllowNonCollectionEnumerableTypes = true; + this.AllowAsymmetricSerializer = false; } } } diff --git a/src/MsgPack/Serialization/SerializationContext.cs b/src/MsgPack/Serialization/SerializationContext.cs index f4bd15e9b..0b78adec7 100644 --- a/src/MsgPack/Serialization/SerializationContext.cs +++ b/src/MsgPack/Serialization/SerializationContext.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,29 +20,28 @@ #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY -#define AOT #endif using System; #if !UNITY || MSGPACK_UNITY_FULL using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL -#if !SILVERLIGHT && !NETFX_35 && !UNITY +#if FEATURE_CONCURRENT using System.Collections.Concurrent; -#else // !SILVERLIGHT && !NETFX_35 && !UNITY +#else // !FEATURE_CONCURRENT using System.Collections.Generic; -#endif // !SILVERLIGHT && !NETFX_35 && !UNITY -#if CORE_CLR || UNITY +#endif // !SILVERLIGHT && !NET35 && !UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #if UNITY || NETSTANDARD1_1 || NETSTANDARD1_3 using System.Linq; #endif // UNITY || NETSTANDARD1_1 || NETSTANDARD1_3 -#if AOT +#if UNITY || WINDOWS_PHONE || WINDOWS_UWP using System.Reflection; -#endif // AOT +#endif // UNITY || WINDOWS_PHONE || WINDOWS_UWP using System.Threading; using MsgPack.Serialization.DefaultSerializers; @@ -58,13 +57,14 @@ namespace MsgPack.Serialization public sealed partial class SerializationContext { #if UNITY +#warning WORKAROUND private static readonly object DefaultContextSyncRoot = new object(); #endif // UNITY -#if AOT +#if UNITY || WINDOWS_PHONE || WINDOWS_UWP private static readonly MethodInfo GetSerializer1Method = typeof( SerializationContext ).GetRuntimeMethod( "GetSerializer", new[] { typeof( object ) } ); -#endif // AOT +#endif // UNITY || WINDOWS_PHONE || WINDOWS_UWP // Set SerializerRepository null because it requires SerializationContext, so re-init in constructor. @@ -109,14 +109,35 @@ public static SerializationContext Default } private readonly SerializerRepository _serializers; -#if SILVERLIGHT || NETFX_35 || UNITY +#if !FEATURE_CONCURRENT private readonly Dictionary _typeLock; #else private readonly ConcurrentDictionary _typeLock; -#endif // SILVERLIGHT || NETFX_35 || UNITY +#endif // !FEATURE_CONCURRENT private readonly object _generationLock; + private readonly BindingOptions _bindingOptions; + + /// + /// Gets the option settings for binding of type with serializer for field/property. + /// + /// + /// The option settings for binding of type's property/field in serializer generation. + /// This value will not be null. + /// + public BindingOptions BindingOptions + { + get + { +#if DEBUG + Contract.Ensures( Contract.Result() != null ); +#endif // DEBUG + + return this._bindingOptions; + } + } + /// /// Gets the current . /// @@ -176,6 +197,48 @@ public SerializationCompatibilityOptions CompatibilityOptions } } + private readonly DictionarySerializationOptions _dictionarySerializationOptions; + + /// + /// Gets the dictionary(map) based serialization options. + /// + /// + /// The which stores dictionary(map) based serialization options. This value will not be null. + /// + public DictionarySerializationOptions DictionarySerializationOptions + { + get + { +#if DEBUG + Contract.Ensures( Contract.Result() != null ); +#endif // DEBUG + + return this._dictionarySerializationOptions; + } + } + + /// + /// Gets the dictionary(map) based serialization options. + /// + /// + /// The which stores dictionary(map) based serialization options. This value will not be null. + /// + [Obsolete("Use DictionarySerializationOption instead.")] +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable(EditorBrowsableState.Never)] +#endif + public DictionarySerializationOptions DictionarySerlaizationOptions + { + get + { +#if DEBUG + Contract.Ensures( Contract.Result() != null ); +#endif // DEBUG + + return this._dictionarySerializationOptions; + } + } + private int _serializationMethod; /// @@ -216,7 +279,25 @@ public SerializationMethod SerializationMethod } } - private int _enumSerializationMethod; + private readonly EnumSerializationOptions _enumSerializationOptions; + + /// + /// Gets the enum serialization options. + /// + /// + /// The which stores enum serialization options. This value will not be null. + /// + public EnumSerializationOptions EnumSerializationOptions + { + get + { +#if DEBUG + Contract.Ensures( Contract.Result() != null ); +#endif // DEBUG + + return this._enumSerializationOptions; + } + } /// /// Gets or sets the to determine default serialization strategy of enum types. @@ -226,6 +307,7 @@ public SerializationMethod SerializationMethod /// /// The setting value is invalid as enum. /// + /// This property is wrapper for property. /// A serialization strategy for specific member is determined as following: /// /// If the member is marked with and its value is not , then it will be used. @@ -234,38 +316,14 @@ public SerializationMethod SerializationMethod /// /// Note that the default value of this property is , it is not size efficient but tolerant to unexpected enum definition change. /// + [Obsolete( "Use EnumSerializationOptions.SerializationMethod instead." )] public EnumSerializationMethod EnumSerializationMethod { - get - { -#if DEBUG - Contract.Ensures( Enum.IsDefined( typeof( EnumSerializationMethod ), Contract.Result() ) ); -#endif // DEBUG - - return ( EnumSerializationMethod )Volatile.Read( ref this._enumSerializationMethod ); - } - set - { - switch ( value ) - { - case EnumSerializationMethod.ByName: - case EnumSerializationMethod.ByUnderlyingValue: - { - break; - } - default: - { - throw new ArgumentOutOfRangeException( "value" ); - } - } - - Contract.EndContractBlock(); - - Volatile.Write( ref this._enumSerializationMethod, ( int )value ); - } + get { return this._enumSerializationOptions.SerializationMethod; } + set { this._enumSerializationOptions.SerializationMethod = value; } } -#if !AOT +#if !UNITY /// /// Gets or sets the to control code generation. @@ -274,6 +332,7 @@ public EnumSerializationMethod EnumSerializationMethod /// /// The . /// + [Obsolete( "Use SerializerOptions.GeneratorOption instead." )] public SerializationMethodGeneratorOption GeneratorOption { @@ -281,7 +340,7 @@ public SerializationMethodGeneratorOption GeneratorOption set { this._serializerGeneratorOptions.GeneratorOption = value; } } -#endif // !AOT +#endif // !UNITY private readonly DefaultConcreteTypeRepository _defaultCollectionTypes; @@ -296,24 +355,7 @@ public DefaultConcreteTypeRepository DefaultCollectionTypes get { return this._defaultCollectionTypes; } } -#if !AOT - - /// - /// Gets or sets a value indicating whether runtime generation is disabled or not. - /// - /// - /// true if runtime generation is disabled; otherwise, false. - /// - [Obsolete] - internal bool IsRuntimeGenerationDisabled - { - get { return this._serializerGeneratorOptions.IsRuntimeGenerationDisabled; } - set { this._serializerGeneratorOptions.IsRuntimeGenerationDisabled = value; } - } - -#endif // !AOT - - private int _defaultDateTimeConversionMethod; + private int _defaultDateTimeConversionMethod = ( int )DateTimeConversionMethod.Timestamp; /// /// Gets or sets the default conversion methods of built-in serializers. @@ -336,6 +378,7 @@ public DateTimeConversionMethod DefaultDateTimeConversionMethod { case DateTimeConversionMethod.Native: case DateTimeConversionMethod.UnixEpoc: + case DateTimeConversionMethod.Timestamp: { break; } @@ -352,6 +395,7 @@ public DateTimeConversionMethod DefaultDateTimeConversionMethod } #if UNITY +#warning WORKAROUND private readonly object _resolveSerializerSyncRoot = new object(); #endif // UNITY @@ -457,14 +501,26 @@ private MessagePackSerializer OnResolveSerializer( PolymorphismSchema sche } /// - /// Configures as new classic instance. + /// Configures as new classic instance as compatible for ver 0.5. /// /// The previously set context as . /// + [Obsolete( "Use ConfigureClassic(SerializationCompatibilityLevel) instead." )] public static SerializationContext ConfigureClassic() { + return ConfigureClassic( SerializationCompatibilityLevel.Version0_5 ); + } + + /// + /// Configures as new classic instance as compatible for sepcified version. + /// + /// A to specify compatibility level. + /// The previously set context as . + /// + public static SerializationContext ConfigureClassic(SerializationCompatibilityLevel compatibilityLevel) + { #if !UNITY - return Interlocked.Exchange( ref _default, CreateClassicContext() ); + return Interlocked.Exchange( ref _default, CreateClassicContext( compatibilityLevel) ); #else lock ( DefaultContextSyncRoot ) { @@ -481,34 +537,93 @@ public static SerializationContext ConfigureClassic() /// /// A new which is configured as same as 0.5. /// + [Obsolete( "Use CreateClassicContext(SerializationCompatibilityLevel) instead." )] + public static SerializationContext CreateClassicContext() + { + return CreateClassicContext( SerializationCompatibilityLevel.Version0_5 ); + } + + /// + /// Creates a new which is configured as compatible for the specified version. + /// + /// A to specify compatibility level. + /// + /// A new which is configured as compatible for the specified version. + /// /// - /// There are breaking changes of properties to improve API usability and to prevent accidental failure. - /// This method returns a which configured as classic style settings as follows: + /// + /// There are breaking changes of properties to improve API usability and to prevent accidental failure. + /// This method returns a which configured as classic style settings as follows: + /// /// /// /// - /// Default (as of 0.6) - /// Classic (before 0.6) + /// Latest (as of 0.6) + /// Version0_9 (as of 0.6) + /// Version0_5 (formally, "classic", before 0.6) /// /// - /// Packed object members order (if members are not marked with nor System.Runtime.Serialization.DataMemberAttribute and serializer uses ) - /// As declared (metadata table order) - /// As lexicographical - /// - /// - /// value + /// and value + /// value. /// Native representation (100-nano ticks, preserving .) /// UTC, milliseconds Unix epoc. /// + /// + /// Usage of ext types + /// Allowed + /// Allowed + /// Prohibited + /// + /// + /// Binary (such as Byte[]) representation + /// Bin types + /// Bin types + /// Raw types + /// + /// + /// Strings which lengthes are between 17 to 255 + /// Str8 type + /// Str8 types + /// Raw16 type + /// /// + /// + /// In short, prohibits deserialization error in legacy implementation + /// which do not recognize ext types, str8 type, and/or bin types. + /// prohibits only serialization for datetime + /// to keep compatibility for 0.9.x instead of maximize datetime serialization for modern implementations which uses msgpack timestamp type, + /// which is composite ext type, nano-second precision Unix epoc time. + /// /// - public static SerializationContext CreateClassicContext() + public static SerializationContext CreateClassicContext( SerializationCompatibilityLevel compatibilityLevel ) { - return - new SerializationContext( PackerCompatibilityOptions.Classic ) + switch ( compatibilityLevel ) + { + case SerializationCompatibilityLevel.Version0_5: { - DefaultDateTimeConversionMethod = DateTimeConversionMethod.UnixEpoc - }; + return + new SerializationContext( PackerCompatibilityOptions.Classic ) + { + DefaultDateTimeConversionMethod = DateTimeConversionMethod.UnixEpoc + }; + } + case SerializationCompatibilityLevel.Version0_9: + { + return + new SerializationContext( PackerCompatibilityOptions.None ) + { + DefaultDateTimeConversionMethod = DateTimeConversionMethod.Native + }; + } + case SerializationCompatibilityLevel.Latest: + { + return new SerializationContext( PackerCompatibilityOptions.None ); + } + default: + { + throw new ArgumentOutOfRangeException( "Unknown SerializationCompatibilityLevel value." ); + } + } } /// @@ -532,21 +647,24 @@ public SerializationContext( PackerCompatibilityOptions packerCompatibilityOptio this._serializers = new SerializerRepository( SerializerRepository.GetDefault( this ) ); -#if SILVERLIGHT || NETFX_35 || UNITY +#if !FEATURE_CONCURRENT this._typeLock = new Dictionary(); #else this._typeLock = new ConcurrentDictionary(); -#endif // SILVERLIGHT || NETFX_35 || UNITY +#endif // !FEATURE_CONCURRENT this._generationLock = new object(); this._defaultCollectionTypes = new DefaultConcreteTypeRepository(); this._serializerGeneratorOptions = new SerializerOptions(); + this._dictionarySerializationOptions = new DictionarySerializationOptions(); + this._enumSerializationOptions = new EnumSerializationOptions(); + this._bindingOptions = new BindingOptions(); } internal bool ContainsSerializer( Type rootType ) { return - this._serializers.Contains( rootType ) - || ( rootType.GetIsGenericType() && this._serializers.Contains( rootType.GetGenericTypeDefinition() ) ); + this._serializers.ContainsFor( rootType ) + || ( rootType.GetIsGenericType() && this._serializers.ContainsFor( rootType.GetGenericTypeDefinition() ) ); } /// @@ -601,7 +719,6 @@ public MessagePackSerializer GetSerializer( object providerParameter ) Contract.Ensures( Contract.Result>() != null ); #endif // DEBUG - var schema = providerParameter as PolymorphismSchema; // Explicitly generated serializer should always used, so get it first. MessagePackSerializer serializer = this._serializers.Get( this, providerParameter ); @@ -623,10 +740,10 @@ public MessagePackSerializer GetSerializer( object providerParameter ) try { - try {} + try { } finally { -#if SILVERLIGHT || NETFX_35 || UNITY +#if !FEATURE_CONCURRENT lock ( this._typeLock ) { var typeLock = new object(); @@ -641,33 +758,34 @@ public MessagePackSerializer GetSerializer( object providerParameter ) var typeLock = new object(); var aquiredTypeLock = this._typeLock.GetOrAdd( typeof( T ), _ => typeLock ); lockTaken = typeLock == aquiredTypeLock; -#endif // if SILVERLIGHT || NETFX_35 || UNITY +#endif // !FEATURE_CONCURRENT } if ( lockTaken ) { // First try to create generic serializer w/o code generation. + var schema = ( providerParameter ?? PolymorphismSchema.Create( typeof( T ), null ) ) as PolymorphismSchema; serializer = GenericSerializer.Create( this, schema ); if ( serializer == null ) { -#if !AOT - if ( this._serializerGeneratorOptions.IsRuntimeGenerationDisabled ) +#if !UNITY + if ( !this._serializerGeneratorOptions.CanRuntimeCodeGeneration ) { -#endif // AOT +#endif // !UNITY // On debugging, or AOT only envs, use reflection based aproach. serializer = this.GetSerializerWithoutGeneration( schema ) ?? this.OnResolveSerializer( schema ) ?? MessagePackSerializer.CreateReflectionInternal( this, this.EnsureConcreteTypeRegistered( typeof( T ) ), schema ); -#if !AOT +#if !UNITY } else { // This thread creating new type serializer. serializer = this.OnResolveSerializer( schema ) ?? MessagePackSerializer.CreateInternal( this, schema ); } -#endif // !AOT +#endif // !UNITY } } else @@ -739,7 +857,7 @@ out nullableSerializerProvider { if ( lockTaken ) { -#if SILVERLIGHT || NETFX_35 || UNITY +#if !FEATURE_CONCURRENT lock ( this._typeLock ) { this._typeLock.Remove( typeof( T ) ); @@ -747,7 +865,7 @@ out nullableSerializerProvider #else object dummy; this._typeLock.TryRemove( typeof( T ), out dummy ); -#endif // if SILVERLIGHT || NETFX_35 || UNITY +#endif // !FEATURE_CONCURRENT } } } @@ -875,26 +993,26 @@ public MessagePackSerializer GetSerializer( Type targetType, object providerPara Contract.Ensures( Contract.Result() != null ); #endif // DEBUG -#if DEBUG && UNITY +#if UNITY try { -#endif // DEBUG && UNITY - return SerializerGetter.Instance.Get( this, targetType, providerParameter ); -#if DEBUG && UNITY +#endif // UNITY + return SerializerGetter.Instance.Get( this, targetType, providerParameter ); +#if UNITY } catch ( Exception ex ) { AotHelper.HandleAotError( targetType, ex ); throw; } -#endif // DEBUG && UNITY +#endif // UNITY } private sealed class SerializerGetter { public static readonly SerializerGetter Instance = new SerializerGetter(); -#if !SILVERLIGHT && !NETFX_35 && !UNITY +#if FEATURE_CONCURRENT private readonly ConcurrentDictionary> _cache = new ConcurrentDictionary>(); #elif UNITY @@ -903,7 +1021,7 @@ private sealed class SerializerGetter #else private readonly Dictionary> _cache = new Dictionary>(); -#endif // !SILVERLIGHT && !NETFX_35 && !UNITY +#endif // FEATURE_CONCURRENT private SerializerGetter() { } @@ -920,10 +1038,10 @@ public MessagePackSerializer Get( SerializationContext context, Type targetType, return ( MessagePackSerializer )method.InvokePreservingExceptionType( context, providerParameter ); #else Func func; -#if SILVERLIGHT || NETFX_35 || UNITY +#if !FEATURE_CONCURRENT lock ( this._cache ) { -#endif // SILVERLIGHT || NETFX_35 || UNITY +#endif // !FEATURE_CONCURRENT if ( !this._cache.TryGetValue( targetType.TypeHandle, out func ) || func == null ) { #if !NETSTANDARD1_1 && !NETSTANDARD1_3 @@ -943,9 +1061,9 @@ public MessagePackSerializer Get( SerializationContext context, Type targetType, this._cache[ targetType.TypeHandle ] = func; } -#if SILVERLIGHT || NETFX_35 || UNITY +#if !FEATURE_CONCURRENT } -#endif // SILVERLIGHT || NETFX_35 || UNITY +#endif // !FEATURE_CONCURRENT return func( context, providerParameter ); #endif // UNITY } @@ -956,21 +1074,21 @@ public MessagePackSerializer Get( SerializationContext context, Type targetType, private static class SerializerGetter { private static readonly Func> _func = -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !WINDOWS_PHONE && !UNITY && !XAMARIN - Delegate.CreateDelegate( +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !WINDOWS_PHONE && !UNITY + Delegate.CreateDelegate( typeof( Func> ), Metadata._SerializationContext.GetSerializer1_Parameter_Method.MakeGenericMethod( typeof( T ) ) ) as Func>; #else -#if !AOT +#if !UNITY && !WINDOWS_PHONE && !WINDOWS_UWP Metadata._SerializationContext.GetSerializer1_Parameter_Method -#else +#else // !UNITY && !WINDOWS_PHONE && !WINDOWS_UWP GetSerializer1Method -#endif // !AOT +#endif // !UNITY && !WINDOWS_PHONE && !WINDOWS_UWP .MakeGenericMethod( typeof( T ) ).CreateDelegate( typeof( Func> ) ) as Func>; -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !WINDOWS_PHONE && !UNITY && !XAMARIN +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !WINDOWS_PHONE && !UNITY // ReSharper disable UnusedMember.Local // This method is invoked via Reflection on SerializerGetter.Get(). @@ -980,6 +1098,6 @@ public static MessagePackSerializer Get( SerializationContext context, object pr } // ReSharper restore UnusedMember.Local } -#endif // !UNITY +#endif // !UNITY && !UNITY } } diff --git a/src/MsgPack/Serialization/SerializationExceptions.cs b/src/MsgPack/Serialization/SerializationExceptions.cs index d9ae1e40d..e60e686ad 100644 --- a/src/MsgPack/Serialization/SerializationExceptions.cs +++ b/src/MsgPack/Serialization/SerializationExceptions.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,11 +27,11 @@ #if !UNITY || MSGPACK_UNITY_FULL using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; #if !UNITY using System.Reflection; @@ -53,7 +53,7 @@ namespace MsgPack.Serialization public static class SerializationExceptions { #if !AOT - internal static readonly MethodInfo ThrowValueTypeCannotBeNull3Method = FromExpression.ToMethod( ( string name, Type memberType, Type declaringType ) => ThrowValueTypeCannotBeNull( name, memberType, declaringType ) ); + internal static readonly MethodInfo ThrowValueTypeCannotBeNull3Method = typeof( SerializationExceptions ).GetMethod( nameof( ThrowValueTypeCannotBeNull ), new[] { typeof( string ), typeof( Type ), typeof( Type ) } ); #endif // !AOT /// @@ -445,7 +445,7 @@ public static Exception NewMissingAddMethod( Type type ) #if !AOT internal static readonly MethodInfo ThrowIsNotArrayHeaderMethod = - FromExpression.ToMethod( ( Unpacker unpacker ) => ThrowIsNotArrayHeader( unpacker ) ); + typeof( SerializationExceptions ).GetMethod( nameof( ThrowIsNotArrayHeader ), new[] { typeof( Unpacker ) } ); #endif // !AOT /// @@ -501,7 +501,7 @@ public static void ThrowIsNotArrayHeader( Unpacker unpacker ) #if !AOT internal static readonly MethodInfo ThrowIsNotMapHeaderMethod = - FromExpression.ToMethod( ( Unpacker unpacker ) => ThrowIsNotMapHeader( unpacker ) ); + typeof( SerializationExceptions ).GetMethod( nameof( ThrowIsNotMapHeader ), new[] { typeof( Unpacker ) } ); #endif // !AOT /// @@ -582,10 +582,7 @@ public static Exception NewNotSupportedBecauseCannotInstanciateAbstractType( Typ /// /// internal static readonly MethodInfo ThrowTupleCardinarityIsNotMatchMethod = - FromExpression.ToMethod( - ( int expectedTupleCardinality, long actualArrayLength, Unpacker unpacker ) => - ThrowTupleCardinarityIsNotMatch( expectedTupleCardinality, actualArrayLength, unpacker ) - ); + typeof( SerializationExceptions ).GetMethod( nameof( ThrowTupleCardinarityIsNotMatch ), new[] { typeof( int ), typeof( long ), typeof( Unpacker ) } ); #endif // !AOT /// @@ -713,7 +710,7 @@ internal static void ThrowIsTooLargeCollection() } #if !AOT - internal static readonly MethodInfo ThrowNullIsProhibitedMethod = FromExpression.ToMethod( ( string memberName ) => ThrowNullIsProhibited( memberName ) ); + internal static readonly MethodInfo ThrowNullIsProhibitedMethod = typeof( SerializationExceptions ).GetMethod( nameof( ThrowNullIsProhibited ), new[] { typeof( string ) } ); #endif // !AOT /// @@ -824,6 +821,47 @@ internal static void ThrowFailedToDeserializeMember( Type targetType, string mem throw NewFailedToDeserializeMember( targetType, memberName, inner ); } +#if !AOT + /// + /// + /// + internal static readonly MethodInfo NewUnpackFromIsNotSupportedMethod = + typeof( SerializationExceptions ).GetMethod( nameof( NewUnpackFromIsNotSupported ), new[] { typeof( Type ) } ); +#endif // !AOT + + /// + /// Returns a new exception which represents UnpackFrom is not supported in this asymmetric serializer. + /// + /// Deserializing type. + /// The exception. This value will not be null. + public static Exception NewUnpackFromIsNotSupported( Type targetType ) + { +#if DEBUG + Contract.Requires( targetType != null ); +#endif // DEBUG + return new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "This operation is not supported for '{0}' because the serializer does not support UnpackFrom method.", targetType ) ); + } + +#if !AOT + /// + /// + /// + internal static readonly MethodInfo NewCreateInstanceIsNotSupportedMethod = + typeof( SerializationExceptions ).GetMethod( nameof( NewCreateInstanceIsNotSupported ), new[] { typeof( Type ) } ); +#endif // !AOT + + /// + /// Returns a new exception which represents UnpackFrom is not supported in this asymmetric serializer. + /// + /// Deserializing type. + /// The exception. This value will not be null. + public static Exception NewCreateInstanceIsNotSupported( Type targetType ) + { +#if DEBUG + Contract.Requires( targetType != null ); +#endif // DEBUG + return new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "This operation is not supported for '{0}' because the serializer does not support CreateInstance method.", targetType ) ); + } internal static Exception NewUnpackToIsNotSupported( Type type, Exception inner ) { @@ -866,11 +904,21 @@ internal static void ThrowArgumentNullException( string parameterName ) throw new ArgumentNullException( parameterName ); } + internal static void ThrowArgumentNullException( string parameterName, string fieldName ) + { + throw new ArgumentNullException( parameterName, String.Format( CultureInfo.CurrentCulture, "Field '{0}' of parameter '{1}' cannot be null.", fieldName, parameterName ) ); + } + internal static void ThrowArgumentCannotBeNegativeException( string parameterName ) { throw new ArgumentOutOfRangeException( parameterName, "The value cannot be negative number." ); } + internal static void ThrowArgumentCannotBeNegativeException( string parameterName, string fieldName ) + { + throw new ArgumentOutOfRangeException( parameterName, String.Format( CultureInfo.CurrentCulture, "Field '{0}' of parameter '{1}' cannot be negative number.", fieldName, parameterName ) ); + } + internal static void ThrowArgumentException( string parameterName, string message ) { throw new ArgumentException( message, parameterName ); @@ -886,7 +934,12 @@ internal static void ThrowSerializationException( string message, Exception inne throw new SerializationException( message, innerException ); } - internal static void ThrowInvalidArrayItemsCount( Unpacker unpacker, Type targetType, int requiredCount ) +#if UNITY && DEBUG + public +#else + internal +#endif + static void ThrowInvalidArrayItemsCount( Unpacker unpacker, Type targetType, int requiredCount ) { throw unpacker.IsCollectionHeader diff --git a/src/MsgPack/Serialization/SerializationTarget.cs b/src/MsgPack/Serialization/SerializationTarget.cs index f093a47f8..8efe8ab1b 100644 --- a/src/MsgPack/Serialization/SerializationTarget.cs +++ b/src/MsgPack/Serialization/SerializationTarget.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2014-2016 FUJIWARA, Yusuke +// Copyright (C) 2014-2018 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,21 +20,22 @@ // Takeshi KIRIYA // Odyth // Roman-Blinkov +// Samuel Cragg // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY -#define AOT #endif using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +using System.Diagnostics; +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; using System.Reflection; @@ -47,30 +48,110 @@ namespace MsgPack.Serialization /// /// Implements serialization target member extraction logics. /// - internal class SerializationTarget +#if UNITY && DEBUG + public +#else + internal +#endif + class SerializationTarget { + // Type names to avoid user who doesn't embed "message pack assembly's attributes" in their code directly. + private static readonly string MessagePackMemberAttributeTypeName = typeof( MessagePackMemberAttribute ).FullName; + private static readonly string MessagePackIgnoreAttributeTypeName = typeof( MessagePackIgnoreAttribute ).FullName; + private static readonly string MessagePackDeserializationConstructorAttributeTypeName = typeof( MessagePackDeserializationConstructorAttribute ).FullName; + private static readonly string[] EmptyStrings = new string[ 0 ]; + private static readonly SerializingMember[] EmptyMembers = new SerializingMember[ 0 ]; + private static readonly Assembly ThisAssembly = typeof( SerializationTarget ).GetAssembly(); + public IList Members { get; private set; } + public ConstructorInfo DeserializationConstructor { get; private set; } - public bool IsConstructorDeserialization - { - get { return this.DeserializationConstructor != null && this.DeserializationConstructor.GetParameters().Length > 0; } - } - private SerializationTarget( IList members, ConstructorInfo constructor ) + private readonly string[] _correspondingMemberNames; + + public bool IsConstructorDeserialization { get; private set; } + + public bool CanDeserialize { get; private set; } + + private SerializationTarget( IList members, ConstructorInfo constructor, string[] correspondingMemberNames, bool canDeserialize ) { + Trace( "SerializationTarget::ctor(canDeserialize: {0})", canDeserialize ); this.Members = members; this.DeserializationConstructor = constructor; + this.IsConstructorDeserialization = constructor != null && constructor.GetParameters().Any(); + this.CanDeserialize = canDeserialize; + this._correspondingMemberNames = correspondingMemberNames ?? EmptyStrings; + } + + public SerializerCapabilities GetCapabilitiesForObject() + { + return this.CanDeserialize ? ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) : SerializerCapabilities.PackTo; } - public string FindCorrespondingMemberName( ParameterInfo parameterInfo ) + public SerializerCapabilities GetCapabilitiesForCollection( CollectionTraits traits ) { return - this.Members.Where( - item => - parameterInfo.Name.Equals( item.Contract.Name, StringComparison.OrdinalIgnoreCase ) && - item.Member.GetMemberValueType() == parameterInfo.ParameterType - ).Select( item => item.Contract.Name ) - .FirstOrDefault(); + !this.CanDeserialize + ? SerializerCapabilities.PackTo + : traits.AddMethod == null + ? ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) + : ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ); + } + + private static string[] FindCorrespondingMemberNames( IList members, ConstructorInfo constructor ) + { + if ( constructor == null ) + { + return null; + } + + var constructorParameters = constructor.GetParameters(); + return + constructorParameters.GroupJoin( + members, + p => new KeyValuePair( p.Name, p.ParameterType ), + m => new KeyValuePair( m.Contract.Name, m.Member == null ? null : m.Member.GetMemberValueType() ), + ( p, ms ) => DetermineCorrespondingMemberName( p, ms ), + MemberConstructorParameterEqualityComparer.Instance + ).ToArray(); + } + + private static string DetermineCorrespondingMemberName( ParameterInfo parameterInfo, IEnumerable members ) + { + var membersArray = members.ToArray(); + switch ( membersArray.Length ) + { + case 0: + { + return null; + } + case 1: + { + return membersArray[ 0 ].MemberName; + } + default: + { + ThrowAmbigiousMatchException( parameterInfo, membersArray ); + return null; + } + } + } + + private static void ThrowAmbigiousMatchException( ParameterInfo parameterInfo, ICollection members ) + { + throw new AmbiguousMatchException( + String.Format( + CultureInfo.CurrentCulture, + "There are multiple candiates for corresponding member for parameter '{0}' of constructor. [{1}]", + parameterInfo, + String.Join( ", ", members.Select( x => x.ToString() ).ToArray() ) + ) + ); + } + + public string GetCorrespondingMemberName( int constructorParameterIndex ) + { + return this._correspondingMemberNames[ constructorParameterIndex ]; } public static void VerifyType( Type targetType ) @@ -81,43 +162,177 @@ public static void VerifyType( Type targetType ) } } - public static SerializationTarget Prepare( SerializationContext context, Type targetType ) + public static void VerifyCanSerializeTargetType( SerializationContext context, Type targetType ) { - var getters = GetTargetMembers( targetType ).OrderBy( entry => entry.Contract.Id ).ToArray(); + if ( context.SerializerOptions.DisablePrivilegedAccess && !targetType.GetIsPublic() && !targetType.GetIsNestedPublic() && !ThisAssembly.Equals( targetType.GetAssembly() ) ) + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it is not public to the serializer.", targetType ) ); + } + } - if ( getters.Length == 0 ) + public static SerializationTarget Prepare( SerializationContext context, Type targetType ) + { + VerifyCanSerializeTargetType( context, targetType ); + + IEnumerable memberIgnoreList = context.BindingOptions.GetIgnoringMembers( targetType ); + var getters = GetTargetMembers( targetType ) + .Where( getter => !memberIgnoreList.Contains( getter.MemberName, StringComparer.Ordinal ) ) + .OrderBy( entry => entry.Contract.Id ) + .ToArray(); + + if ( getters.Length == 0 + && !typeof( IPackable ).IsAssignableFrom( targetType ) + && !typeof( IUnpackable ).IsAssignableFrom( targetType ) +#if FEATURE_TAP + && ( context.SerializerOptions.WithAsync + && ( !typeof( IAsyncPackable ).IsAssignableFrom( targetType ) + && !typeof( IAsyncUnpackable ).IsAssignableFrom( targetType ) + ) + ) +#endif // FEATURE_TAP + ) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it does not have any serializable fields nor properties.", targetType ) ); } - var memberCandidates = getters.Where( entry => CheckTargetEligibility( entry.Member ) ).ToArray(); + var memberCandidates = getters.Where( entry => CheckTargetEligibility( context, entry.Member ) ).ToArray(); - if ( memberCandidates.Length == 0 ) + if ( memberCandidates.Length == 0 && !context.CompatibilityOptions.AllowAsymmetricSerializer ) { - var constructor = FindDeserializationConstructor( targetType ); - return new SerializationTarget( ComplementMembers( getters, context, targetType ), constructor ); + ConstructorKind constructorKind; + var deserializationConstructor = FindDeserializationConstructor( context, targetType, out constructorKind ); + var complementedMembers = ComplementMembers( getters, context, targetType ); + var correspondingMemberNames = FindCorrespondingMemberNames( complementedMembers, deserializationConstructor ); + return + new SerializationTarget( + complementedMembers, + deserializationConstructor, + correspondingMemberNames, + DetermineCanDeserialize( constructorKind, context, targetType, correspondingMemberNames, allowDefault: false ) + ); } - - var defaultConstructor = targetType.GetConstructor( ReflectionAbstractions.EmptyTypes ); - if ( defaultConstructor == null && !targetType.GetIsValueType() ) + else { - throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructor( targetType ); + bool? canDeserialize; + ConstructorKind constructorKind; + + // Try to get default constructor. + var constructor = targetType.GetConstructor( ReflectionAbstractions.EmptyTypes ); + if ( constructor == null && !targetType.GetIsValueType() ) + { + // Try to get deserialization constructor. + var deserializationConstructor = FindDeserializationConstructor( context, targetType, out constructorKind ); + if ( deserializationConstructor == null && !context.CompatibilityOptions.AllowAsymmetricSerializer ) + { + throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructor( targetType ); + } + + constructor = deserializationConstructor; + canDeserialize = null; + } + else if ( memberCandidates.Length == 0 ) + { +#if DEBUG + Contract.Assert( context.CompatibilityOptions.AllowAsymmetricSerializer ); +#endif // DEBUG + // Absolutely cannot deserialize in this case. + canDeserialize = false; + constructorKind = ConstructorKind.Ambiguous; + } + else + { + constructorKind = ConstructorKind.Default; + // Let's prefer annotated constructor here. + var markedConstructors = FindExplicitDeserializationConstructors( targetType.GetConstructors() ); + if ( markedConstructors.Count == 1 ) + { + // For backward compatibility, no exceptions are thrown here even if mulitiple deserialization constructor attributes in the type + // just use default constructor for it. + constructor = markedConstructors[ 0 ]; + constructorKind = ConstructorKind.Marked; + } + + // OK, appropriate constructor and setters are found. + canDeserialize = true; + } + + if ( constructor != null && constructor.GetParameters().Any() || context.CompatibilityOptions.AllowAsymmetricSerializer ) + { + // Recalculate members because getter-only/readonly members should be included for constructor deserialization. + memberCandidates = getters; + } + + // Because members' order is equal to declared order is NOT guaranteed, so explicit ordering is required. + IList members; + if ( memberCandidates.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) ) + { + // Alphabetical order. + members = memberCandidates.OrderBy( item => item.Contract.Name ).ToArray(); + } + else + { + // ID order. + members = ComplementMembers( memberCandidates, context, targetType ); + } + + var correspondingMemberNames = FindCorrespondingMemberNames( members, constructor ); + return + new SerializationTarget( + members, + constructor, + correspondingMemberNames, + canDeserialize ?? DetermineCanDeserialize( constructorKind, context, targetType, correspondingMemberNames, allowDefault: true ) + ); } + } + + private static bool HasAnyCorrespondingMembers( IEnumerable correspondingMemberNames ) + { + return correspondingMemberNames.Count( x => !String.IsNullOrEmpty( x ) ) > 0; + } - // Because members' order is equal to declared order is NOT guaranteed, so explicit ordering is required. - IList members; - if ( memberCandidates.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) ) + private static bool HasUnpackableInterface( Type targetType, SerializationContext context ) + { + return + typeof( IUnpackable ).IsAssignableFrom( targetType ) +#if FEATURE_TAP + && ( !context.SerializerOptions.WithAsync || typeof( IAsyncUnpackable ).IsAssignableFrom( targetType ) ) +#endif // FEATURE_TAP + ; + } + + private static bool DetermineCanDeserialize( ConstructorKind kind, SerializationContext context, Type targetType, IEnumerable correspondingMemberNames, bool allowDefault ) + { + if ( HasUnpackableInterface( targetType, context ) ) { - // Alphabetical order. - members = memberCandidates.OrderBy( item => item.Contract.Name ).ToArray(); + Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> true: HasUnpackableInterface", targetType, kind ); + return true; } - else + + switch ( kind ) { - // ID order. - members = ComplementMembers( memberCandidates, context, targetType ); + case ConstructorKind.Marked: + { + Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> true: Marked", targetType, kind ); + return true; + } + case ConstructorKind.Parameterful: + { + var result = HasAnyCorrespondingMembers( correspondingMemberNames ); + Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> {2}: HasAnyCorrespondingMembers", targetType, kind, result ); + return result; + } + case ConstructorKind.Default: + { + Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> {2}: Default", targetType, kind, allowDefault ); + return allowDefault; + } + default: + { + Contract.Assert( kind == ConstructorKind.None || kind == ConstructorKind.Ambiguous, "kind == ConstructorKind.None || kind == ConstructorKind.Ambiguous : " + kind ); + return false; + } } - - return new SerializationTarget( members, defaultConstructor ); } private static MemberInfo[] GetDistinctMembers( Type type ) @@ -126,12 +341,12 @@ private static MemberInfo[] GetDistinctMembers( Type type ) var returningMemberNamesSet = new HashSet(); while ( type != typeof( object ) && type != null ) { - var members = + var members = #if !NETSTANDARD1_1 && !NETSTANDARD1_3 - type.FindMembers( - MemberTypes.Field | MemberTypes.Property, + type.FindMembers( + MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, - null, + null, null ); #else @@ -152,20 +367,33 @@ private static MemberInfo[] GetDistinctMembers( Type type ) return distinctMembers.ToArray(); } - private static IEnumerable GetTargetMembers(Type type) + private static IEnumerable GetTargetMembers( Type type ) { Contract.Assert( type != null, "type != null" ); var members = GetDistinctMembers( type ); - var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray(); + var filtered = members.Where( item => +#if !UNITY + item.GetCustomAttributesData().Any( a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName ) +#else + item.GetCustomAttributes( typeof( MessagePackMemberAttribute ), true ).Any() +#endif // !UNITY + ).ToArray(); if ( filtered.Length > 0 ) { return GetAnnotatedMembersWithDuplicationDetection( type, filtered ); } - if ( type.GetCustomAttributesData().Any( attr => - attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) ) + if ( +#if !UNITY + type.GetCustomAttributesData().Any( attr => + attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) +#else + type.GetCustomAttributes( true ).Any( attr => + attr.GetType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) +#endif // !UNITY + ) { return GetSystemRuntimeSerializationCompatibleMembers( members ); } @@ -177,7 +405,11 @@ private static IEnumerable GetAnnotatedMembersWithDuplication { var duplicated = filtered.FirstOrDefault( - member => member.IsDefined( typeof( MessagePackIgnoreAttribute ) ) +#if !UNITY + member => member.GetCustomAttributesData().Any( a => a.GetAttributeType().FullName == MessagePackIgnoreAttributeTypeName ) +#else + member => member.GetCustomAttributes( typeof( MessagePackIgnoreAttribute ), true ).Any() +#endif // !UNITY ); if ( duplicated != null ) @@ -195,13 +427,73 @@ private static IEnumerable GetAnnotatedMembersWithDuplication return filtered.Select( member => - new SerializingMember( - member, - new DataMemberContract( member, member.GetCustomAttribute() ) - ) - ); + { +#if !UNITY + var attribute = member.GetCustomAttributesData().Single( a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName ); + return + new SerializingMember( + member, + new DataMemberContract( + member, + ( string )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "Name" ), +#if !SILVERLIGHT + ( NilImplication )( ( int? )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "NilImplication" ) ).GetValueOrDefault(), + ( int? )GetAttributeArgument( MessagePackMemberAttributeTypeName, attribute, 0 ) +#else + ( NilImplication )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "NilImplication" ), + ( int? )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "Id" ) +#endif // !SILVERLIGHT + ) + ); +#else + var attribute = member.GetCustomAttributes( typeof( MessagePackMemberAttribute ), true ).Single() as MessagePackMemberAttribute; + return + new SerializingMember( + member, + new DataMemberContract( + member, + attribute.Name, + attribute.NilImplication, + attribute.Id + ) + ); +#endif // !UNITY + } + ); } +#if !UNITY +#if !SILVERLIGHT + private static object GetAttributeArgument( string attributeName, CustomAttributeData attribute, int index ) + { + var arguments = attribute.GetConstructorArguments(); + if ( arguments.Count < index ) + { + // Use default. + return null; + } + + return arguments[ index ].Value; + } +#endif // !SILVERLIGHT + +#if !SILVERLIGHT + private static object GetAttributeProperty( string attributeName, CustomAttributeData attribute, string propertyName ) +#else + private static object GetAttributeProperty( string attributeName, Attribute attribute, string propertyName ) +#endif // !SILVERLIGHT + { + var property = attribute.GetNamedArguments().SingleOrDefault( a => a.GetMemberName() == propertyName ); + if ( property.GetMemberName() == null ) + { + // Use default. + return null; + } + + return property.GetTypedValue().Value; + } +#endif // !UNITY + private static IEnumerable GetSystemRuntimeSerializationCompatibleMembers( MemberInfo[] members ) { return @@ -211,15 +503,23 @@ private static IEnumerable GetSystemRuntimeSerializationCompa { member = item, data = +#if !UNITY item.GetCustomAttributesData() .FirstOrDefault( data => data.GetAttributeType().FullName == "System.Runtime.Serialization.DataMemberAttribute" ) +#else + item.GetCustomAttributes( true ) + .FirstOrDefault( + data => data.GetType().FullName == "System.Runtime.Serialization.DataMemberAttribute" + ) +#endif // !UNITY } ).Where( item => item.data != null ) .Select( item => { +#if !UNITY var name = item.data.GetNamedArguments() .Where( arg => arg.GetMemberName() == "Name" ) @@ -228,29 +528,57 @@ private static IEnumerable GetSystemRuntimeSerializationCompa var id = item.data.GetNamedArguments() .Where( arg => arg.GetMemberName() == "Order" ) -#if !UNITY .Select( arg => ( int? )arg.GetTypedValue().Value ) -#else - .Select( arg => arg.GetTypedValue().Value ) -#endif .FirstOrDefault(); -#if SILVERLIGHT if ( id == -1 ) { - // Shim for Silverlight returns -1 because GetNamedArguments() extension method cannot recognize whether the argument was actually specified or not. id = null; } -#endif // SILVERLIGHT return new SerializingMember( item.member, -#if !UNITY new DataMemberContract( item.member, name, NilImplication.MemberDefault, id ) + ); #else - new DataMemberContract( item.member, name, NilImplication.MemberDefault, ( int? )id ) -#endif // !UNITY + var nameProperty = item.data.GetType().GetProperty( "Name" ); + var orderProperty = item.data.GetType().GetProperty( "Order" ); + + if ( nameProperty == null || !nameProperty.CanRead || nameProperty.GetGetMethod().GetParameters().Length > 0 ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Failed to get Name property from {0} type.", + item.data.GetType().AssemblyQualifiedName + ) + ); + } + + if( orderProperty == null || !orderProperty.CanRead || orderProperty.GetGetMethod().GetParameters().Length > 0 ) + { + throw new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Failed to get Order property from {0} type.", + item.data.GetType().AssemblyQualifiedName + ) ); + } + + var name = ( string )nameProperty.GetValue( item.data, null ); + var id = ( int? )orderProperty.GetValue( item.data, null ); + if ( id == -1 ) + { + id = null; + } + + return + new SerializingMember( + item.member, + new DataMemberContract( item.member, name, NilImplication.MemberDefault, id ) + ); +#endif // !UNITY } ); } @@ -260,29 +588,53 @@ private static IEnumerable GetPublicUnpreventedMembers( Membe return members.Where( member => member.GetIsPublic() - && !member.GetCustomAttributesData() + && !member +#if !UNITY + .GetCustomAttributesData() .Select( data => data.GetAttributeType().FullName ) +#else + .GetCustomAttributes( true ) + .Select( data => data.GetType().FullName ) +#endif // !UNITY .Any( attr => attr == "MsgPack.Serialization.MessagePackIgnoreAttribute" - || attr == "System.NonSerializedAttribute" || attr == "System.Runtime.Serialization.IgnoreDataMemberAttribute" ) + && !IsNonSerializedField( member ) ).Select( member => new SerializingMember( member, new DataMemberContract( member ) ) ); } + private static bool IsNonSerializedField( MemberInfo member ) + { + var asField = member as FieldInfo; + if ( asField == null ) + { + return false; + } + + return ( asField.Attributes & FieldAttributes.NotSerialized ) != 0; + } - private static ConstructorInfo FindDeserializationConstructor( Type targetType ) + private static ConstructorInfo FindDeserializationConstructor( SerializationContext context, Type targetType, out ConstructorKind constructorKind ) { var constructors = targetType.GetConstructors().ToArray(); if ( constructors.Length == 0 ) { - throw NewTypeCannotBeSerializedException( targetType ); + if ( context.CompatibilityOptions.AllowAsymmetricSerializer ) + { + constructorKind = ConstructorKind.None; + return null; + } + else + { + throw NewTypeCannotBeSerializedException( targetType ); + } } // The marked construtor is always preferred. - var markedConstructors = constructors.Where( ctor => ctor.IsDefined( typeof( MessagePackDeserializationConstructorAttribute ) ) ).ToArray(); - switch ( markedConstructors.Length ) + var markedConstructors = FindExplicitDeserializationConstructors( constructors ); + switch ( markedConstructors.Count ) { case 0: { @@ -290,7 +642,8 @@ private static ConstructorInfo FindDeserializationConstructor( Type targetType ) } case 1: { - // OK Use it + // OK use it for deserialization. + constructorKind = ConstructorKind.Marked; return markedConstructors[ 0 ]; } default: @@ -308,22 +661,40 @@ private static ConstructorInfo FindDeserializationConstructor( Type targetType ) // A constructor which has most parameters will be used. var mostRichConstructors = constructors.GroupBy( ctor => ctor.GetParameters().Length ).OrderByDescending( g => g.Key ).First().ToArray(); +#if DEBUG + Trace( "SerializationTarget::FindDeserializationConstructor.MostRich({0}) -> {1}", targetType, String.Join( ";", mostRichConstructors.Select( x => x.ToString() ).ToArray() ) ); +#endif // DEBUG switch ( mostRichConstructors.Length ) { case 1: { if ( mostRichConstructors[ 0 ].GetParameters().Length == 0 ) { - throw NewTypeCannotBeSerializedException( targetType ); + if ( context.CompatibilityOptions.AllowAsymmetricSerializer ) + { + constructorKind = ConstructorKind.Default; + return mostRichConstructors[ 0 ]; + } + else + { + throw NewTypeCannotBeSerializedException( targetType ); + } } - // OK Use it + // OK try use it but it may not handle deserialization correctly. + constructorKind = ConstructorKind.Parameterful; return mostRichConstructors[ 0 ]; } default: { - throw - new SerializationException( + if ( context.CompatibilityOptions.AllowAsymmetricSerializer ) + { + constructorKind = ConstructorKind.Ambiguous; + return null; + } + else + { + throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it does not have any serializable fields nor properties, and serializer generator failed to determine constructor to deserialize among({1}).", @@ -331,23 +702,42 @@ private static ConstructorInfo FindDeserializationConstructor( Type targetType ) String.Join( ", ", mostRichConstructors.Select( ctor => ctor.ToString() ).ToArray() ) ) ); + } } } } + private static IList FindExplicitDeserializationConstructors( IEnumerable construtors ) + { + return + construtors + .Where( ctor => +#if !UNITY + ctor.GetCustomAttributesData().Any( a => + a.GetAttributeType().FullName +#else + ctor.GetCustomAttributes( true ).Any( a => + a.GetType().FullName +#endif // !UNITY + == MessagePackDeserializationConstructorAttributeTypeName + ) + ).ToArray(); + } + private static SerializationException NewTypeCannotBeSerializedException( Type targetType ) { - return new SerializationException( - String.Format( - CultureInfo.CurrentCulture, - "Cannot serialize type '{0}' because it does not have any serializable fields nor properties, and it does not have any public constructors with parameters.", - targetType + return + new SerializationException( + String.Format( + CultureInfo.CurrentCulture, + "Cannot serialize type '{0}' because it does not have any serializable fields nor properties, and it does not have any public constructors with parameters.", + targetType ) ); } - private static bool CheckTargetEligibility( MemberInfo member ) + private static bool CheckTargetEligibility( SerializationContext context, MemberInfo member ) { var asProperty = member as PropertyInfo; var asField = member as FieldInfo; @@ -362,12 +752,22 @@ private static bool CheckTargetEligibility( MemberInfo member ) } #if !NETSTANDARD1_1 && !NETSTANDARD1_3 - if ( asProperty.GetSetMethod( true ) != null ) + var setter = asProperty.GetSetMethod( true ); #else - if ( asProperty.SetMethod != null ) + var setter = asProperty.SetMethod; #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + if ( setter != null ) { - return true; + if ( setter.GetIsPublic() ) + { + return true; + } + + if ( !context.SerializerOptions.DisablePrivilegedAccess ) + { + // Can deserialize non-public setter if privileged. + return true; + } } returnType = asProperty.PropertyType; @@ -383,10 +783,14 @@ private static bool CheckTargetEligibility( MemberInfo member ) } else { +#if DEBUG + Contract.Assert( false, "Unknown type member " + member ); +#endif // DEBUG + // ReSharper disable once HeuristicUnreachableCode return true; } - var traits = returnType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod ); + var traits = returnType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod, allowNonCollectionEnumerableTypes: false ); switch ( traits.CollectionType ) { case CollectionKind.Array: @@ -403,6 +807,11 @@ private static bool CheckTargetEligibility( MemberInfo member ) private static IList ComplementMembers( IList candidates, SerializationContext context, Type targetType ) { + if ( candidates.Count == 0 ) + { + return candidates; + } + if ( candidates[ 0 ].Contract.Id < 0 ) { return candidates; @@ -411,7 +820,8 @@ private static IList ComplementMembers( IList result ) } } -#if !NETFX_35 + public static SerializationTarget CreateForCollection( ConstructorInfo collectionConstructor, bool canDeserialize ) + { + return new SerializationTarget( EmptyMembers, collectionConstructor, EmptyStrings, canDeserialize ); + } + +#if !NET35 public static SerializationTarget CreateForTuple( IList itemTypes ) { - return new SerializationTarget( itemTypes.Select( ( _, i ) => new SerializingMember( GetTupleItemNameFromIndex( i ) ) ).ToArray(), null ); + return new SerializationTarget( itemTypes.Select( ( _, i ) => new SerializingMember( GetTupleItemNameFromIndex( i ) ) ).ToArray(), null, null, true ); } public static string GetTupleItemNameFromIndex( int i ) { return "Item" + ( i + 1 ).ToString( "D", CultureInfo.InvariantCulture ); } -#endif // !NETFX_35 +#endif // !NET35 -#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !AOT +#if FEATURE_CODEGEN public static bool BuiltInSerializerExists( ISerializerGeneratorConfiguration configuration, Type type, CollectionTraits traits ) { - return GenericSerializer.IsSupported( type, traits, configuration.PreferReflectionBasedSerializer ) || SerializerRepository.InternalDefault.Contains( type ); + return GenericSerializer.IsSupported( type, traits, configuration.PreferReflectionBasedSerializer ) || SerializerRepository.InternalDefault.ContainsFor( type ); + } +#endif // FEATURE_CODEGEN + + private sealed class MemberConstructorParameterEqualityComparer : EqualityComparer> + { + public static readonly IEqualityComparer> Instance = new MemberConstructorParameterEqualityComparer(); + + private MemberConstructorParameterEqualityComparer() { } + + public override bool Equals( KeyValuePair x, KeyValuePair y ) + { + return String.Equals( x.Key, y.Key, StringComparison.OrdinalIgnoreCase ) && x.Value == y.Value; + } + + public override int GetHashCode( KeyValuePair obj ) + { + return ( obj.Key == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode( obj.Key ) ) ^ ( obj.Value == null ? 0 : obj.Value.GetHashCode() ); + } + } + + [Conditional( "DEBUG" )] + private static void Trace( string format, params object[] args ) + { +#if !SILVERLIGHT && !WINDOWS_PHONE && !NETFX_CORE + Tracer.Binding.TraceEvent( Tracer.EventType.Trace, Tracer.EventId.Trace, format, args ); +#endif // !SILVERLIGHT && !WINDOWS_PHONE && !NETFX_CORE + } + + private enum ConstructorKind + { + None = 0, + Marked, + Default, + Parameterful, + Ambiguous } -#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !AOT } } diff --git a/src/MsgPack/Serialization/SerializerAssemblyGenerationConfiguration.cs b/src/MsgPack/Serialization/SerializerAssemblyGenerationConfiguration.cs index f6df2601b..1cadb925b 100644 --- a/src/MsgPack/Serialization/SerializerAssemblyGenerationConfiguration.cs +++ b/src/MsgPack/Serialization/SerializerAssemblyGenerationConfiguration.cs @@ -169,6 +169,28 @@ public string Namespace } } + private readonly SerializationCompatibilityOptions _compatibilityOptions = new SerializationCompatibilityOptions(); + + /// + /// Gets the compatibility options for generating serializers. + /// + /// + /// The which stores compatibility options for generating serializers. This value will not be null. + /// + public SerializationCompatibilityOptions CompatibilityOptions + { + get { return this._compatibilityOptions; } + } + + /// + /// Gets or sets a value indicating whether generated serializers will override async methods or not. + /// + /// + /// true if generated serializers will override async methods; otherwise, false. + /// Default is true. + /// + public bool WithAsync { get; set; } + /// /// Initializes a new instance of the class. /// diff --git a/src/MsgPack/Serialization/SerializerCapabilities.cs b/src/MsgPack/Serialization/SerializerCapabilities.cs index de8736d73..a6a941f2c 100644 --- a/src/MsgPack/Serialization/SerializerCapabilities.cs +++ b/src/MsgPack/Serialization/SerializerCapabilities.cs @@ -22,7 +22,6 @@ namespace MsgPack.Serialization { -#warning TODO: Asymmetric serializers /// /// Represents serializer capabilities. /// diff --git a/src/MsgPack/Serialization/SerializerCodeGenerationConfiguration.cs b/src/MsgPack/Serialization/SerializerCodeGenerationConfiguration.cs index 4def58718..9b11e7369 100644 --- a/src/MsgPack/Serialization/SerializerCodeGenerationConfiguration.cs +++ b/src/MsgPack/Serialization/SerializerCodeGenerationConfiguration.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -214,6 +214,45 @@ public EnumSerializationMethod EnumSerializationMethod /// public bool IsInternalToMsgPackLibrary { get; set; } // This is also convinience to Unittest -- which is intern with InternalsVisibleTo + private readonly SerializationCompatibilityOptions _compatibilityOptions = new SerializationCompatibilityOptions(); + + /// + /// Gets the compatibility options for generating serializers. + /// + /// + /// The which stores compatibility options for generating serializers. This value will not be null. + /// + public SerializationCompatibilityOptions CompatibilityOptions + { + get { return this._compatibilityOptions; } + } + + /// + /// Gets or sets a value indicating whether generated serializers will override async methods or not. + /// + /// + /// true if generated serializers will override async methods; otherwise, false. + /// Default is true. + /// + public bool WithAsync { get; set; } + + /// + /// Gets or sets a value indicating whether generated serializers will not be qualified with or not. + /// + /// + /// true if generated serializers will not be qualified with ; otherwise, false. + /// Default is false. + /// + public bool SuppressDebuggerNonUserCodeAttribute { get; set; } + + /// + /// Gets or sets the code generation sink which handles code generation output. + /// + /// + /// The code generation sink. If the value is null, default file based sink will be used. + /// + public CodeGenerationSink CodeGenerationSink { get; set; } + /// /// Initializes a new instance of the class. /// diff --git a/src/MsgPack/Serialization/SerializerCodeInformation.cs b/src/MsgPack/Serialization/SerializerCodeInformation.cs new file mode 100644 index 000000000..8d053888e --- /dev/null +++ b/src/MsgPack/Serialization/SerializerCodeInformation.cs @@ -0,0 +1,130 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Text; + +namespace MsgPack.Serialization +{ + /// + /// Represents generating serializer code information. + /// + public sealed class SerializerCodeInformation + { + /// + /// Gets the full name of the generating type. + /// + /// + /// The full name of the generating type. + /// + public string TypeFullName { get; private set; } + + /// + /// Gets the directory where the code file to be generated. + /// + /// + /// The directory where the code file to be generated. + /// + public string Directory { get; private set; } + + /// + /// Gets the file extension of the code including leading dot. + /// + /// + /// The file extension of the code including leading dot. + /// + public string FileExtension { get; private set; } + + /// + /// Gets or sets the which the code text to be written. + /// + /// + /// The text writer the which the code text to be written. + /// The initial value is null. + /// If this property is not set, the code generator will fail to emit the code. + /// + /// + /// You should not set this property directly, use or instead. + /// + public TextWriter TextWriter { get; set; } + + /// + /// Gets or sets the file path of the generating code. + /// + /// + /// The file path of the generating code. + /// The initial value is null. + /// This property will be used to report code generation result. + /// + /// + /// You should not set this property directly, use or instead. + /// + public string FilePath { get; set; } + + internal SerializerCodeInformation( string typeFullName, string directory, string fileExtension ) + { + this.TypeFullName = typeFullName; + this.Directory = directory; + this.FileExtension = fileExtension; + } + + /// + /// Sets up this object to use for specified file path. + /// + /// The file path. + /// The is null. + /// The is empty or invalid character. + /// The is unsupported form. + /// The is too long. + /// The point the directory which does not exist. + /// The points the location which is not writable from this process. + /// + /// Use this method to emit the code to the file. + /// This method sets and property. + /// + public void SetFileWriter( string path ) + { + this.TextWriter = new StreamWriter( path, false, Encoding.UTF8 ); + this.FilePath = Path.GetFullPath( path ); + } + + /// + /// Sets up this object to use specified . + /// + /// The writer. + /// The is null. + /// + /// Use this method to emit the code to specified instead of the file. + /// Use if you want to emit to the file. + /// This method sets the property with the argument, and sets null for . + /// + public void SetNonFileWriter( TextWriter writer ) + { + if ( writer == null ) + { + throw new ArgumentNullException( "writer" ); + } + + this.TextWriter = writer; + this.FilePath = null; + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/SerializerDebugging.cs b/src/MsgPack/Serialization/SerializerDebugging.cs index 083882813..c794f0ae7 100644 --- a/src/MsgPack/Serialization/SerializerDebugging.cs +++ b/src/MsgPack/Serialization/SerializerDebugging.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,29 +16,33 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY -#define AOT #endif using System; -#if !NETFX_35 && !UNITY && !WINDOWS_PHONE +#if FEATURE_CONCURRENT using System.Collections.Concurrent; -#endif // !NETFX_35 && !UNITY && !WINDOWS_PHONE +#endif // FEATURE_CONCURRENT using System.Collections.Generic; -#if CORE_CLR || UNITY +using System.Diagnostics; +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; +using System.Text; using System.Threading; namespace MsgPack.Serialization @@ -46,9 +50,15 @@ namespace MsgPack.Serialization /// /// Holds debugging support information. /// - internal static class SerializerDebugging +#if UNITY && DEBUG + public +#else + internal +#endif + static class SerializerDebugging { -#if !AOT +#if !UNITY +#if DEBUG [ThreadStatic] private static bool _traceEnabled; @@ -65,7 +75,6 @@ public static bool TraceEnabled set { _traceEnabled = value; } } -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 [ThreadStatic] private static bool _dumpEnabled; @@ -81,9 +90,10 @@ public static bool DumpEnabled get { return _dumpEnabled; } set { _dumpEnabled = value; } } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 -#endif // !AOT +#endif // DEBUG +#endif // !UNITY +#if DEBUG [ThreadStatic] private static bool _avoidsGenericSerializer; @@ -100,10 +110,13 @@ public static bool AvoidsGenericSerializer get { return _avoidsGenericSerializer; } set { _avoidsGenericSerializer = value; } } +#endif // DEBUG -#if !AOT && !SILVERLIGHT +#if FEATURE_EMIT +#if DEBUG [ThreadStatic] private static StringWriter _ilTraceWriter; +#endif // DEBUG /// /// Gets the for IL tracing. @@ -116,9 +129,10 @@ public static TextWriter ILTraceWriter { get { +#if DEBUG if ( !_traceEnabled ) { - return TextWriter.Null; + return NullTextWriter.Instance; } if ( _ilTraceWriter == null ) @@ -127,17 +141,21 @@ public static TextWriter ILTraceWriter } return _ilTraceWriter; +#else + return NullTextWriter.Instance; +#endif // DEBUG } } +#if DEBUG /// - /// Traces the specific event. + /// Traces the emitting event. /// /// The format string. /// The args for formatting. [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "format", Justification = "Used in other platforms" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args", Justification = "Used in other platforms" )] - public static void TraceEvent( string format, params object[] args ) + public static void TraceEmitEvent( string format, params object[] args ) { if ( !_traceEnabled ) { @@ -146,7 +164,33 @@ public static void TraceEvent( string format, params object[] args ) Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, format, args ); } +#endif // DEBUG +#endif // FEATURE_EMIT + /// + /// Traces the polymorphic schema event. + /// + /// The format string. + /// The target of schema. + /// The schema. + [Conditional( "DEBUG" )] + public static void TracePolimorphicSchemaEvent( string format, MemberInfo memberInfo, PolymorphismSchema schema ) + { +#if DEBUG +#if FEATURE_EMIT + if ( !_traceEnabled ) + { + return; + } + + Tracer.Emit.TraceEvent( Tracer.EventType.PolimorphicSchema, Tracer.EventId.PolimorphicSchema, format, memberInfo, schema == null ? "(null)" : schema.DebugString ); +#endif // FEATURE_EMIT +#endif + } + +#if DEBUG + +#if FEATURE_EMIT /// /// Flushes the trace data. /// @@ -162,7 +206,8 @@ public static void FlushTraceData() _ilTraceWriter.GetStringBuilder().Length = 0; } -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD1_3 +#if !NETSTANDARD2_0 [ThreadStatic] private static AssemblyBuilder _assemblyBuilder; @@ -199,152 +244,82 @@ public static void PrepareDump() _moduleBuilder = _assemblyBuilder.DefineDynamicModule( "ExpressionTreeSerializerLogics", "ExpressionTreeSerializerLogics.dll", true ); } +#endif // !NETSTANDARD2_0 - [ThreadStatic] - private static IList _runtimeAssemblies; +#if !FERATURE_CONCURRENT + private static volatile DependentAssemblyManager _dependentAssemblyManager = DependentAssemblyManager.Default; - [ThreadStatic] - private static IList _compiledCodeDomSerializerAssemblies; + public static DependentAssemblyManager DependentAssemblyManager + { + get { return _dependentAssemblyManager; } + set { _dependentAssemblyManager = value; } + } +#else + private static DependentAssemblyManager _dependentAssemblyManager = DependentAssemblyManager.Default; - public static IEnumerable CodeDomSerializerDependentAssemblies + public static DependentAssemblyManager DependentAssemblyManager { - get - { - EnsureDependentAssembliesListsInitialized(); -#if DEBUG - Contract.Assert( _compiledCodeDomSerializerAssemblies != null ); -#endif // DEBUG - // FCL dependencies and msgpack core libs - foreach ( var runtimeAssembly in _runtimeAssemblies ) - { - yield return runtimeAssembly; - } + get { return Volatile.Read( ref _dependentAssemblyManager ); } + set { Volatile.Write( ref _dependentAssemblyManager, value ); } + } +#endif // FERATURE_CONCURRENT - // dependents - foreach ( var compiledAssembly in _compiledCodeDomSerializerAssemblies ) - { - yield return compiledAssembly; - } - } + public static IEnumerable CodeSerializerDependentAssemblies + { + get { return _dependentAssemblyManager.CodeSerializerDependentAssemblies; } } -#endif // !SILVERLIGHT -#if NETSTANDARD1_1 || NETSTANDARD1_3 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pathToAssembly", Justification = "For API compatibility" )] -#endif // NETSTANDARD1_1 || NETSTANDARD1_3 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] + public static void AddRuntimeAssembly( string pathToAssembly ) { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - EnsureDependentAssembliesListsInitialized(); - _runtimeAssemblies.Add( pathToAssembly ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + _dependentAssemblyManager.AddRuntimeAssembly( pathToAssembly ); } -#if NETSTANDARD1_1 || NETSTANDARD1_3 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pathToAssembly", Justification = "For API compatibility" )] -#endif // NETSTANDARD1_1 || NETSTANDARD1_3 - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] - public static void AddCompiledCodeDomAssembly( string pathToAssembly ) + public static void AddCompiledCodeAssembly( string pathToAssembly ) { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - EnsureDependentAssembliesListsInitialized(); - _compiledCodeDomSerializerAssemblies.Add( pathToAssembly ); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + _dependentAssemblyManager.AddCompiledCodeAssembly( pathToAssembly ); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] - public static void ResetDependentAssemblies() + public static void AddCompiledCodeAssembly( string name, byte[] image ) { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - EnsureDependentAssembliesListsInitialized(); - -#if !NETFX_35 - File.AppendAllLines( GetHistoryFilePath(), _compiledCodeDomSerializerAssemblies ); -#else - File.AppendAllText( GetHistoryFilePath(), String.Join( Environment.NewLine, _compiledCodeDomSerializerAssemblies.ToArray() ) + Environment.NewLine ); -#endif // !NETFX_35 - _compiledCodeDomSerializerAssemblies.Clear(); - ResetRuntimeAssemblies(); -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 + _dependentAssemblyManager.AddCompiledCodeAssembly( name, image ); } -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 - private static int _wasDeleted; - private const string HistoryFile = "MsgPack.Serialization.SerializationGenerationDebugging.CodeDOM.History.txt"; - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] - public static void DeletePastTemporaries() + public static void ResetDependentAssemblies() { - if ( Interlocked.CompareExchange( ref _wasDeleted, 1, 0 ) != 0 ) - { - return; - } - - try - { - var historyFilePath = GetHistoryFilePath(); - if ( !File.Exists( historyFilePath ) ) - { - return; - } - - foreach ( var pastAssembly in File.ReadAllLines( historyFilePath ) ) - { - if ( !String.IsNullOrEmpty( pastAssembly ) ) - { - File.Delete( pastAssembly ); - } - } - - new FileStream( historyFilePath, FileMode.Truncate ).Close(); - } - catch ( IOException ) { } + _dependentAssemblyManager.ResetDependentAssemblies(); } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] - private static string GetHistoryFilePath() + public static string DumpDirectory { - return Path.Combine( Path.GetTempPath(), HistoryFile ); + get { return _dependentAssemblyManager.DumpDirectory; } +#if DEBUG + set { _dependentAssemblyManager.DumpDirectory = value; } +#endif // DEBUG } - private static void EnsureDependentAssembliesListsInitialized() + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] + public static void DeletePastTemporaries() { - if ( _runtimeAssemblies == null ) - { - _runtimeAssemblies = new List(); - ResetRuntimeAssemblies(); - } - - if ( _compiledCodeDomSerializerAssemblies == null ) - { - _compiledCodeDomSerializerAssemblies = new List(); - } + _dependentAssemblyManager.DeletePastTemporaries(); } - private static void ResetRuntimeAssemblies() + public static Assembly LoadAssembly( string path ) { - _runtimeAssemblies.Add( "System.dll" ); -#if NETFX_35 - _runtimeAssemblies.Add( typeof( Enumerable ).Assembly.Location ); -#else - _runtimeAssemblies.Add( "System.Core.dll" ); - _runtimeAssemblies.Add( "System.Numerics.dll" ); -#endif // NETFX_35 - _runtimeAssemblies.Add( typeof( SerializerDebugging ).Assembly.Location ); + return _dependentAssemblyManager.LoadAssembly( path ); } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 [ThreadStatic] private static bool _onTheFlyCodeDomEnabled; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] - public static bool OnTheFlyCodeDomEnabled + public static bool OnTheFlyCodeGenerationEnabled { get { return _onTheFlyCodeDomEnabled; } set { _onTheFlyCodeDomEnabled = value; } } -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD2_0 /// /// Creates the new type builder for the serializer. /// @@ -370,14 +345,14 @@ public static TypeBuilder NewTypeBuilder( Type targetType ) [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static void Dump() { -#if !NETFX_35 +#if !NET35 if ( _assemblyBuilder != null ) { _assemblyBuilder.Save( _assemblyBuilder.GetName().Name + ".dll" ); } -#endif // !NETFX_35 +#endif // !NET35 } -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETSTANDARD2_0 /// /// Resets debugging states. @@ -385,11 +360,11 @@ public static void Dump() [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static void Reset() { -#if !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETSTANDARD2_0 _assemblyBuilder = null; _moduleBuilder = null; +#endif // !NETSTANDARD2_0 _dumpEnabled = false; -#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 if ( _ilTraceWriter != null ) { @@ -398,9 +373,38 @@ public static void Reset() } _traceEnabled = false; + _codeWriter = null; ResetDependentAssemblies(); } -#endif // !AOT && !SILVERLIGHT +#endif // !NETSTANDARD1_3 +#endif // FEATURE_EMIT + +#if NET35 || UNITY || SILVERLIGHT + private static int _useLegacyNullMapEntryHandling; +#else + private static bool _useLegacyNullMapEntryHandling; +#endif // NET35 || UNITY || SILVERLIGHT + + public static bool UseLegacyNullMapEntryHandling + { + get + { +#if NET35 || UNITY || SILVERLIGHT + return Volatile.Read( ref _useLegacyNullMapEntryHandling ) == 1; +#else + return Volatile.Read( ref _useLegacyNullMapEntryHandling ); +#endif + } + set + { +#if NET35 || UNITY || SILVERLIGHT + Volatile.Write( ref _useLegacyNullMapEntryHandling, value ? 1 : 0 ); +#else + Volatile.Write( ref _useLegacyNullMapEntryHandling, value ); +#endif + } + } + #if DEBUG && FEATURE_TAP @@ -421,5 +425,52 @@ internal static void EnsureNaiveAsyncAllowed( object source, [CallerMemberName]s } #endif // DEBUG && FEATURE_TAP + +#if !NETSTANDARD1_1 && !NETSTANDARD1_3 + [ThreadStatic] + private static StringWriter _codeWriter; + + public static StringWriter CodeWriter + { + get + { + if ( _codeWriter == null ) + { + _codeWriter = new StringWriter( CultureInfo.InvariantCulture ); + } + + return _codeWriter; + } + } + + public static void CompileAssembly( bool isDebug, out Assembly compiledAssembly, out IList errors, out IList warnings ) + { + _codeCompiler( CodeWriter.ToString(), isDebug, out compiledAssembly, out errors, out warnings ); + } + + public static void ClearCodeBuffer() + { + // Clears buffer and enable reopen. + _codeWriter = null; + } + +#if FEATURE_CONCURRENT + private static CodeCompiler _codeCompiler; +#else + private static volatile CodeCompiler _codeCompiler; +#endif + + public static void SetCodeCompiler( CodeCompiler codeCompiler ) + { +#if FEATURE_CONCURRENT + Volatile.Write( ref _codeCompiler, codeCompiler ); +#else + _codeCompiler = codeCompiler; +#endif + } + + public delegate void CodeCompiler( string code, bool isDebug, out Assembly compiledAssembly, out IList errors, out IList warnings ); +#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // DEBUG } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/SerializerGenerator.cs b/src/MsgPack/Serialization/SerializerGenerator.cs index abc24a019..753d83474 100644 --- a/src/MsgPack/Serialization/SerializerGenerator.cs +++ b/src/MsgPack/Serialization/SerializerGenerator.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,19 +16,28 @@ // See the License for the specific language governing permissions and // limitations under the License. // +// Contributors: +// Samuel Cragg +// #endregion -- License Terms -- using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; using System.IO; using System.Linq; -using System.Reflection; -using System.Reflection.Emit; using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.CodeDomSerializers; + +#if !NETSTANDARD2_0 +using System.CodeDom; +using System.Diagnostics.Contracts; +using System.Globalization; +using System.Reflection; +using System.Reflection.Emit; + using MsgPack.Serialization.EmittingSerializers; +#endif // !NETSTANDARD2_0 namespace MsgPack.Serialization { @@ -52,8 +61,13 @@ namespace MsgPack.Serialization /// If you want to get such fine grained control for them, you should implement own hand made serializers. /// /// - public class SerializerGenerator + public +#if NETSTANDARD2_0 + static +#endif // NETSTANDARD2_0 + class SerializerGenerator { +#if !NETSTANDARD2_0 /// /// Gets the type of the root object which will be serialized/deserialized. /// @@ -280,6 +294,8 @@ public static IEnumerable GenerateSerializerCode { return new SerializerAssemblyGenerationLogic().Generate( targetTypes, configuration ); } +#endif // !NETSTANDARD2_0 + /// /// Generates source codes which implement auto-generated serializer types for specified types with default configuration. /// @@ -433,11 +449,27 @@ public IEnumerable Generate( IEnumerable t var context = new SerializationContext { - GeneratorOption = SerializationMethodGeneratorOption.CanDump, - EnumSerializationMethod = configuration.EnumSerializationMethod, - SerializationMethod = configuration.SerializationMethod + SerializationMethod = configuration.SerializationMethod, + SerializerOptions = + { +#if FEATURE_TAP + WithAsync = configuration.WithAsync, +#endif // FEATURE_TAP + GeneratorOption = SerializationMethodGeneratorOption.CanDump, + EmitterFlavor = this.EmitterFlavor + }, + EnumSerializationOptions = + { + SerializationMethod = configuration.EnumSerializationMethod + }, + CompatibilityOptions = + { + AllowNonCollectionEnumerableTypes = configuration.CompatibilityOptions.AllowNonCollectionEnumerableTypes, + IgnorePackabilityForCollection = configuration.CompatibilityOptions.IgnorePackabilityForCollection, + OneBoundDataMemberOrder = configuration.CompatibilityOptions.OneBoundDataMemberOrder, + PackerCompatibilityOptions = configuration.CompatibilityOptions.PackerCompatibilityOptions + } }; - context.SerializerOptions.EmitterFlavor = this.EmitterFlavor; IEnumerable realTargetTypes; if ( configuration.IsRecursive ) @@ -450,11 +482,11 @@ public IEnumerable Generate( IEnumerable t { realTargetTypes = targetTypes - .Where( t => !SerializationTarget.BuiltInSerializerExists( configuration, t, t.GetCollectionTraits( CollectionTraitOptions.None ) ) ); + .Where( t => !SerializationTarget.BuiltInSerializerExists( configuration, t, t.GetCollectionTraits( CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) ) ); } var generationContext = this.CreateGenerationContext( context, configuration ); - var generatorFactory = this.CreateGeneratorFactory(); + var generatorFactory = this.CreateGeneratorFactory( context ); foreach ( var targetType in realTargetTypes.Distinct() ) { @@ -476,17 +508,18 @@ public IEnumerable Generate( IEnumerable t private static IEnumerable ExtractElementTypes( SerializationContext context, ISerializerGeneratorConfiguration configuration, Type type ) { - if ( !SerializationTarget.BuiltInSerializerExists( configuration, type, type.GetCollectionTraits( CollectionTraitOptions.None ) ) ) + var traits = type.GetCollectionTraits( CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ); + if ( !SerializationTarget.BuiltInSerializerExists( configuration, type, traits ) ) { yield return type; - // Search dependents recursively if the type is NOT enum. - if ( !type.GetIsEnum() ) + // Search dependents recursively if the type is NOT enum nand NOT collection. + if ( !type.GetIsEnum() && traits.CollectionType == CollectionKind.NotCollection ) { foreach ( var dependentType in SerializationTarget.Prepare( context, type ) - .Members.Where( m => m.Member != null ).SelectMany( m => ExtractElementTypes( context, configuration, m.Member.GetMemberValueType() ) ) + .Members.Where( m => m.Member != null ).SelectMany( m => ExtractElementTypes( context, configuration, m.Member.GetMemberValueType() ) ) ) { yield return dependentType; @@ -494,10 +527,21 @@ var dependentType in } } - if ( type.IsArray ) + var elementTypes = new List(); + + if ( traits.ElementType != null ) { - var elementType = type.GetElementType(); - if ( !SerializationTarget.BuiltInSerializerExists( configuration, elementType, elementType.GetCollectionTraits( CollectionTraitOptions.None ) ) ) + elementTypes.Add( traits.ElementType ); + } + else if ( type.IsGenericType ) + { + // Search generic arguments recursively. + elementTypes.AddRange( type.GetGenericArguments().SelectMany( g => ExtractElementTypes( context, configuration, g ) ) ); + } + + foreach ( var elementType in elementTypes ) + { + if ( !SerializationTarget.BuiltInSerializerExists( configuration, elementType, elementType.GetCollectionTraits( CollectionTraitOptions.None, allowNonCollectionEnumerableTypes: false ) ) ) { foreach ( var descendant in ExtractElementTypes( context, configuration, elementType ) ) { @@ -506,17 +550,6 @@ var dependentType in yield return elementType; } - - yield break; - } - - if ( type.IsGenericType ) - { - // Search generic arguments recursively. - foreach ( var elementType in type.GetGenericArguments().SelectMany( g => ExtractElementTypes( context, configuration, g ) ) ) - { - yield return elementType; - } } if ( configuration.WithNullableSerializers && type.GetIsValueType() && Nullable.GetUnderlyingType( type ) == null ) @@ -528,9 +561,10 @@ var dependentType in protected abstract ISerializerCodeGenerationContext CreateGenerationContext( SerializationContext context, TConfig configuration ); - protected abstract Func CreateGeneratorFactory(); + protected abstract Func CreateGeneratorFactory( SerializationContext context ); } +#if !NETSTANDARD2_0 private sealed class SerializerAssemblyGenerationLogic : SerializerGenerationLogic { protected override EmitterFlavor EmitterFlavor @@ -540,7 +574,7 @@ protected override EmitterFlavor EmitterFlavor public SerializerAssemblyGenerationLogic() { } - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ISerializerCodeGenerationContext CreateGenerationContext( SerializationContext context, SerializerAssemblyGenerationConfiguration configuration ) { return @@ -555,11 +589,12 @@ protected override ISerializerCodeGenerationContext CreateGenerationContext( Ser ); } - protected override Func CreateGeneratorFactory() + protected override Func CreateGeneratorFactory( SerializationContext context ) { - return type => new AssemblyBuilderSerializerBuilder( type, type.GetCollectionTraits( CollectionTraitOptions.Full ) ); + return type => new AssemblyBuilderSerializerBuilder( type, type.GetCollectionTraits( CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) ); } } +#endif // !NETSTANDARD2_0 private sealed class SerializerCodesGenerationLogic : SerializerGenerationLogic { @@ -575,9 +610,9 @@ protected override ISerializerCodeGenerationContext CreateGenerationContext( Ser return new CodeDomContext( context, configuration ); } - protected override Func CreateGeneratorFactory() + protected override Func CreateGeneratorFactory( SerializationContext context ) { - return type => new CodeDomSerializerBuilder( type, type.GetCollectionTraits( CollectionTraitOptions.Full ) ); + return type => new CodeDomSerializerBuilder( type, type.GetCollectionTraits( CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) ); } } } diff --git a/src/MsgPack/Serialization/SerializerOptions.cs b/src/MsgPack/Serialization/SerializerOptions.cs index 200aa3760..156e36970 100644 --- a/src/MsgPack/Serialization/SerializerOptions.cs +++ b/src/MsgPack/Serialization/SerializerOptions.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2012-2016 FUJIWARA, Yusuke +// Copyright (C) 2012-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,16 +20,23 @@ #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY -#define AOT #endif using System; -using System.Threading; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT +#if NETSTANDARD1_3 || NETSTANDARD2_0 +using System.Reflection; +using System.Reflection.Emit; +#endif // NETSTANDARD1_3 || NETSTANDARD2_0 +using System.Runtime.CompilerServices; +using System.Threading; +#if ( NETSTANDARD1_3 || NETSTANDARD2_0 ) && !WINDOWS_UWP +using MsgPack.Serialization.EmittingSerializers; +#endif // ( NETSTANDARD1_3 || NETSTANDARD2_0 ) && !WINDOWS_UWP namespace MsgPack.Serialization { @@ -38,7 +45,7 @@ namespace MsgPack.Serialization /// public sealed class SerializerOptions { -#if AOT || SILVERLIGHT +#if UNITY || SILVERLIGHT private int _emitterFlavor = ( int )EmitterFlavor.ReflectionBased; #else private int _emitterFlavor = ( int )EmitterFlavor.FieldBased; @@ -53,13 +60,18 @@ public sealed class SerializerOptions /// /// For testing purposes. /// - internal EmitterFlavor EmitterFlavor +#if UNITY && DEBUG + public +#else + internal +#endif + EmitterFlavor EmitterFlavor { get { return ( EmitterFlavor )Volatile.Read( ref this._emitterFlavor ); } set { Volatile.Write( ref this._emitterFlavor, ( int )value ); } } -#if !AOT +#if !UNITY private int _generatorOption; @@ -104,38 +116,117 @@ public SerializationMethodGeneratorOption GeneratorOption } } -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT private volatile bool _isRuntimeGenerationDisabled; #else private bool _isRuntimeGenerationDisabled; -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT /// - /// Gets or sets a value indicating whether runtime generation is disabled or not. + /// Gets or sets a value indicating whether runtime generation should be disabled or not. /// /// - /// true if runtime generation is disabled; otherwise, false. + /// true if runtime generation is disabled; otherwise, false. Defaults to false. /// - internal bool IsRuntimeGenerationDisabled + public bool DisableRuntimeCodeGeneration { get { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT return this._isRuntimeGenerationDisabled; #else return Volatile.Read( ref this._isRuntimeGenerationDisabled ); -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT } set { -#if NETFX_35 || UNITY || SILVERLIGHT +#if !FEATURE_CONCURRENT this._isRuntimeGenerationDisabled = value; #else Volatile.Write( ref this._isRuntimeGenerationDisabled, value ); -#endif // NETFX_35 || UNITY || SILVERLIGHT +#endif // !FEATURE_CONCURRENT + } + } + + internal static readonly bool CanEmit = DetermineCanEmit(); + + [MethodImpl( MethodImplOptions.NoInlining )] + private static bool DetermineCanEmit() + { +#if ( NETSTANDARD1_3 || NETSTANDARD2_0 ) && !WINDOWS_UWP + try + { + return DetermineCanEmitCore(); + } + catch + { + return false; + } +#elif NETFX_CORE || UNITY + return false; +#else + // Desktop etc. + return true; +#endif + } + +#if ( NETSTANDARD1_3 || NETSTANDARD2_0 ) && !WINDOWS_UWP + + [MethodImpl( MethodImplOptions.NoInlining )] + private static bool DetermineCanEmitCore() + { + return SerializationMethodGeneratorManager.Fast != null; + } + +#endif // ( NETSTANDARD1_3 || NETSTANDARD2_0 ) && !WINDOWS_UWP + + internal bool CanRuntimeCodeGeneration + { + get { return CanEmit && !this.DisableRuntimeCodeGeneration; } + } + +#endif // !UNITY + +#if !FEATURE_CONCURRENT + private volatile bool _isNonPublicAccessDisabled; +#else + private bool _isNonPublicAccessDisabled; +#endif // !FEATURE_CONCURRENT + + /// + /// Gets or sets a value indicating whether generated and/or reflection serializers should not access non public members via privileged reflection. + /// + /// + /// true if privileged reflection access is disabled; otherwise, false. Defaults to false. + /// + /// + /// The privileged reflection means: + /// + /// Access for non-public fields or property accessors via reflection. This operation requires ReflectionPermission of MemberAccess or RestrictedMemberAccess. + /// Writing values for init only fields via reflection. This operation requires SecurityPermission of SerializationFormatter. + /// + /// If the program run on non-privileged Silverlight environment or restricted desktop CLR, + /// serialization and deserialization should fail with SecurityException. + /// + public bool DisablePrivilegedAccess + { + get + { +#if !FEATURE_CONCURRENT + return this._isNonPublicAccessDisabled; +#else + return Volatile.Read( ref this._isNonPublicAccessDisabled ); +#endif // !FEATURE_CONCURRENT + } + set + { +#if !FEATURE_CONCURRENT + this._isNonPublicAccessDisabled = value; +#else + Volatile.Write( ref this._isNonPublicAccessDisabled, value ); +#endif // !FEATURE_CONCURRENT } } -#endif // !AOT #if FEATURE_TAP @@ -163,9 +254,9 @@ internal SerializerOptions() #if FEATURE_TAP this.WithAsync = true; #endif // FEATURE_TAP -#if !AOT +#if !UNITY this.GeneratorOption = SerializationMethodGeneratorOption.Fast; -#endif // !AOT +#endif // !UNITY } } } diff --git a/src/MsgPack/Serialization/SerializerRepository.cs b/src/MsgPack/Serialization/SerializerRepository.cs index fad98934d..967f6367b 100644 --- a/src/MsgPack/Serialization/SerializerRepository.cs +++ b/src/MsgPack/Serialization/SerializerRepository.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2014 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY -#define AOT #endif using System; using System.Collections.Generic; +using System.Linq; using MsgPack.Serialization.DefaultSerializers; using MsgPack.Serialization.Polymorphic; @@ -140,7 +140,7 @@ public MessagePackSerializer Get( SerializationContext context, object pro #endif // !UNITY } -#if AOT +#if UNITY internal MessagePackSerializer Get( SerializationContext context, Type targetType, object providerParameter ) { if ( context == null ) @@ -157,7 +157,7 @@ internal MessagePackSerializer Get( SerializationContext context, Type targetTyp var asProvider = result as MessagePackSerializerProvider; return ( asProvider != null ? asProvider.Get( context, providerParameter ) : result ) as MessagePackSerializer; } -#endif // AOT +#endif // UNITY /// /// Registers a . @@ -255,7 +255,12 @@ out MessagePackSerializerProvider nullableSerializerProvider } #endif // !UNITY - internal bool Register( Type targetType, MessagePackSerializerProvider serializerProvider, Type nullableType, MessagePackSerializerProvider nullableSerializerProvider, SerializerRegistrationOptions options ) +#if UNITY && DEBUG + public +#else + internal +#endif + bool Register( Type targetType, MessagePackSerializerProvider serializerProvider, Type nullableType, MessagePackSerializerProvider nullableSerializerProvider, SerializerRegistrationOptions options ) { return this._repository.Register( targetType, serializerProvider, nullableType, nullableSerializerProvider, options ); } @@ -346,9 +351,39 @@ public static SerializerRepository GetDefault( SerializationContext ownerContext return new SerializerRepository( InitializeDefaultTable( ownerContext ) ); } - internal bool Contains( Type rootType ) + /// + /// Determines whether this repository contains serializer for the specified target type. + /// + /// Type of the target. + /// + /// true if this repository contains serializer for the specified target type; otherwise, false. + /// This method returns false for null. + /// + public bool ContainsFor( Type targetType ) + { + return this._repository.Contains( targetType ); + } + + /// + /// Gets the copy of registered serializer entries. + /// + /// + /// The copy of registered serializer entries. + /// This value will not be null and consistent in the invoked timing. + /// + /// + /// This method returns snapshot of the invoked timing, so the result may not reflect latest status. + /// You should use the result for debugging or tooling purpose only. + /// Use Get() overloads to get proper serializer. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method causes collection copying." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )] + public IEnumerable> GetRegisteredSerializers() { - return this._repository.Contains( rootType ); + return + this._repository.GetEntries() + .Select( kv => new KeyValuePair( kv.Key, kv.Value as MessagePackSerializer ) ) + .Where( kV => kV.Value != null ); } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Serialization/SerializerRepository.defaults.cs b/src/MsgPack/Serialization/SerializerRepository.defaults.cs index f6b178f90..b81174f86 100644 --- a/src/MsgPack/Serialization/SerializerRepository.defaults.cs +++ b/src/MsgPack/Serialization/SerializerRepository.defaults.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -29,9 +29,9 @@ using System.Collections.Specialized; #endif // !UNITY || MSGPACK_UNITY_FULL using System.Globalization; -#if !WINDOWS_PHONE && !NETFX_35 && !UNITY +#if !WINDOWS_PHONE && !NET35 && !UNITY using System.Numerics; -#endif // !WINDOWS_PHONE && !NETFX_35 && !UNITY +#endif // !WINDOWS_PHONE && !NET35 && !UNITY using System.Reflection; using System.Text; @@ -45,10 +45,20 @@ namespace MsgPack.Serialization // ReSharper disable RedundantNameQualifier partial class SerializerRepository { - internal const int DefaultTableCapacity = 56; +#if UNITY && DEBUG + public +#else + internal +#endif + const int DefaultTableCapacity = 58; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This API is naturally coupled with many types" )] - internal static Dictionary InitializeDefaultTable( SerializationContext ownerContext ) +#if UNITY && DEBUG + public +#else + internal +#endif + static Dictionary InitializeDefaultTable( SerializationContext ownerContext ) { var dictionary = new Dictionary( DefaultTableCapacity ); dictionary.Add( typeof( MessagePackObject ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackObjectMessagePackSerializer( ownerContext ) ); @@ -66,18 +76,20 @@ internal static Dictionary InitializeDefaultTable( Se dictionary.Add( typeof( Byte[] ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_ByteArrayMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( DateTime ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, false ) ); dictionary.Add( typeof( DateTimeOffset ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext, false ) ); -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY + dictionary.Add( typeof( Timestamp ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.TimestampMessagePackSerializerProvider( ownerContext, false ) ); +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, false ) ); -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY // DateTime, DateTimeOffset, and FILETIME must have nullable providers. dictionary.Add( typeof( DateTime? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, true ) ); dictionary.Add( typeof( DateTimeOffset? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext, true ) ); -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY + dictionary.Add( typeof( Timestamp? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.TimestampMessagePackSerializerProvider( ownerContext, true ) ); +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, true ) ); -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY -#if !NETFX_CORE +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY +#if !NETFX_CORE && !NETSTANDARD1_1 dictionary.Add( typeof( DBNull ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DBNullMessagePackSerializer( ownerContext ) ); -#endif // !NETFX_CORE +#endif // !NETFX_CORE && !NETSTANDARD1_1 dictionary.Add( typeof( System.Boolean ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_BooleanMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Byte ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_ByteMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Char ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_CharMessagePackSerializer( ownerContext ) ); @@ -94,11 +106,11 @@ internal static Dictionary InitializeDefaultTable( Se dictionary.Add( typeof( System.UInt32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt32MessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.UInt64 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt64MessagePackSerializer( ownerContext ) ); #if !NETSTANDARD1_1 -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN dictionary.Add( typeof( System.Security.Cryptography.HashAlgorithmName ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer( ownerContext ) ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #endif // !NETSTANDARD1_1 #if !NETSTANDARD1_1 #if !SILVERLIGHT @@ -108,61 +120,61 @@ internal static Dictionary InitializeDefaultTable( Se #endif // !SILVERLIGHT #endif // !NETSTANDARD1_1 #if !WINDOWS_PHONE -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.BigInteger ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_BigIntegerMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY #endif // !WINDOWS_PHONE -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Matrix3x2 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Matrix3x2MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Matrix4x4 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Matrix4x4MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Plane ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_PlaneMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Quaternion ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_QuaternionMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Vector2 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Vector2MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Vector3 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Vector3MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Vector4 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Vector4MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT dictionary.Add( typeof( System.ArraySegment<> ).TypeHandle, typeof( System_ArraySegment_1MessagePackSerializer<> ) ); dictionary.Add( typeof( System.Globalization.CultureInfo ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Globalization_CultureInfoMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Collections.DictionaryEntry ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_DictionaryEntryMessagePackSerializer( ownerContext ) ); @@ -184,11 +196,11 @@ internal static Dictionary InitializeDefaultTable( Se dictionary.Add( typeof( System.Collections.Generic.Queue<> ).TypeHandle, typeof( System_Collections_Generic_Queue_1MessagePackSerializer<> ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #if !WINDOWS_PHONE -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Complex ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_ComplexMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY #endif // !WINDOWS_PHONE #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Uri ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UriMessagePackSerializer( ownerContext ) ); diff --git a/src/MsgPack/Serialization/SerializerRepository.defaults.tt b/src/MsgPack/Serialization/SerializerRepository.defaults.tt index fbb3c62ba..adf4b2c7d 100644 --- a/src/MsgPack/Serialization/SerializerRepository.defaults.tt +++ b/src/MsgPack/Serialization/SerializerRepository.defaults.tt @@ -1,8 +1,8 @@ -<# +<# // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -135,6 +135,24 @@ var excludes = // .NET 4.6 Types -- comment out when you face T4Template problems typeof( System.Diagnostics.Tracing.EventSourceOptions ), typeof( System.Threading.AsyncLocalValueChangedArgs<> ), + // .NET 4.7 Types -- comment out when you face T4Template problems + typeof( System.Security.Cryptography.ECCurve ), + typeof( System.Security.Cryptography.ECParameters ), + typeof( System.Security.Cryptography.ECPoint ), + // .NET 4.7.1 Types -- comment out when you face T4Template problems + typeof( System.Net.Sockets.SocketReceiveFromResult ), + typeof( System.Net.Sockets.SocketReceiveMessageFromResult ), + typeof( System.Runtime.InteropServices.OSPlatform ), + // ValueTuples -- should be supported via tuple support + typeof( System.ValueTuple ), + typeof( System.ValueTuple<> ), + typeof( System.ValueTuple<,> ), + typeof( System.ValueTuple<,,> ), + typeof( System.ValueTuple<,,,> ), + typeof( System.ValueTuple<,,,,> ), + typeof( System.ValueTuple<,,,,,> ), + typeof( System.ValueTuple<,,,,,,> ), + typeof( System.ValueTuple<,,,,,,,> ), }; var structTypes = typeof( object ).Assembly.GetTypes() @@ -222,12 +240,17 @@ var notInNetStandard1_1 = typeof( System.Collections.Specialized.NameValueCollection ), typeof( System.Security.Cryptography.HashAlgorithmName ), }; +var onlyInNetStandard2_0 = + new HashSet() + { + typeof( System.Runtime.InteropServices.OSPlatform ), + }; #> #region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -254,9 +277,9 @@ using System.Collections.Generic; using System.Collections.Specialized; #endif // !UNITY || MSGPACK_UNITY_FULL using System.Globalization; -#if !WINDOWS_PHONE && !NETFX_35 && !UNITY +#if !WINDOWS_PHONE && !NET35 && !UNITY using System.Numerics; -#endif // !WINDOWS_PHONE && !NETFX_35 && !UNITY +#endif // !WINDOWS_PHONE && !NET35 && !UNITY using System.Reflection; using System.Text; @@ -270,10 +293,20 @@ namespace MsgPack.Serialization // ReSharper disable RedundantNameQualifier partial class <#= typeName #> { - internal const int DefaultTableCapacity = <#= structTypes.Where( t => !t.IsEnum ).Count() + classTypes.Length + 19 #>; +#if UNITY && DEBUG + public +#else + internal +#endif + const int DefaultTableCapacity = <#= structTypes.Where( t => !t.IsEnum ).Count() + classTypes.Length + 21 #>; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This API is naturally coupled with many types" )] - internal static Dictionary InitializeDefaultTable( SerializationContext ownerContext ) +#if UNITY && DEBUG + public +#else + internal +#endif + static Dictionary InitializeDefaultTable( SerializationContext ownerContext ) { var dictionary = new Dictionary( DefaultTableCapacity ); dictionary.Add( typeof( MessagePackObject ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackObjectMessagePackSerializer( ownerContext ) ); @@ -291,18 +324,20 @@ namespace MsgPack.Serialization dictionary.Add( typeof( Byte[] ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.<#= typeof( Byte ).FullName.Replace( Type.Delimiter, '_' ).Replace( '`', '_' ) #>ArrayMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( DateTime ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, false ) ); dictionary.Add( typeof( DateTimeOffset ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext, false ) ); -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY + dictionary.Add( typeof( Timestamp ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.TimestampMessagePackSerializerProvider( ownerContext, false ) ); +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, false ) ); -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY // DateTime, DateTimeOffset, and FILETIME must have nullable providers. dictionary.Add( typeof( DateTime? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, true ) ); dictionary.Add( typeof( DateTimeOffset? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext, true ) ); -#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY + dictionary.Add( typeof( Timestamp? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.TimestampMessagePackSerializerProvider( ownerContext, true ) ); +#if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, true ) ); -#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY -#if !NETFX_CORE +#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY +#if !NETFX_CORE && !NETSTANDARD1_1 dictionary.Add( typeof( DBNull ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DBNullMessagePackSerializer( ownerContext ) ); -#endif // !NETFX_CORE +#endif // !NETFX_CORE && !NETSTANDARD1_1 <# foreach( Type type in structTypes ) { @@ -328,7 +363,7 @@ foreach( Type type in structTypes ) if( notInNet45s.Contains( type ) ) { #> -#if !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT <# } @@ -349,7 +384,14 @@ foreach( Type type in structTypes ) if( notInNet35s.Contains( type ) ) { #> -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY +<# + } + + if ( onlyInNetStandard2_0.Contains( type ) ) + { +#> +#if NETSTANDARD2_0 <# } @@ -367,13 +409,20 @@ foreach( Type type in structTypes ) { #> #endif // !UNITY || MSGPACK_UNITY_FULL +<# + } + + if ( onlyInNetStandard2_0.Contains( type ) ) + { +#> +#endif // NETSTANDARD2_0 <# } if( notInNet35s.Contains( type ) ) { #> -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY <# } @@ -394,7 +443,7 @@ foreach( Type type in structTypes ) if( notInNet45s.Contains( type ) ) { #> -#endif // !NETFX_35 && !UNITY && !NETFX_40 && !NETFX_45 && !SILVERLIGHT +#endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT <# } @@ -431,7 +480,7 @@ foreach( Type type in classTypes ) if( notInNet45s.Contains( type ) ) { #> -#if !NETFX_40 && !NETFX_45 +#if !NET40 && !NET45 <# } @@ -445,7 +494,7 @@ foreach( Type type in classTypes ) if( notInNet35s.Contains( type ) ) { #> -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY <# } @@ -479,7 +528,7 @@ foreach( Type type in classTypes ) if( notInNet35s.Contains( type ) ) { #> -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY <# } @@ -493,7 +542,7 @@ foreach( Type type in classTypes ) if( notInNet45s.Contains( type ) ) { #> -#endif // !NETFX_40 && !NETFX_45 +#endif // !NET40 && !NET45 <# } @@ -583,4 +632,4 @@ private static string ToCSharpToken( Type type ) return buffer.ToString(); } -#> \ No newline at end of file +#> diff --git a/src/MsgPack/Serialization/SerializerTypeKeyRepository.cs b/src/MsgPack/Serialization/SerializerTypeKeyRepository.cs index 26de608d6..33ed12bec 100644 --- a/src/MsgPack/Serialization/SerializerTypeKeyRepository.cs +++ b/src/MsgPack/Serialization/SerializerTypeKeyRepository.cs @@ -24,23 +24,23 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY -#if !NETFX_35 && !UNITY +#endif // FEATURE_MPCONTRACT +#if !NET35 && !UNITY using System.Security; -#endif // !NETFX_35 && !UNITY +#endif // !NET35 && !UNITY namespace MsgPack.Serialization { /// /// Specialized for serializers. /// -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] -#endif // !NETFX_35 +#endif // !NET35 internal sealed class SerializerTypeKeyRepository : TypeKeyRepository { #if UNITY diff --git a/src/MsgPack/Serialization/SerializingMember.cs b/src/MsgPack/Serialization/SerializingMember.cs index e7c6fc5b3..f6e77e838 100644 --- a/src/MsgPack/Serialization/SerializingMember.cs +++ b/src/MsgPack/Serialization/SerializingMember.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,11 +23,12 @@ #endif using System; -#if CORE_CLR || UNITY +using System.Globalization; +#if FEATURE_MPCONTRACT using MPContract = MsgPack.MPContract; #else using MPContract = System.Diagnostics.Contracts.Contract; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Reflection; namespace MsgPack.Serialization @@ -38,7 +39,12 @@ namespace MsgPack.Serialization #if !UNITY internal struct SerializingMember #else - internal sealed class SerializingMember +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class SerializingMember #endif // !UNITY { public readonly MemberInfo Member; @@ -64,7 +70,7 @@ public SerializingMember( MemberInfo member, DataMemberContract contract ) this.MemberName = member == null ? null : contract.Name; } -#if !NETFX_35 +#if !NET35 // For Tuple public SerializingMember( string name ) { @@ -75,7 +81,7 @@ public SerializingMember( string name ) this.Contract = default ( DataMemberContract ); this.MemberName = name; } -#endif // !NETFX_35 +#endif // !NET35 public EnumMemberSerializationMethod GetEnumMemberSerializationMethod() { @@ -120,5 +126,15 @@ public DateTimeMemberConversionMethod GetDateTimeMemberConversionMethod() return DateTimeMemberConversionMethod.Default; } + + public override string ToString() + { + if ( this.MemberName == null ) + { + return String.Empty; + } + + return String.Format( CultureInfo.InvariantCulture, "{{\"Name\": \"{0}\", \"Id\": {1}, \"Member\": \"{2}\", \"NilImplication\": \"{3}\" }}", this.MemberName, this.Contract.Id, this.MemberName, this.Contract.NilImplication ); + } } } diff --git a/src/MsgPack/Serialization/SingleTextWriterCodeGenerationSink.cs b/src/MsgPack/Serialization/SingleTextWriterCodeGenerationSink.cs new file mode 100644 index 000000000..d3a5c55cc --- /dev/null +++ b/src/MsgPack/Serialization/SingleTextWriterCodeGenerationSink.cs @@ -0,0 +1,49 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; + +namespace MsgPack.Serialization +{ + /// + /// A which emits all codes to specified . + /// + internal sealed class SingleTextWriterCodeGenerationSink : CodeGenerationSink + { + private readonly TextWriter _writer; + + public SingleTextWriterCodeGenerationSink( TextWriter writer ) + { + if ( writer == null ) + { + throw new ArgumentNullException( "writer" ); + } + + this._writer = writer; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally." )] + protected override void AssignTextWriterCore( SerializerCodeInformation codeInformation ) + { + codeInformation.SetNonFileWriter( this._writer ); + } + } +} \ No newline at end of file diff --git a/src/MsgPack/Serialization/TeeTextWriter.cs b/src/MsgPack/Serialization/TeeTextWriter.cs new file mode 100644 index 000000000..4517ce450 --- /dev/null +++ b/src/MsgPack/Serialization/TeeTextWriter.cs @@ -0,0 +1,269 @@ +// +// This code was generated by a TeeTextWriter.tt. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// + +#if DEBUG +using System.IO; +using System.Text; + +namespace MsgPack.Serialization +{ + internal sealed class TeeTextWriter : TextWriter + { + private readonly TextWriter _main; + private readonly TextWriter _sub; + + public override Encoding Encoding + { + get { return this._main.Encoding; } + } + + public TeeTextWriter( TextWriter main, TextWriter sub ) + : base( main.FormatProvider ) + { + this._main = main; + this._sub = sub; + } + + + public override void Write( string value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Flush() + { + this._main.Flush(); + this._sub.Flush(); + } + +#if !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + public override void Close() + { + this._main.Close(); + this._sub.Close(); + } +#endif // !NETFX_CORE && !NETSTANDARD1_1 && !NETSTANDARD1_3 + + public override void Write( char value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( char[] buffer ) + { + this._main.Write( buffer ); + this._sub.Write( buffer ); + } + + public override void Write( char[] buffer, int index, int count ) + { + this._main.Write( buffer, index, count ); + this._sub.Write( buffer, index, count ); + } + + public override void Write( bool value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( int value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( uint value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( long value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( ulong value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( float value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( double value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( decimal value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + + public override void Write( object value ) + { + this._main.Write( value ); + this._sub.Write( value ); + } + +#if !NETSTANDARD1_1 + public override void Write( string format, object arg0 ) + { + this._main.Write( format, arg0 ); + this._sub.Write( format, arg0 ); + } +#endif // !NETSTANDARD1_1 + +#if !NETSTANDARD1_1 + public override void Write( string format, object arg0, object arg1 ) + { + this._main.Write( format, arg0, arg1 ); + this._sub.Write( format, arg0, arg1 ); + } +#endif // !NETSTANDARD1_1 + +#if !SILVERLIGHT && !NETSTANDARD1_1 + public override void Write( string format, object arg0, object arg1, object arg2 ) + { + this._main.Write( format, arg0, arg1, arg2 ); + this._sub.Write( format, arg0, arg1, arg2 ); + } +#endif // !SILVERLIGHT && !NETSTANDARD1_1 + + public override void Write( string format, object[] arg ) + { + this._main.Write( format, arg ); + this._sub.Write( format, arg ); + } + + public override void WriteLine() + { + this._main.WriteLine(); + this._sub.WriteLine(); + } + + public override void WriteLine( char value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( char[] buffer ) + { + this._main.WriteLine( buffer ); + this._sub.WriteLine( buffer ); + } + + public override void WriteLine( char[] buffer, int index, int count ) + { + this._main.WriteLine( buffer, index, count ); + this._sub.WriteLine( buffer, index, count ); + } + + public override void WriteLine( bool value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( int value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( uint value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( long value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( ulong value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( float value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( double value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( decimal value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( string value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + + public override void WriteLine( object value ) + { + this._main.WriteLine( value ); + this._sub.WriteLine( value ); + } + +#if !NETSTANDARD1_1 + public override void WriteLine( string format, object arg0 ) + { + this._main.WriteLine( format, arg0 ); + this._sub.WriteLine( format, arg0 ); + } +#endif // !NETSTANDARD1_1 + +#if !NETSTANDARD1_1 + public override void WriteLine( string format, object arg0, object arg1 ) + { + this._main.WriteLine( format, arg0, arg1 ); + this._sub.WriteLine( format, arg0, arg1 ); + } +#endif // !NETSTANDARD1_1 + +#if !SILVERLIGHT && !NETSTANDARD1_1 + public override void WriteLine( string format, object arg0, object arg1, object arg2 ) + { + this._main.WriteLine( format, arg0, arg1, arg2 ); + this._sub.WriteLine( format, arg0, arg1, arg2 ); + } +#endif // !SILVERLIGHT && !NETSTANDARD1_1 + + public override void WriteLine( string format, object[] arg ) + { + this._main.WriteLine( format, arg ); + this._sub.WriteLine( format, arg ); + } + } +} +#endif // DEBUG diff --git a/src/MsgPack/Serialization/TeeTextWriter.tt b/src/MsgPack/Serialization/TeeTextWriter.tt new file mode 100644 index 000000000..876ab9108 --- /dev/null +++ b/src/MsgPack/Serialization/TeeTextWriter.tt @@ -0,0 +1,137 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.CodeDom" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Reflection" #> +<#@ import namespace="Microsoft.CSharp" #> +<#@ output extension=".cs" #> +// +// This code was generated by a TeeTextWriter.tt. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// + +using System.IO; +using System.Text; + +namespace MsgPack.Serialization +{ + internal sealed class TeeTextWriter : TextWriter + { + private readonly TextWriter _main; + private readonly TextWriter _sub; + + public override Encoding Encoding + { + get { return this._main.Encoding; } + } + + public TeeTextWriter( TextWriter main, TextWriter sub ) + { + this._main = main; + this._sub = sub; + } + +<# + var notInSLs = + new List> + { + Tuple.Create( "Write", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }), + Tuple.Create( "WriteLine", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }) + }; + var notInNetFxCores = + new List> + { + Tuple.Create("Close", new Type[ 0 ]) + }; + var notInNetStd1_1s = + new List> + { + Tuple.Create("Write", new Type[] { typeof( string ), typeof( object ) }), + Tuple.Create("Write", new Type[] { typeof( string ), typeof( object ), typeof( object ) }), + Tuple.Create("Write", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }), + Tuple.Create("WriteLine", new Type[] { typeof( string ), typeof( object ) }), + Tuple.Create("WriteLine", new Type[] { typeof( string ), typeof( object ), typeof( object ) }), + Tuple.Create("WriteLine", new Type[] { typeof( string ), typeof( object ), typeof( object ), typeof( object ) }), + Tuple.Create("Close", new Type[ 0 ]) + }; + var notInNetStd1_3s = + new List> + { + Tuple.Create("Close", new Type[ 0 ]) + }; + + using (var provider = new CSharpCodeProvider()) + { + IEnumerable methods = + typeof(System.IO.TextWriter).GetMethods() + .Where(m => !m.IsFinal && m.IsVirtual) // A method we can override + .Where(m => m.ReturnType == typeof(void)) // We're generating empty methods only + .Where(m => !m.IsSpecialName); // Exclude properties + + foreach (MethodInfo method in methods) + { +#> + +<# + var unsupportedPlatforms = new List(); + if (IsNotIn(method, notInSLs)) + { + unsupportedPlatforms.Add("SILVERLIGHT"); + } + if (IsNotIn(method, notInNetFxCores)) + { + unsupportedPlatforms.Add("NETFX_CORE"); + } + if (IsNotIn(method, notInNetStd1_1s)) + { + unsupportedPlatforms.Add("NETSTANDARD1_1"); + } + if (IsNotIn(method, notInNetStd1_3s)) + { + unsupportedPlatforms.Add("NETSTANDARD1_3"); + } + + if (unsupportedPlatforms.Count > 0 ) + { +#> +#if <#= String.Join( " && ", unsupportedPlatforms.Select(s => "!" + s )) #> +<# + } + + var parameterInfos = method.GetParameters(); + var parameters = + parameterInfos.Length == 0 + ? "()" + : "( " + String.Join(", ", parameterInfos.Select( p => provider.GetTypeOutput( new CodeTypeReference( p.ParameterType ) ) + " " + p.Name ) ) + " )"; + var arguments = + parameterInfos.Length == 0 + ? "()" + : "( " + String.Join(", ", parameterInfos.Select( p => p.Name ) ) + " )"; + +#> + public override void <#= method.Name #><#= parameters #> + { + this._main.<#= method.Name #><#= arguments #>; + this._sub.<#= method.Name #><#= arguments #>; + } +<# + if (unsupportedPlatforms.Count > 0 ) + { +#> +#endif // <#= String.Join( " && ", unsupportedPlatforms.Select(s => "!" + s )) #> +<# + } + } + } +#> + } +} +<#+ +private static bool IsNotIn(MethodInfo method, IList> unavailableMethodSignatures) +{ + return unavailableMethodSignatures.Any(sig => sig.Item1 == method.Name && sig.Item2.SequenceEqual(method.GetParameters().Select(p => p.ParameterType))); +} +#> diff --git a/src/MsgPack/Serialization/Tracer.cs b/src/MsgPack/Serialization/Tracer.cs index beddff7ea..12726ba26 100644 --- a/src/MsgPack/Serialization/Tracer.cs +++ b/src/MsgPack/Serialization/Tracer.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,17 +18,27 @@ // #endregion -- License Terms -- +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + using System; using System.Diagnostics; -#if NETSTANDARD1_1 || NETSTANDARD1_3 +#if NETSTANDARD1_1 || NETSTANDARD1_3 || ( UNITY && !MSGPACK_UNITY_FULL ) using System.Globalization; -#endif // NETSTANDARD1_1 || NETSTANDARD1_3 +#endif // NETSTANDARD1_1 || NETSTANDARD1_3 || ( UNITY && !MSGPACK_UNITY_FULL ) namespace MsgPack.Serialization { - internal static class Tracer +#if UNITY && DEBUG + public +#else + internal +#endif + static class Tracer { public static readonly TraceSource Emit = new TraceSource( "MsgPack.Serialization.Emit" ); + public static readonly TraceSource Binding = new TraceSource( "MsgPack.Serialization.Binding" ); public static readonly TraceSource Tracing = new TraceSource( "MsgPack.Serialization.Tracing" ); public static class EventId @@ -36,6 +46,7 @@ public static class EventId public const int Trace = 0; public const int ILTrace = 101; public const int DefineType = 102; + public const int PolimorphicSchema = 103; public const int NoAccessorFound = 901; public const int MultipleAccessorFound = 902; public const int ReadOnlyValueTypeMember = 903; @@ -47,6 +58,7 @@ public static class EventType public const TraceEventType Trace = TraceEventType.Verbose; public const TraceEventType ILTrace = TraceEventType.Verbose; public const TraceEventType DefineType = TraceEventType.Verbose; + public const TraceEventType PolimorphicSchema = TraceEventType.Verbose; public const TraceEventType NoAccessorFound = TraceEventType.Verbose; public const TraceEventType MultipleAccessorFound = TraceEventType.Verbose; public const TraceEventType ReadOnlyValueTypeMember = TraceEventType.Verbose; @@ -54,8 +66,13 @@ public static class EventType } } -#if NETSTANDARD1_1 || NETSTANDARD1_3 - internal enum TraceEventType +#if NETSTANDARD1_1 || NETSTANDARD1_3 || ( UNITY && !MSGPACK_UNITY_FULL ) +#if UNITY && DEBUG + public +#else + internal +#endif + enum TraceEventType { Critical = 1, Error = 2, @@ -64,7 +81,12 @@ internal enum TraceEventType Warning = 4, } - internal class TraceSource +#if UNITY && DEBUG + public +#else + internal +#endif + class TraceSource { private readonly string _name; @@ -76,14 +98,18 @@ public TraceSource( string name ) [Conditional( "TRACE" )] public void TraceEvent( TraceEventType eventType, int id, string format, params object[] args ) { +#if !UNITY Debug.WriteLine( String.Format( CultureInfo.InvariantCulture, "{0} {1}: {2} : {3}", this._name, eventType, id, String.Format( CultureInfo.InvariantCulture, format, args ) ) ); +#endif // !UNITY } [Conditional( "TRACE" )] public void TraceData( TraceEventType eventType, int id, object data ) { +#if !UNITY Debug.WriteLine( String.Format( CultureInfo.InvariantCulture, "{0} {1}: {2} : {3}", this._name, eventType, id, data ) ); +#endif // !UNITY } } -#endif // NETSTANDARD1_1 || NETSTANDARD1_3 +#endif // NETSTANDARD1_1 || NETSTANDARD1_3 || ( UNITY && !MSGPACK_UNITY_FULL ) } diff --git a/src/MsgPack/Serialization/TypeKeyRepository.cs b/src/MsgPack/Serialization/TypeKeyRepository.cs index fbafa26d1..1bbd08ef7 100644 --- a/src/MsgPack/Serialization/TypeKeyRepository.cs +++ b/src/MsgPack/Serialization/TypeKeyRepository.cs @@ -24,11 +24,12 @@ using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +using System.Linq; +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #if NETFX_CORE using System.Reflection; #endif @@ -42,7 +43,7 @@ namespace MsgPack.Serialization /// Repository for key type with RWlock scheme. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Repository should not be disposable because it may be shared so it is difficult to determine disposition timing" )] -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] #endif internal class TypeKeyRepository @@ -73,12 +74,12 @@ public TypeKeyRepository( Dictionary table ) this._table = table; } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] #endif -#if NETFX_35 || UNITY +#if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] -#endif // NETFX_35 || UNITY +#endif // NET35 || UNITY private Dictionary GetClonedTable() { bool holdsReadLock = false; @@ -112,12 +113,12 @@ public bool Get( Type type, out object matched, out object genericDefinitionMatc return this.GetCore( type, out matched, out genericDefinitionMatched ); } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] #endif -#if NETFX_35 || UNITY +#if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] -#endif // NETFX_35 || UNITY +#endif // NET35 || UNITY private bool GetCore( Type type, out object matched, out object genericDefinitionMatched ) { bool holdsReadLock = false; @@ -173,12 +174,12 @@ public bool Register( Type type, object entry, Type nullableType, object nullabl return this.RegisterCore( type, entry, nullableType, nullableValue, options ); } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] #endif -#if NETFX_35 || UNITY +#if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] -#endif // NETFX_35 || UNITY +#endif // NET35 || UNITY private bool RegisterCore( Type key, object value, Type nullableType, object nullableValue, SerializerRegistrationOptions options ) { var allowOverwrite = ( options & SerializerRegistrationOptions.AllowOverride ) != 0; @@ -242,12 +243,12 @@ public bool Unregister( Type type ) return this.UnregisterCore( type ); } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] #endif -#if NETFX_35 || UNITY +#if NET35 || UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "CER is OK" )] -#endif // NETFX_35 || UNITY +#endif // NET35 || UNITY private bool UnregisterCore( Type key ) { if ( this._table.ContainsKey( key.TypeHandle ) ) @@ -281,7 +282,7 @@ private bool UnregisterCore( Type key ) return false; } -#if !NETFX_35 && !UNITY +#if !NET35 && !UNITY [SecuritySafeCritical] #endif internal bool Contains( Type type ) @@ -311,5 +312,36 @@ internal bool Contains( Type type ) } } } + +#if !NET35 && !UNITY + [SecuritySafeCritical] +#endif + internal IEnumerable> GetEntries() + { + bool holdsReadLock = false; +#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 + RuntimeHelpers.PrepareConstrainedRegions(); +#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 + try + { +#if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 + RuntimeHelpers.PrepareConstrainedRegions(); +#endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 + try { } + finally + { + this._lock.EnterReadLock(); + holdsReadLock = true; + } + return this._table.Select( kv => new KeyValuePair( Type.GetTypeFromHandle( kv.Key ), kv.Value ) ).ToArray(); + } + finally + { + if ( holdsReadLock ) + { + this._lock.ExitReadLock(); + } + } + } } } diff --git a/src/MsgPack/Serialization/UnpackHelperParameters.cs b/src/MsgPack/Serialization/UnpackHelperParameters.cs new file mode 100644 index 000000000..e4b182402 --- /dev/null +++ b/src/MsgPack/Serialization/UnpackHelperParameters.cs @@ -0,0 +1,949 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if !UNITY || MSGPACK_UNITY_FULL +using System.ComponentModel; +#endif //!UNITY || MSGPACK_UNITY_FULL +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization +{ + // This file was generated from UnpackHelperParameters.tt + // DO NET modify this file directly. + + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackValueTypeValueParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func DirectRead; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackValueTypeValueAsyncParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func> DirectRead; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackReferenceTypeValueParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func DirectRead; + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackReferenceTypeValueAsyncParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func> DirectRead; + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackNullableTypeValueParameters + where TValue : struct + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func DirectRead; + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackNullableTypeValueAsyncParameters + where TValue : struct + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func> DirectRead; + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackMessagePackObjectValueParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackMessagePackObjectValueAsyncParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action Setter; + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the unpacked object. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackFromArrayParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// A delegate to the factory method which creates the result from the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func Factory; + /// + /// The names of the members for pretty exception message. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList ItemNames; + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the unpacked object. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackFromArrayAsyncParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// A delegate to the factory method which creates the result from the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func Factory; + /// + /// The names of the members for pretty exception message. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList ItemNames; + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the unpacked object. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackFromMapParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// A delegate to the factory method which creates the result from the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func Factory; + + /// + /// Delegates each ones unpack single member in order. + /// The key of this dictionary must be member name. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the context object which will store deserialized value. + /// The type of the unpacked object. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackFromMapAsyncParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// A delegate to the factory method which creates the result from the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func Factory; + + /// + /// Delegates each ones unpack single member in order. + /// The key of this dictionary must be member name. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP + + + /// + /// Represents parameters of method. + /// + /// The type of the collection to be unpacked. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackCollectionParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The collection instance to be added unpacked items. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Collection; + + /// + /// A delegate to the bulk operation (typically UnpackToCore call). + /// The 1st argument will be , 2nd argument will be , + /// and 3rd argument will be . + /// If this field is null, will be used. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action BulkOperation; + + /// + /// A delegate to the operation for each items, which typically unpack value and append it to the . + /// The 1st argument will be , 2nd argument will be , + /// and 3rd argument will be index of the current item. + /// If field is not null, this field will be ignored. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action EachOperation; + } + +#if FEATURE_TAP + + /// + /// Represents parameters of method. + /// + /// The type of the collection to be unpacked. +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct UnpackCollectionAsyncParameters + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The collection instance to be added unpacked items. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Collection; + + /// + /// A delegate to the bulk operation (typically UnpackToCore call). + /// The 1st argument will be , 2nd argument will be , + /// and 3rd argument will be . + /// If this field is null, will be used. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func BulkOperation; + + /// + /// A delegate to the operation for each items, which typically unpack value and append it to the . + /// The 1st argument will be , 2nd argument will be , + /// and 3rd argument will be index of the current item. + /// If field is not null, this field will be ignored. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func EachOperation; + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; + } + +#endif // FEATURE_TAP +} diff --git a/src/MsgPack/Serialization/UnpackHelperParameters.tt b/src/MsgPack/Serialization/UnpackHelperParameters.tt new file mode 100644 index 000000000..2f624e59f --- /dev/null +++ b/src/MsgPack/Serialization/UnpackHelperParameters.tt @@ -0,0 +1,470 @@ +<#@ template debug="true" hostSpecific="true" #> +<#@ output extension=".cs" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections.Generic" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2016 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Collections.Generic; +#if !UNITY || MSGPACK_UNITY_FULL +using System.ComponentModel; +#endif //!UNITY || MSGPACK_UNITY_FULL +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack.Serialization +{ + // This file was generated from UnpackHelperParameters.tt + // DO NET modify this file directly. + +<# + var valueGenerics = + new Dictionary + { + { "TContext", "The type of the context object which will store deserialized value." }, + { "TValue", "The type of the value." } + }; + + var mpoGenerics = + new Dictionary + { + { "TContext", "The type of the context object which will store deserialized value." } + }; + + var objectGenerics = + new Dictionary + { + { "TContext", "The type of the context object which will store deserialized value." }, + { "TResult", "The type of the unpacked object." } + }; + + var collectionGenerics = + new Dictionary + { + { "T", "The type of the collection to be unpacked." } + }; +#> + +<# + WriteParameters( "ValueTypeValue", false, valueGenerics, this.WriteUnpackValueTypeValueMembers ); +#> + +<# + WriteParameters( "ValueTypeValue", true, valueGenerics, this.WriteUnpackValueTypeValueMembers ); +#> + +<# + WriteParameters( "ReferenceTypeValue", false, valueGenerics, this.WriteUnpackReferenceTypeValueMembers ); +#> + +<# + WriteParameters( "ReferenceTypeValue", true, valueGenerics, this.WriteUnpackReferenceTypeValueMembers ); +#> + +<# + WriteParameters( "NullableTypeValue", false, valueGenerics, this.WriteUnpackNullableTypeValueMembers, "TValue : struct" ); +#> + +<# + WriteParameters( "NullableTypeValue", true, valueGenerics, this.WriteUnpackNullableTypeValueMembers, "TValue : struct" ); +#> + +<# + WriteParameters( "MessagePackObjectValue", false, mpoGenerics, this.WriteUnpackMessagePackObjectValueMembers ); +#> + +<# + WriteParameters( "MessagePackObjectValue", true, mpoGenerics, this.WriteUnpackMessagePackObjectValueMembers ); +#> + +<# + WriteParameters( "FromArray", false, objectGenerics, this.WriteUnpackObjectFromArrayMembers ); +#> + +<# + WriteParameters( "FromArray", true, objectGenerics, this.WriteUnpackObjectFromArrayMembers ); +#> + +<# + WriteParameters( "FromMap", false, objectGenerics, this.WriteUnpackObjectFromMapMembers ); +#> + +<# + WriteParameters( "FromMap", true, objectGenerics, this.WriteUnpackObjectFromMapMembers ); +#> + + +<# + WriteParameters( "Collection", false, collectionGenerics, this.WriteUnpackCollectionMembers ); +#> + +<# + WriteParameters( "Collection", true, collectionGenerics, this.WriteUnpackCollectionMembers ); +#> +} +<#+ +void WriteParameters( string suffix, bool isAsync, IDictionary genericParameters, Action differenceGenerator, params string[] genericConstraints ) +{ + var methodName = "Unpack" + suffix + ( isAsync ? "Async" : String.Empty ); + var genericParameterTokens = String.Join( ", ", genericParameters.Keys ); + if ( isAsync ) + { +#> +#if FEATURE_TAP + +<#+ + } +#> + /// + /// Represents parameters of method. + /// +<#+ + foreach ( var genericParameter in genericParameters ) + { +#> + /// <#= genericParameter.Value #> +<#+ + } +#> +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "This struct is not intended for value." )] + public struct <#= methodName #>Parameters<<#= genericParameterTokens #>> +<#+ + foreach ( var genericContraint in genericConstraints ) + { +#> + where <#= genericContraint #> +<#+ + } +#> + { + /// + /// The unpacker. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Unpacker Unpacker; +<#+ + differenceGenerator( isAsync ); + + if( isAsync ) + { +#> + + /// + /// The token to monitor for cancellation requests. The default value is . + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public CancellationToken CancellationToken; +<#+ + } +#> + } +<#+ + if( isAsync ) + { +#> + +#endif // FEATURE_TAP +<#+ + } +} + +void WriteUnpackValueMembers( bool isAsync, string tvalue ) +{ +#> + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// The serializer to deserialize current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public MessagePackSerializer<<#= tvalue #>> Serializer; + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int Unpacked; + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public string MemberName; + + /// + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Action> Setter; +<#+ +} + +void WriteAnyTypeValueMembers( bool isAsync, string tvalue ) +{ +#> + + /// + /// The current unpacked count for debugging. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Type TargetObjectType; + + /// + /// The delegate which refers direct reading. This field should be null when is specified. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] +<#+ + if ( !isAsync ) + { +#> + public Func> DirectRead; +<#+ + } + else + { +#> + public Func>> DirectRead; +<#+ + } +#><#+ +} + +void WriteUnpackNullableValueMembers() +{ +#> + + /// + /// The nil implication of current item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public NilImplication NilImplication; +<#+ +} + +void WriteUnpackValueTypeValueMembers( bool isAsync ) +{ + WriteUnpackValueMembers( isAsync, "TValue" ); + WriteAnyTypeValueMembers( isAsync, "TValue" ); +} + +void WriteUnpackReferenceTypeValueMembers( bool isAsync ) +{ + WriteUnpackValueMembers( isAsync, "TValue" ); + WriteAnyTypeValueMembers( isAsync, "TValue" ); + WriteUnpackNullableValueMembers(); +} + +void WriteUnpackNullableTypeValueMembers( bool isAsync ) +{ + WriteUnpackValueMembers( isAsync, "TValue?" ); + WriteAnyTypeValueMembers( isAsync, "TValue?" ); + WriteUnpackNullableValueMembers(); +} + +void WriteUnpackMessagePackObjectValueMembers( bool isAsync ) +{ + WriteUnpackValueMembers( isAsync, "MessagePackObject" ); + WriteUnpackNullableValueMembers(); +} + +void WriteUnpackObjectMembers() +{ +#> + + /// + /// The context which will store deserialized value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public TContext UnpackingContext; + + /// + /// A delegate to the factory method which creates the result from the context. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public Func Factory; +<#+ +} + +void WriteUnpackObjectFromArrayMembers( bool isAsync ) +{ + WriteUnpackObjectMembers(); + +#> + /// + /// The names of the members for pretty exception message. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList ItemNames; +<#+ + if ( !isAsync ) + { +#> + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; +<#+ + } + else + { +#> + + /// + /// Delegates each ones unpack single member in order. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IList> Operations; +<#+ + } +} + +void WriteUnpackObjectFromMapMembers( bool isAsync ) +{ + WriteUnpackObjectMembers(); + + if ( !isAsync ) + { +#> + + /// + /// Delegates each ones unpack single member in order. + /// The key of this dictionary must be member name. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; +<#+ + } + else + { +#> + + /// + /// Delegates each ones unpack single member in order. + /// The key of this dictionary must be member name. + /// The 1st argument will be , 2nd argument will be , + /// 3rd argument is index of current item, and 4th argument is total items count in the array or map stream. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public IDictionary> Operations; +<#+ + } +} + +void WriteUnpackCollectionMembers( bool isAsync ) +{ +#> + + /// + /// The items count to be unpacked. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public int ItemsCount; + + /// + /// The collection instance to be added unpacked items. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] + public T Collection; + + /// + /// A delegate to the bulk operation (typically UnpackToCore call). + /// The 1st argument will be , 2nd argument will be , + /// and 3rd argument will be . + /// If this field is null, will be used. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] +<#+ + if ( !isAsync ) + { +#> + public Action BulkOperation; +<#+ + } + else + { +#> + public Func BulkOperation; +<#+ + } +#> + + /// + /// A delegate to the operation for each items, which typically unpack value and append it to the . + /// The 1st argument will be , 2nd argument will be , + /// and 3rd argument will be index of the current item. + /// If field is not null, this field will be ignored. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design" )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Performance critical effectively internal structure for ref access.")] +<#+ + if ( !isAsync ) + { +#> + public Action EachOperation; +<#+ + } + else + { +#> + public Func EachOperation; +<#+ + } +} +#> diff --git a/src/MsgPack/Serialization/UnpackHelpers.cs b/src/MsgPack/Serialization/UnpackHelpers.cs index d063b6da1..ab1ff3336 100644 --- a/src/MsgPack/Serialization/UnpackHelpers.cs +++ b/src/MsgPack/Serialization/UnpackHelpers.cs @@ -24,7 +24,7 @@ #if DEBUG #define ASSERT -#endif // DEBUG && !UNITY && !UNITY +#endif // DEBUG #if DEBUG && !NETFX_CORE #define TRACING @@ -38,11 +38,11 @@ #endif //!UNITY || MSGPACK_UNITY_FULL using System.Diagnostics; #if ASSERT -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // ASSERT using System.Reflection; using System.Runtime.CompilerServices; @@ -731,13 +731,34 @@ public static T InvokeUnpackFrom( MessagePackSerializer serializer, Unpack return serializer.UnpackFromCore( unpacker ); } + internal static SerializationTarget DetermineCollectionSerializationStrategy( Type instanceType, bool allowAsymmetricSerializer ) + { + bool canDeserialize; + var collectionConstructor = UnpackHelpers.TryGetCollectionConstructor( instanceType ); + if ( collectionConstructor == null ) + { + if ( !allowAsymmetricSerializer ) + { + SerializationExceptions.ThrowTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity( instanceType ); + } + + // Pack only. + canDeserialize = false; + } + else + { + canDeserialize = true; + } + + return SerializationTarget.CreateForCollection( collectionConstructor, canDeserialize ); + } /// /// Retrieves a most appropriate constructor with capacity parameter and comparer parameter or both of them, >or default constructor of the . /// /// The target collection type to be instanciated. /// A constructor of the . - internal static ConstructorInfo GetCollectionConstructor( Type instanceType ) + private static ConstructorInfo TryGetCollectionConstructor( Type instanceType ) { const int noParameters = 0; const int withCapacity = 10; @@ -795,11 +816,6 @@ internal static ConstructorInfo GetCollectionConstructor( Type instanceType ) } } - if ( constructor == null ) - { - SerializationExceptions.ThrowTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity( instanceType ); - } - return constructor; } @@ -846,7 +862,7 @@ public static IEqualityComparer GetEqualityComparer() return AotHelper.GetEqualityComparer(); #endif // !UNITY } - + /// /// Gets the delegate which just returns the input ('identity' function). /// @@ -1025,9 +1041,9 @@ private static void Trace( UnpackerTraceContext context, string label, Unpacker [Conditional( "TRACING" )] private static void TraceCore( string format, params object[] args ) { -#if !UNITY && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN +#if !UNITY && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 Tracer.Tracing.TraceEvent( Tracer.EventType.Trace, Tracer.EventId.Trace, format, args ); -#endif // !UNITY && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN +#endif // !UNITY && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 } private sealed class UnpackerTraceContext @@ -1046,11 +1062,11 @@ public UnpackerTraceContext( long positionOrOffset, string methodName ) } } #if TRACING -#if ( SILVERLIGHT && !WINDOWS_PHONE ) || NETFX_35 || NETFX_40 || UNITY +#if ( SILVERLIGHT && !WINDOWS_PHONE ) || NET35 || NET40 || UNITY namespace System.Runtime.CompilerServices { [AttributeUsage( AttributeTargets.Parameter, Inherited = false )] internal sealed class CallerMemberNameAttribute : Attribute { } } -#endif // SILVERLIGHT || NETFX_35 || NETFX_40 || UNITY +#endif // SILVERLIGHT || NET35 || NET40 || UNITY #endif // TRACING diff --git a/src/MsgPack/Serialization/UnpackHelpers.direct.cs b/src/MsgPack/Serialization/UnpackHelpers.direct.cs index 00bf33a10..3ba602880 100644 --- a/src/MsgPack/Serialization/UnpackHelpers.direct.cs +++ b/src/MsgPack/Serialization/UnpackHelpers.direct.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -31,11 +31,11 @@ using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL #if ASSERT -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // ASSERT #if FEATURE_TAP using System.Threading; diff --git a/src/MsgPack/Serialization/UnpackHelpers.direct.tt b/src/MsgPack/Serialization/UnpackHelpers.direct.tt index 19bb2a3b5..393c4f71e 100644 --- a/src/MsgPack/Serialization/UnpackHelpers.direct.tt +++ b/src/MsgPack/Serialization/UnpackHelpers.direct.tt @@ -1,4 +1,4 @@ -<#@ template debug="true" hostSpecific="true" #> +<#@ template debug="true" hostSpecific="true" #> <#@ output extension=".cs" #> <#@ Assembly Name="System.Core" #> <#@ Assembly Name="System.Windows.Forms" #> @@ -41,11 +41,11 @@ using System; using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL #if ASSERT -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // ASSERT #if FEATURE_TAP using System.Threading; diff --git a/src/MsgPack/Serialization/UnpackHelpers.facade.cs b/src/MsgPack/Serialization/UnpackHelpers.facade.cs index 4fae0f7f8..417c6cbc1 100644 --- a/src/MsgPack/Serialization/UnpackHelpers.facade.cs +++ b/src/MsgPack/Serialization/UnpackHelpers.facade.cs @@ -1,9 +1,9 @@ - + #region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -33,11 +33,11 @@ using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL #if ASSERT -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // ASSERT #if FEATURE_TAP using System.Threading; @@ -51,6 +51,7 @@ namespace MsgPack.Serialization partial class UnpackHelpers { + /// /// Unpacks the complex object from specified with specified / /// @@ -61,13 +62,22 @@ partial class UnpackHelpers /// /// A value read from current stream. /// + /// + /// is null. + /// Or, is null. + /// + /// + /// is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] - public static T UnpackComplexObject( Unpacker unpacker, MessagePackSerializer serializer, int unpacked ) + public static T UnpackComplexObject( + Unpacker unpacker, MessagePackSerializer serializer, int unpacked + ) { if ( unpacker == null ) { @@ -100,7 +110,7 @@ public static T UnpackComplexObject( Unpacker unpacker, MessagePackSerializer } else { - using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() ) + using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { return serializer.UnpackFrom( subtreeUnpacker ); } @@ -122,13 +132,22 @@ public static T UnpackComplexObject( Unpacker unpacker, MessagePackSerializer /// The value of the TResult parameter contains a value whether the operation was succeeded and /// a value read from current stream. /// + /// + /// is null. + /// Or, is null. + /// + /// + /// is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] - public static async Task UnpackComplexObjectAsync( Unpacker unpacker, MessagePackSerializer serializer, int unpacked, CancellationToken cancellationToken ) + public static async Task UnpackComplexObjectAsync( + Unpacker unpacker, MessagePackSerializer serializer, int unpacked, CancellationToken cancellationToken + ) { if ( unpacker == null ) { @@ -161,7 +180,7 @@ public static async Task UnpackComplexObjectAsync( Unpacker unpacker, Mess } else { - using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() ) + using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { return await serializer.UnpackFromAsync( subtreeUnpacker, cancellationToken ).ConfigureAwait( false ); } @@ -170,6 +189,7 @@ public static async Task UnpackComplexObjectAsync( Unpacker unpacker, Mess #endif // FEATURE_TAP + /// /// Unpacks the value type value from MessagePack stream. /// @@ -182,8 +202,22 @@ public static async Task UnpackComplexObjectAsync( Unpacker unpacker, Mess /// The unpacked items count. /// Type of the target object for debugging message. /// Name of the member for debugging message. - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// + /// + /// Both of and are null. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -238,6 +272,114 @@ Func directRead, Action setter SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } + var parameter = + new UnpackValueTypeValueParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, + DirectRead = directRead, + Setter = setter, + }; + UnpackValueTypeValue( ref parameter ); + } + + /// + /// Unpacks the value type value from MessagePack stream. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. + /// The reference to object. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// + /// + /// Both of + /// and of are null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static void UnpackValueTypeValue( + ref UnpackValueTypeValueParameters parameter + ) + where TValue : struct + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + UnpackValueTypeValueCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, + parameter.DirectRead, + parameter.Setter + ); + } + + private static void UnpackValueTypeValueCore( + Unpacker unpacker, TContext context, MessagePackSerializer serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, + Func directRead, Action setter + ) + where TValue : struct + { + #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( context != null ); @@ -284,17 +426,31 @@ Func directRead, Action setter /// The unpacked items count. /// Type of the target object for debugging message. /// Name of the member for debugging message. - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// + /// + /// Both of and are null. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "8", Justification = "False positive because never reached." )] - public static async Task UnpackValueTypeValueAsync( + public static Task UnpackValueTypeValueAsync( Unpacker unpacker, TContext context, MessagePackSerializer serializer, int itemsCount, int unpacked, Type targetObjectType, string memberName, @@ -342,6 +498,117 @@ public static async Task UnpackValueTypeValueAsync( SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } + var parameter = + new UnpackValueTypeValueAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, + DirectRead = directRead, + Setter = setter, + CancellationToken = cancellationToken + }; + return UnpackValueTypeValueAsync( ref parameter ); + } + + /// + /// Unpacks the value type value from MessagePack stream asyncronously. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. + /// The reference to object. + /// A that represents the asynchronous operation. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// + /// + /// Both of + /// and of are null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackValueTypeValueAsync( + ref UnpackValueTypeValueAsyncParameters parameter + ) + where TValue : struct + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + return UnpackValueTypeValueAsyncCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, + parameter.DirectRead, + parameter.Setter + , parameter.CancellationToken + ); + } + + private static async Task UnpackValueTypeValueAsyncCore( + Unpacker unpacker, TContext context, MessagePackSerializer serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, + Func> directRead, Action setter, CancellationToken cancellationToken + ) + where TValue : struct + { + #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( context != null ); @@ -376,6 +643,7 @@ public static async Task UnpackValueTypeValueAsync( #endif // FEATURE_TAP + /// /// Unpacks the reference type value from MessagePack stream. /// @@ -389,8 +657,22 @@ public static async Task UnpackValueTypeValueAsync( /// Type of the target object for debugging message. /// Name of the member for debugging message. /// The nil implication of current item. - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// + /// + /// Both of and are null. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -446,6 +728,117 @@ Func directRead, Action setter SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } + var parameter = + new UnpackReferenceTypeValueParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, + NilImplication = nilImplication, + DirectRead = directRead, + Setter = setter, + }; + UnpackReferenceTypeValue( ref parameter ); + } + + /// + /// Unpacks the reference type value from MessagePack stream. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. + /// The reference to object. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// + /// + /// Both of + /// and of are null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static void UnpackReferenceTypeValue( + ref UnpackReferenceTypeValueParameters parameter + ) + where TValue : class + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + UnpackReferenceTypeValueCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, + parameter.NilImplication, + parameter.DirectRead, + parameter.Setter + ); + } + + private static void UnpackReferenceTypeValueCore( + Unpacker unpacker, TContext context, MessagePackSerializer serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, + NilImplication nilImplication, + Func directRead, Action setter + ) + where TValue : class + { + #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( context != null ); @@ -504,17 +897,31 @@ Func directRead, Action setter /// Type of the target object for debugging message. /// Name of the member for debugging message. /// The nil implication of current item. - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// + /// + /// Both of and are null. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "9", Justification = "False positive because never reached." )] - public static async Task UnpackReferenceTypeValueAsync( + public static Task UnpackReferenceTypeValueAsync( Unpacker unpacker, TContext context, MessagePackSerializer serializer, int itemsCount, int unpacked, Type targetObjectType, string memberName, @@ -563,6 +970,120 @@ public static async Task UnpackReferenceTypeValueAsync( SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } + var parameter = + new UnpackReferenceTypeValueAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, + NilImplication = nilImplication, + DirectRead = directRead, + Setter = setter, + CancellationToken = cancellationToken + }; + return UnpackReferenceTypeValueAsync( ref parameter ); + } + + /// + /// Unpacks the reference type value from MessagePack stream asyncronously. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. + /// The reference to object. + /// A that represents the asynchronous operation. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// + /// + /// Both of + /// and of are null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackReferenceTypeValueAsync( + ref UnpackReferenceTypeValueAsyncParameters parameter + ) + where TValue : class + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + return UnpackReferenceTypeValueAsyncCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, + parameter.NilImplication, + parameter.DirectRead, + parameter.Setter + , parameter.CancellationToken + ); + } + + private static async Task UnpackReferenceTypeValueAsyncCore( + Unpacker unpacker, TContext context, MessagePackSerializer serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, + NilImplication nilImplication, + Func> directRead, Action setter, CancellationToken cancellationToken + ) + where TValue : class + { + #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( context != null ); @@ -608,6 +1129,7 @@ public static async Task UnpackReferenceTypeValueAsync( #endif // FEATURE_TAP + /// /// Unpacks the nullable type value from MessagePack stream. /// @@ -621,8 +1143,22 @@ public static async Task UnpackReferenceTypeValueAsync( /// Type of the target object for debugging message. /// Name of the member for debugging message. /// The nil implication of current item. - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// + /// + /// Both of and are null. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -678,13 +1214,124 @@ public static void UnpackNullableTypeValue( SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } -#if ASSERT - Contract.Assert( unpacker != null ); - Contract.Assert( context != null ); - Contract.Assert( itemsCount >= 0 ); - Contract.Assert( unpacked >= 0 ); - Contract.Assert( targetObjectType != null ); - Contract.Assert( memberName != null ); + var parameter = + new UnpackNullableTypeValueParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, + NilImplication = nilImplication, + DirectRead = directRead, + Setter = setter, + }; + UnpackNullableTypeValue( ref parameter ); + } + + /// + /// Unpacks the nullable type value from MessagePack stream. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. + /// The reference to object. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// + /// + /// Both of + /// and of are null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static void UnpackNullableTypeValue( + ref UnpackNullableTypeValueParameters parameter + ) + where TValue : struct + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + UnpackNullableTypeValueCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, + parameter.NilImplication, + parameter.DirectRead, + parameter.Setter + ); + } + + private static void UnpackNullableTypeValueCore( + Unpacker unpacker, TContext context, MessagePackSerializer serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, + NilImplication nilImplication, + Func directRead, Action setter + ) + where TValue : struct + { + +#if ASSERT + Contract.Assert( unpacker != null ); + Contract.Assert( context != null ); + Contract.Assert( itemsCount >= 0 ); + Contract.Assert( unpacked >= 0 ); + Contract.Assert( targetObjectType != null ); + Contract.Assert( memberName != null ); Contract.Assert( setter != null ); Contract.Assert( serializer != null || directRead != null ); #endif // ASSERT @@ -736,17 +1383,31 @@ public static void UnpackNullableTypeValue( /// Type of the target object for debugging message. /// Name of the member for debugging message. /// The nil implication of current item. - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// + /// + /// Both of and are null. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "9", Justification = "False positive because never reached." )] - public static async Task UnpackNullableTypeValueAsync( + public static Task UnpackNullableTypeValueAsync( Unpacker unpacker, TContext context, MessagePackSerializer serializer, int itemsCount, int unpacked, Type targetObjectType, string memberName, @@ -795,6 +1456,120 @@ public static async Task UnpackNullableTypeValueAsync( SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } + var parameter = + new UnpackNullableTypeValueAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, + NilImplication = nilImplication, + DirectRead = directRead, + Setter = setter, + CancellationToken = cancellationToken + }; + return UnpackNullableTypeValueAsync( ref parameter ); + } + + /// + /// Unpacks the nullable type value from MessagePack stream asyncronously. + /// + /// The type of the context object which will store deserialized value. + /// The type of the value. + /// The reference to object. + /// A that represents the asynchronous operation. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// + /// + /// Both of + /// and of are null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackNullableTypeValueAsync( + ref UnpackNullableTypeValueAsyncParameters parameter + ) + where TValue : struct + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + return UnpackNullableTypeValueAsyncCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, + parameter.NilImplication, + parameter.DirectRead, + parameter.Setter + , parameter.CancellationToken + ); + } + + private static async Task UnpackNullableTypeValueAsyncCore( + Unpacker unpacker, TContext context, MessagePackSerializer serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, + NilImplication nilImplication, + Func> directRead, Action setter, CancellationToken cancellationToken + ) + where TValue : struct + { + #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( context != null ); @@ -840,6 +1615,7 @@ public static async Task UnpackNullableTypeValueAsync( #endif // FEATURE_TAP + /// /// Unpacks the value from MessagePack array. /// @@ -851,6 +1627,16 @@ public static async Task UnpackNullableTypeValueAsync( /// Name of the member for debugging message. /// The nil implication of current item. /// The delegate which takes and unpacked value, and then set the value to the context. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -896,49 +1682,19 @@ Action setter SerializationExceptions.ThrowArgumentNullException( "setter" ); } -#if ASSERT - Contract.Assert( unpacker != null ); - Contract.Assert( context != null ); - Contract.Assert( itemsCount >= 0 ); - Contract.Assert( unpacked >= 0 ); - Contract.Assert( memberName != null ); - Contract.Assert( setter != null ); -#endif // ASSERT - - MessagePackObject nullable; - if ( unpacked < itemsCount ) - { - if ( !unpacker.Read() ) - { - SerializationExceptions.ThrowMissingItem( unpacked, unpacker ); - } - - nullable = unpacker.LastReadData; - } - else - { - nullable = MessagePackObject.Nil; - } - - if ( nullable.IsNil ) - { - switch ( nilImplication ) + var parameter = + new UnpackMessagePackObjectValueParameters { - case NilImplication.Prohibit: - { - SerializationExceptions.ThrowNullIsProhibited( memberName ); - break; - } - case NilImplication.MemberDefault: - { - return; - } - } - } - - setter( context, nullable ); + Unpacker = unpacker, + UnpackingContext = context, + ItemsCount = itemsCount, + Unpacked = unpacked, + MemberName = memberName, + Setter = setter, + NilImplication = nilImplication, + }; + UnpackMessagePackObjectValue( ref parameter ); } - #if FEATURE_TAP /// @@ -954,6 +1710,16 @@ Action setter /// The delegate which takes and unpacked value, and then set the value to the context. /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -962,7 +1728,7 @@ Action setter [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "6", Justification = "False positive because never reached." )] - public static async Task UnpackMessagePackObjectValueFromArrayAsync( + public static Task UnpackMessagePackObjectValueFromArrayAsync( Unpacker unpacker, TContext context, int itemsCount, int unpacked, string memberName, NilImplication nilImplication, @@ -999,53 +1765,106 @@ public static async Task UnpackMessagePackObjectValueFromArrayAsync( SerializationExceptions.ThrowArgumentNullException( "setter" ); } -#if ASSERT - Contract.Assert( unpacker != null ); - Contract.Assert( context != null ); - Contract.Assert( itemsCount >= 0 ); - Contract.Assert( unpacked >= 0 ); - Contract.Assert( memberName != null ); - Contract.Assert( setter != null ); -#endif // ASSERT + var parameter = + new UnpackMessagePackObjectValueAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + ItemsCount = itemsCount, + Unpacked = unpacked, + MemberName = memberName, + Setter = setter, + NilImplication = nilImplication, + CancellationToken = cancellationToken + }; + return UnpackMessagePackObjectValueAsync( ref parameter ); + } +#endif // FEATURE_TAP - MessagePackObject nullable; - if ( unpacked < itemsCount ) + + /// + /// Unpacks the value from MessagePack map. + /// + /// The type of the context object which will store deserialized value. + /// The unpacker. + /// The context which will store deserialized value. + /// The items count to be unpacked. + /// The unpacked items count. + /// Name of the member for debugging message. + /// The nil implication of current item. + /// The delegate which takes and unpacked value, and then set the value to the context. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "6", Justification = "False positive because never reached." )] + public static void UnpackMessagePackObjectValueFromMap( + Unpacker unpacker, TContext context, + int itemsCount, int unpacked, + string memberName, NilImplication nilImplication, + Action setter + ) + { + if ( unpacker == null ) { - if ( !( await unpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) ) - { - SerializationExceptions.ThrowMissingItem( unpacked, unpacker ); - } + SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + } - nullable = unpacker.LastReadData; + if ( context == null ) + { + SerializationExceptions.ThrowArgumentNullException( "context" ); } - else + + if ( itemsCount < 0 ) { - nullable = MessagePackObject.Nil; + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "itemsCount" ); } - if ( nullable.IsNil ) + if ( unpacked < 0 ) { - switch ( nilImplication ) - { - case NilImplication.Prohibit: - { - SerializationExceptions.ThrowNullIsProhibited( memberName ); - break; - } - case NilImplication.MemberDefault: - { - return; - } - } + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "unpacked" ); } - setter( context, nullable ); - } + if ( memberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "memberName" ); + } -#endif // FEATURE_TAP + if ( setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "setter" ); + } + + var parameter = + new UnpackMessagePackObjectValueParameters + { + Unpacker = unpacker, + UnpackingContext = context, + ItemsCount = itemsCount, + Unpacked = unpacked, + MemberName = memberName, + Setter = setter, + NilImplication = nilImplication, + }; + UnpackMessagePackObjectValue( ref parameter ); + } +#if FEATURE_TAP /// - /// Unpacks the value from MessagePack map. + /// Unpacks the value from MessagePack map asyncronously. /// /// The type of the context object which will store deserialized value. /// The unpacker. @@ -1055,6 +1874,18 @@ public static async Task UnpackMessagePackObjectValueFromArrayAsync( /// Name of the member for debugging message. /// The nil implication of current item. /// The delegate which takes and unpacked value, and then set the value to the context. + /// The token to monitor for cancellation requests. The default value is . + /// A that represents the asynchronous operation. + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -1063,11 +1894,11 @@ public static async Task UnpackMessagePackObjectValueFromArrayAsync( [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "6", Justification = "False positive because never reached." )] - public static void UnpackMessagePackObjectValueFromMap( + public static Task UnpackMessagePackObjectValueFromMapAsync( Unpacker unpacker, TContext context, int itemsCount, int unpacked, string memberName, NilImplication nilImplication, - Action setter + Action setter, CancellationToken cancellationToken ) { if ( unpacker == null ) @@ -1100,9 +1931,97 @@ Action setter SerializationExceptions.ThrowArgumentNullException( "setter" ); } + var parameter = + new UnpackMessagePackObjectValueAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + ItemsCount = itemsCount, + Unpacked = unpacked, + MemberName = memberName, + Setter = setter, + NilImplication = nilImplication, + CancellationToken = cancellationToken + }; + return UnpackMessagePackObjectValueAsync( ref parameter ); + } +#endif // FEATURE_TAP + + + /// + /// Unpacks the value from MessagePack stream. + /// + /// The type of the context object which will store deserialized value. + /// The reference to object. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static void UnpackMessagePackObjectValue( + ref UnpackMessagePackObjectValueParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + UnpackMessagePackObjectValueCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.ItemsCount, + parameter.Unpacked, + parameter.MemberName, + parameter.NilImplication, + parameter.Setter + ); + } + + private static void UnpackMessagePackObjectValueCore( + Unpacker unpacker, TContext unpackingContext, + int itemsCount, int unpacked, + string memberName, NilImplication nilImplication, + Action setter + ) + { #if ASSERT Contract.Assert( unpacker != null ); - Contract.Assert( context != null ); + Contract.Assert( unpackingContext != null ); Contract.Assert( itemsCount >= 0 ); Contract.Assert( unpacked >= 0 ); Contract.Assert( memberName != null ); @@ -1140,72 +2059,87 @@ Action setter } } - setter( context, nullable ); + setter( unpackingContext, nullable ); } #if FEATURE_TAP /// - /// Unpacks the value from MessagePack map asyncronously. + /// Unpacks the value from MessagePack stream asyncronously. /// /// The type of the context object which will store deserialized value. - /// The unpacker. - /// The context which will store deserialized value. - /// The items count to be unpacked. - /// The unpacked items count. - /// Name of the member for debugging message. - /// The nil implication of current item. - /// The delegate which takes and unpacked value, and then set the value to the context. - /// The token to monitor for cancellation requests. The default value is . + /// The reference to object. /// A that represents the asynchronous operation. + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "6", Justification = "False positive because never reached." )] - public static async Task UnpackMessagePackObjectValueFromMapAsync( - Unpacker unpacker, TContext context, - int itemsCount, int unpacked, - string memberName, NilImplication nilImplication, - Action setter, CancellationToken cancellationToken + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackMessagePackObjectValueAsync( + ref UnpackMessagePackObjectValueAsyncParameters parameter ) { - if ( unpacker == null ) + if ( parameter.Unpacker == null ) { - SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); } - if ( context == null ) + if ( parameter.UnpackingContext == null ) { - SerializationExceptions.ThrowArgumentNullException( "context" ); + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); } - if ( itemsCount < 0 ) + if ( parameter.ItemsCount < 0 ) { - SerializationExceptions.ThrowArgumentCannotBeNegativeException( "itemsCount" ); + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); } - if ( unpacked < 0 ) + if ( parameter.Unpacked < 0 ) { - SerializationExceptions.ThrowArgumentCannotBeNegativeException( "unpacked" ); + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); } - if ( memberName == null ) + if ( parameter.MemberName == null ) { - SerializationExceptions.ThrowArgumentNullException( "memberName" ); + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); } - if ( setter == null ) + if ( parameter.Setter == null ) { - SerializationExceptions.ThrowArgumentNullException( "setter" ); + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); } + return UnpackMessagePackObjectValueAsyncCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.ItemsCount, + parameter.Unpacked, + parameter.MemberName, + parameter.NilImplication, + parameter.Setter + , parameter.CancellationToken + ); + } + + private static async Task UnpackMessagePackObjectValueAsyncCore( + Unpacker unpacker, TContext unpackingContext, + int itemsCount, int unpacked, + string memberName, NilImplication nilImplication, + Action setter, CancellationToken cancellationToken + ) + { #if ASSERT Contract.Assert( unpacker != null ); - Contract.Assert( context != null ); + Contract.Assert( unpackingContext != null ); Contract.Assert( itemsCount >= 0 ); Contract.Assert( unpacked >= 0 ); Contract.Assert( memberName != null ); @@ -1243,11 +2177,12 @@ public static async Task UnpackMessagePackObjectValueFromMapAsync( } } - setter( context, nullable ); + setter( unpackingContext, nullable ); } #endif // FEATURE_TAP + /// /// Unpacks object from msgpack array. /// @@ -1256,7 +2191,7 @@ public static async Task UnpackMessagePackObjectValueFromMapAsync( /// The unpacker. /// The context which holds intermediate states. This value may be null when the caller implementation allows it. /// A delegate to the factory method which creates the result from the context. - /// The names of the membesr for pretty exception. + /// The names of the members for pretty exception message. /// /// Delegates each ones unpack single member in order. /// The 1st argument will be , 2nd argument will be , @@ -1299,6 +2234,74 @@ IList> operations { SerializationExceptions.ThrowArgumentNullException( "operations" ); } + + var parameter = + new UnpackFromArrayParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Factory = factory, + ItemNames = itemNames, + Operations = operations, + }; + return UnpackFromArray( ref parameter ); + } + + /// + /// Unpacks object from msgpack array. + /// + /// The type of the context. + /// The type of the unpacked object. + /// The reference to object. + /// + /// An unpacked object. + /// + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static TResult UnpackFromArray( + ref UnpackFromArrayParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Factory == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Factory" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return + UnpackFromArrayCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Factory, + parameter.ItemNames, + parameter.Operations + ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "itemNames", Justification = "For DEBUG build." )] + private static TResult UnpackFromArrayCore( + Unpacker unpacker, TContext unpackingContext, + Func factory, + IList itemNames, + IList> operations + ) + { #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( factory != null ); @@ -1314,7 +2317,7 @@ IList> operations var limit = Math.Min( count, operations.Count ); for ( var i = 0; i < limit; i++ ) { - operations[ i ]( unpacker, context, i, count ); + operations[ i ]( unpacker, unpackingContext, i, count ); Trace( ctx, "ReadItem", unpacker, i, itemNames ); } @@ -1326,7 +2329,7 @@ IList> operations } } - return factory( context ); + return factory( unpackingContext ); } #if FEATURE_TAP @@ -1339,7 +2342,7 @@ IList> operations /// The unpacker. /// The context which holds intermediate states. This value may be null when the caller implementation allows it. /// A delegate to the factory method which creates the result from the context. - /// The names of the membesr for pretty exception. + /// The names of the members for pretty exception message. /// /// Delegates each ones unpack single member in order. /// The 1st argument will be , 2nd argument will be , @@ -1364,7 +2367,7 @@ IList> operations [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "itemNames", Justification = "For tracing." )] - public static async Task UnpackFromArrayAsync( + public static Task UnpackFromArrayAsync( Unpacker unpacker, TContext context, Func factory, IList itemNames, @@ -1385,6 +2388,78 @@ public static async Task UnpackFromArrayAsync( { SerializationExceptions.ThrowArgumentNullException( "operations" ); } + + var parameter = + new UnpackFromArrayAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Factory = factory, + ItemNames = itemNames, + Operations = operations, + CancellationToken = cancellationToken + }; + return UnpackFromArrayAsync( ref parameter ); + } + + /// + /// Unpacks object from msgpack array asyncronously. + /// + /// The type of the context. + /// The type of the unpacked object. + /// The reference to object. + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// an unpacked object. + /// + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackFromArrayAsync( + ref UnpackFromArrayAsyncParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Factory == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Factory" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return + UnpackFromArrayAsyncCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Factory, + parameter.ItemNames, + parameter.Operations + , parameter.CancellationToken + ); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "itemNames", Justification = "For DEBUG build." )] + private static async Task UnpackFromArrayAsyncCore( + Unpacker unpacker, TContext unpackingContext, + Func factory, + IList itemNames, + IList> operations, CancellationToken cancellationToken + ) + { #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( factory != null ); @@ -1400,7 +2475,7 @@ public static async Task UnpackFromArrayAsync( var limit = Math.Min( count, operations.Count ); for ( var i = 0; i < limit; i++ ) { - await operations[ i ]( unpacker, context, i, count, cancellationToken ).ConfigureAwait( false ); + await operations[ i ]( unpacker, unpackingContext, i, count, cancellationToken ).ConfigureAwait( false ); Trace( ctx, "ReadItem", unpacker, i, itemNames ); } @@ -1412,13 +2487,14 @@ public static async Task UnpackFromArrayAsync( } } - return factory( context ); + return factory( unpackingContext ); } #endif // FEATURE_TAP + /// - /// Unpacks object from msgpack array. + /// Unpacks object from msgpack map. /// /// The type of the context. /// The type of the unpacked object. @@ -1466,6 +2542,70 @@ IDictionary> operations { SerializationExceptions.ThrowArgumentNullException( "operations" ); } + + var parameter = + new UnpackFromMapParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Factory = factory, + Operations = operations, + }; + return UnpackFromMap( ref parameter ); + } + + /// + /// Unpacks object from msgpack map. + /// + /// The type of the context. + /// The type of the unpacked object. + /// The reference to object. + /// + /// An unpacked object. + /// + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static TResult UnpackFromMap( + ref UnpackFromMapParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Factory == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Factory" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return + UnpackFromMapCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Factory, + parameter.Operations + ); + } + + private static TResult UnpackFromMapCore( + Unpacker unpacker, TContext unpackingContext, + Func factory, + IDictionary> operations + ) + { #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( factory != null ); @@ -1487,7 +2627,7 @@ IDictionary> operations Action operation; if ( key != null && operations.TryGetValue( key, out operation ) ) { - operation( unpacker, context, i, count ); + operation( unpacker, unpackingContext, i, count ); Trace( ctx, "ReadValue", unpacker, i, key ); } else @@ -1506,13 +2646,13 @@ IDictionary> operations } } - return factory( context ); + return factory( unpackingContext ); } #if FEATURE_TAP /// - /// Unpacks object from msgpack array asyncronously. + /// Unpacks object from msgpack map asyncronously. /// /// The type of the context. /// The type of the unpacked object. @@ -1543,7 +2683,7 @@ IDictionary> operations [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "False positive because never reached." )] - public static async Task UnpackFromMapAsync( + public static Task UnpackFromMapAsync( Unpacker unpacker, TContext context, Func factory, IDictionary> operations, CancellationToken cancellationToken @@ -1563,6 +2703,74 @@ public static async Task UnpackFromMapAsync( { SerializationExceptions.ThrowArgumentNullException( "operations" ); } + + var parameter = + new UnpackFromMapAsyncParameters + { + Unpacker = unpacker, + UnpackingContext = context, + Factory = factory, + Operations = operations, + CancellationToken = cancellationToken + }; + return UnpackFromMapAsync( ref parameter ); + } + + /// + /// Unpacks object from msgpack map asyncronously. + /// + /// The type of the context. + /// The type of the unpacked object. + /// The reference to object. + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// an unpacked object. + /// + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackFromMapAsync( + ref UnpackFromMapAsyncParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Factory == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Factory" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return + UnpackFromMapAsyncCore( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Factory, + parameter.Operations + , parameter.CancellationToken + ); + } + + private static async Task UnpackFromMapAsyncCore( + Unpacker unpacker, TContext unpackingContext, + Func factory, + IDictionary> operations, CancellationToken cancellationToken + ) + { #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( factory != null ); @@ -1584,7 +2792,7 @@ public static async Task UnpackFromMapAsync( Func operation; if ( key != null && operations.TryGetValue( key, out operation ) ) { - await operation( unpacker, context, i, count, cancellationToken ).ConfigureAwait( false ); + await operation( unpacker, unpackingContext, i, count, cancellationToken ).ConfigureAwait( false ); Trace( ctx, "ReadValue", unpacker, i, key ); } else @@ -1603,7 +2811,7 @@ public static async Task UnpackFromMapAsync( } } - return factory( context ); + return factory( unpackingContext ); } #endif // FEATURE_TAP @@ -1636,13 +2844,71 @@ public static async Task UnpackFromMapAsync( [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] - public static T UnpackCollection( Unpacker unpacker, int itemsCount, T collection, Action bulkOperation, Action eachOperation ) + public static T UnpackCollection( + Unpacker unpacker, int itemsCount, T collection, Action bulkOperation, Action eachOperation + ) { + if ( unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + } + if ( collection == null ) { SerializationExceptions.ThrowArgumentNullException( "collection" ); } + var parameters = + new UnpackCollectionParameters + { + Unpacker = unpacker, + ItemsCount = itemsCount, + Collection = collection, + BulkOperation = bulkOperation, + EachOperation = eachOperation, + }; + return UnpackCollection( ref parameters ); + } + /// + /// Unpacks the collection from MessagePack stream. + /// + /// The type of the collection to be unpacked. + /// The reference to object. + /// + /// An unpacked collection. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static T UnpackCollection( + ref UnpackCollectionParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Collection == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Collection" ); + } + + return + UnpackCollectionCore( + parameter.Unpacker, + parameter.ItemsCount, + parameter.Collection, + parameter.BulkOperation, + parameter.EachOperation + ); + } + + private static T UnpackCollectionCore( + Unpacker unpacker, int itemsCount, T collection, Action bulkOperation, Action eachOperation + ) + { // ReSharper disable once RedundantAssignment var ctx = default( UnpackerTraceContext ); InitializeUnpackerTrace( unpacker, ref ctx ); @@ -1677,7 +2943,7 @@ public static T UnpackCollection( Unpacker unpacker, int itemsCount, T collec #if FEATURE_TAP /// - /// Unpacks the collection from MessagePack stream. + /// Unpacks the collection from MessagePack stream asyncronously. /// /// The type of the collection to be unpacked. /// The unpacker where position is located at array or map header. @@ -1707,13 +2973,75 @@ public static T UnpackCollection( Unpacker unpacker, int itemsCount, T collec [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] - public static async Task UnpackCollectionAsync( Unpacker unpacker, int itemsCount, T collection, Func bulkOperation, Func eachOperation, CancellationToken cancellationToken ) + public static Task UnpackCollectionAsync( + Unpacker unpacker, int itemsCount, T collection, Func bulkOperation, Func eachOperation, CancellationToken cancellationToken + ) { + if ( unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + } + if ( collection == null ) { SerializationExceptions.ThrowArgumentNullException( "collection" ); } + var parameters = + new UnpackCollectionAsyncParameters + { + Unpacker = unpacker, + ItemsCount = itemsCount, + Collection = collection, + BulkOperation = bulkOperation, + EachOperation = eachOperation, + CancellationToken = cancellationToken + }; + return UnpackCollectionAsync( ref parameters ); + } + /// + /// Unpacks the collection from MessagePack stream asyncronously. + /// + /// The type of the collection to be unpacked. + /// The reference to object. + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// an unpacked collection. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static Task UnpackCollectionAsync( + ref UnpackCollectionAsyncParameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Collection == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Collection" ); + } + + return + UnpackCollectionAsyncCore( + parameter.Unpacker, + parameter.ItemsCount, + parameter.Collection, + parameter.BulkOperation, + parameter.EachOperation + , parameter.CancellationToken + ); + } + + private static async Task UnpackCollectionAsyncCore( + Unpacker unpacker, int itemsCount, T collection, Func bulkOperation, Func eachOperation, CancellationToken cancellationToken + ) + { // ReSharper disable once RedundantAssignment var ctx = default( UnpackerTraceContext ); InitializeUnpackerTrace( unpacker, ref ctx ); diff --git a/src/MsgPack/Serialization/UnpackHelpers.facade.tt b/src/MsgPack/Serialization/UnpackHelpers.facade.tt index edfa292b4..3c89e262f 100644 --- a/src/MsgPack/Serialization/UnpackHelpers.facade.tt +++ b/src/MsgPack/Serialization/UnpackHelpers.facade.tt @@ -1,4 +1,4 @@ -<#@ template debug="true" hostSpecific="true" #> +<#@ template debug="true" hostSpecific="true" #> <#@ output extension=".cs" #> <#@ Assembly Name="System.Core" #> <#@ Assembly Name="System.Windows.Forms" #> @@ -12,7 +12,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -42,11 +42,11 @@ using System.Collections.Generic; using System.ComponentModel; #endif // !UNITY || MSGPACK_UNITY_FULL #if ASSERT -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #endif // ASSERT #if FEATURE_TAP using System.Threading; @@ -67,10 +67,12 @@ foreach ( var isAsync in new [] { false, true } ) { #> #if FEATURE_TAP - <# } + + var methodName = "UnpackComplexObject" + MethodSuffix( isAsync ); #> + /// /// Unpacks the complex object from specified with specified <#= SummarySuffix( isAsync ) #>/ /// @@ -79,38 +81,47 @@ foreach ( var isAsync in new [] { false, true } ) /// The serializer to deserialize complex object. /// The current unpacked count for debugging. <# - if ( isAsync ) - { + if ( isAsync ) + { #> /// The token to monitor for cancellation requests. The default value is . <# - } + } #> /// <# - if ( isAsync ) - { + if ( isAsync ) + { #> /// A that represents the asynchronous operation. /// The value of the TResult parameter contains a value whether the operation was succeeded and /// a value read from current stream. <# - } - else - { + } + else + { #> /// A value read from current stream. <# - } + } #> /// + /// + /// is null. + /// Or, is null. + /// + /// + /// is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] - public static <#= AsyncT( isAsync ) #> UnpackComplexObject<#= MethodSuffix( isAsync ) #>( Unpacker unpacker, MessagePackSerializer serializer, int unpacked<#= CancellationTokenParameter( isAsync ) #> ) + public static <#= AsyncT( isAsync ) #> <#= methodName #>( + Unpacker unpacker, MessagePackSerializer serializer, int unpacked<#= CancellationTokenParameter( isAsync ) #> + ) { if ( unpacker == null ) { @@ -133,18 +144,18 @@ foreach ( var isAsync in new [] { false, true } ) Contract.Assert( unpacked >= 0 ); #endif // ASSERT <# - if ( !isAsync ) - { + if ( !isAsync ) + { #> if ( !unpacker.Read() ) <# - } - else - { + } + else + { #> if ( !( await unpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) ) <# - } + } #> { SerializationExceptions.ThrowMissingItem( unpacked, unpacker ); @@ -156,7 +167,7 @@ foreach ( var isAsync in new [] { false, true } ) } else { - using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() ) + using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { return <#= Await( isAsync ) #>serializer.UnpackFrom<#= MethodSuffix( isAsync ) #>( subtreeUnpacker<#= CancellationTokenArgument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; } @@ -182,15 +193,23 @@ foreach ( var kind in new [] { TypeKind.Value, TypeKind.Reference, TypeKind.Null { #> #if FEATURE_TAP - <# } + + var methodName = "Unpack" + kind + "TypeValue" + MethodSuffix( isAsync ); + foreach ( var isExpandedParameters in new [] { true, false } ) + { #> + /// /// Unpacks the <#= kind.ToString().ToLowerInvariant() #> type value from MessagePack stream<#= SummarySuffix( isAsync ) #>. /// /// The type of the context object which will store deserialized value. /// The type of the value. +<# + if ( isExpandedParameters ) + { +#> /// The unpacker. /// The context which will store deserialized value. /// The serializer to deserialize complex object. This parameter should be null when is specified. @@ -206,47 +225,123 @@ foreach ( var kind in new [] { TypeKind.Value, TypeKind.Reference, TypeKind.Null <# } #> - /// The delegate which referes direct reading. This parameter should be null when is specified. + /// The delegate which refers direct reading. This parameter should be null when is specified. /// The delegate which takes and unpacked value, and then set the value to the context. <# + if ( isAsync ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<# + } + } + else + { +#> + /// The reference to object. +<# + } + if ( isAsync ) { #> - /// The token to monitor for cancellation requests. The default value is . /// A that represents the asynchronous operation. <# } #> + /// +<# + if ( isExpandedParameters ) + { +#> + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. +<# + } + else + { +#> + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. +<# + } +#> + /// + /// +<# + if ( isExpandedParameters ) + { +#> + /// is negative number. + /// Or, is negative number. +<# + } + else + { +#> + /// of is negative number. + /// Or, of is negative number. +<# + } +#> + /// + /// +<# + if ( isExpandedParameters ) + { +#> + /// Both of and are null. +<# + } + else + { +#> + /// Both of + /// and of are null. +<# + } +#> + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL +<# + if ( isExpandedParameters ) + { +#> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] <# - if ( kind != TypeKind.Value ) - { + if ( kind != TypeKind.Value ) + { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "9", Justification = "False positive because never reached." )] <# - } - else - { + } + else + { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "8", Justification = "False positive because never reached." )] <# - } + } #> - public static <#= AsyncVoid( isAsync ) #> Unpack<#= kind #>TypeValue<#= MethodSuffix( isAsync ) #>( + public static <#= TaskVoid( isAsync ) #> <#= methodName #>( Unpacker unpacker, TContext context, MessagePackSerializer<<#= TypeParameter( kind ) #>> serializer, int itemsCount, int unpacked, Type targetObjectType, string memberName, <# - if ( kind != TypeKind.Value ) - { + if ( kind != TypeKind.Value ) + { #> NilImplication nilImplication, <# - } + } #> <#= DirectReadDelegate( kind, isAsync ) #> directRead, Action> setter<#= CancellationTokenParameter( isAsync ) #> ) @@ -292,6 +387,134 @@ foreach ( var kind in new [] { TypeKind.Value, TypeKind.Reference, TypeKind.Null SerializationExceptions.ThrowArgumentException( "directRead", "directRead cannot be null if serializer argument is null." ); } + var parameter = + new <#= methodName #>Parameters + { + Unpacker = unpacker, + UnpackingContext = context, + Serializer = serializer, + ItemsCount = itemsCount, + Unpacked = unpacked, + TargetObjectType = targetObjectType, + MemberName = memberName, +<# + if ( kind != TypeKind.Value ) + { +#> + NilImplication = nilImplication, +<# + } +#> + DirectRead = directRead, + Setter = setter, +<# + if ( isAsync ) + { +#> + CancellationToken = cancellationToken +<# + } +#> + }; + <#= ReturnVoid( isAsync ) #><#= methodName #>( ref parameter ); + } +<# + } + else // isExpandedParametrs + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static <#= TaskVoid( isAsync ) #> <#= methodName #>( + ref <#= methodName #>Parameters parameter + ) + where TValue : <#= kind == TypeKind.Reference ? "class" : "struct" #> + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.TargetObjectType == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "TargetObjectType" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + if ( parameter.Serializer == null && parameter.DirectRead == null ) + { + SerializationExceptions.ThrowArgumentException( "parameter", "DirectRead cannot be null if Serializer field is null." ); + } + + <#= ReturnVoid( isAsync ) #><#= methodName #>Core( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Serializer, + parameter.ItemsCount, + parameter.Unpacked, + parameter.TargetObjectType, + parameter.MemberName, +<# + if ( kind != TypeKind.Value ) + { +#> + parameter.NilImplication, +<# + } +#> + parameter.DirectRead, + parameter.Setter +<# + if ( isAsync ) + { +#> + , parameter.CancellationToken +<# + } +#> + ); + } + + private static <#= AsyncVoid( isAsync ) #> <#= methodName #>Core( + Unpacker unpacker, TContext context, MessagePackSerializer<<#= TypeParameter( kind ) #>> serializer, + int itemsCount, int unpacked, + Type targetObjectType, string memberName, +<# + if ( kind != TypeKind.Value ) + { +#> + NilImplication nilImplication, +<# + } +#> + <#= DirectReadDelegate( kind, isAsync ) #> directRead, Action> setter<#= CancellationTokenParameter( isAsync ) #> + ) + where TValue : <#= kind == TypeKind.Reference ? "class" : "struct" #> + { + #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( context != null ); @@ -319,8 +542,8 @@ foreach ( var kind in new [] { TypeKind.Value, TypeKind.Reference, TypeKind.Null if ( nullable == null ) { <# - if ( kind != TypeKind.Value ) - { + if ( kind != TypeKind.Value ) + { #> switch ( nilImplication ) { @@ -335,13 +558,13 @@ foreach ( var kind in new [] { TypeKind.Value, TypeKind.Reference, TypeKind.Null } } <# - } - else - { + } + else + { #> SerializationExceptions.ThrowValueTypeCannotBeNull( memberName, typeof( TValue ), targetObjectType ); <# - } + } #> } @@ -349,6 +572,9 @@ foreach ( var kind in new [] { TypeKind.Value, TypeKind.Reference, TypeKind.Null } <# + } // isExpandedParametrs + } // foreach ( var isExpandedParametrs ) + if ( isAsync ) { #> @@ -367,10 +593,13 @@ foreach ( var forMap in new [] { false, true } ) { #> #if FEATURE_TAP - <# } + + var methodName = "UnpackMessagePackObjectValueFrom" + ( forMap ? "Map" : "Array" ) + MethodSuffix( isAsync ); + var parameterTypeName = "UnpackMessagePackObjectValue" + MethodSuffix( isAsync ) + "Parameters"; #> + /// /// Unpacks the value from MessagePack <#= forMap ? "map" : "array" #><#= SummarySuffix( isAsync ) #>. /// @@ -391,6 +620,16 @@ foreach ( var forMap in new [] { false, true } ) <# } #> + /// + /// is null. + /// Or, is null. + /// Or, is null. + /// Or, is null. + /// + /// + /// is negative number. + /// Or, is negative number. + /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL @@ -399,7 +638,7 @@ foreach ( var forMap in new [] { false, true } ) [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "6", Justification = "False positive because never reached." )] - public static <#= AsyncVoid( isAsync ) #> UnpackMessagePackObjectValueFrom<#= forMap ? "Map" : "Array" #><#= MethodSuffix( isAsync ) #>( + public static <#= TaskVoid( isAsync ) #> <#= methodName #>( Unpacker unpacker, TContext context, int itemsCount, int unpacked, string memberName, NilImplication nilImplication, @@ -436,9 +675,141 @@ foreach ( var forMap in new [] { false, true } ) SerializationExceptions.ThrowArgumentNullException( "setter" ); } + var parameter = + new <#= parameterTypeName #> + { + Unpacker = unpacker, + UnpackingContext = context, + ItemsCount = itemsCount, + Unpacked = unpacked, + MemberName = memberName, + Setter = setter, + NilImplication = nilImplication, +<# + if ( isAsync ) + { +#> + CancellationToken = cancellationToken +<# + } +#> + }; + <#= ReturnVoid( isAsync ) #>UnpackMessagePackObjectValue<#= MethodSuffix( isAsync ) #>( ref parameter ); + } +<# + + if ( isAsync ) + { +#> +#endif // FEATURE_TAP + +<# + } + } // foreach ( var isAsync ) +} // foreach ( var forMap ) + +foreach ( var isAsync in new [] { false, true } ) +{ + if ( isAsync ) + { +#> +#if FEATURE_TAP +<# + } + + var methodName = "UnpackMessagePackObjectValue" + MethodSuffix( isAsync ); +#> + + /// + /// Unpacks the value from MessagePack stream<#= SummarySuffix( isAsync ) #>. + /// + /// The type of the context object which will store deserialized value. + /// The reference to object. +<# + if ( isAsync ) + { +#> + /// A that represents the asynchronous operation. +<# + } +#> + /// + /// of is null. + /// Or, of is null. + /// Or, of is null. + /// Or, of is null. + /// + /// + /// of is negative number. + /// Or, of is negative number. + /// +#if !UNITY || MSGPACK_UNITY_FULL + [EditorBrowsable( EditorBrowsableState.Never )] +#endif // !UNITY || MSGPACK_UNITY_FULL + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static <#= TaskVoid( isAsync ) #> <#= methodName #>( + ref <#= methodName #>Parameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.UnpackingContext == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "UnpackingContext" ); + } + + if ( parameter.ItemsCount < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "ItemsCount" ); + } + + if ( parameter.Unpacked < 0 ) + { + SerializationExceptions.ThrowArgumentCannotBeNegativeException( "parameter", "Unpacked" ); + } + + if ( parameter.MemberName == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "MemberName" ); + } + + if ( parameter.Setter == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Setter" ); + } + + <#= ReturnVoid( isAsync ) #><#= methodName #>Core( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.ItemsCount, + parameter.Unpacked, + parameter.MemberName, + parameter.NilImplication, + parameter.Setter +<# + if ( isAsync ) + { +#> + , parameter.CancellationToken +<# + } +#> + ); + } + + private static <#= AsyncVoid( isAsync ) #> <#= methodName #>Core( + Unpacker unpacker, TContext unpackingContext, + int itemsCount, int unpacked, + string memberName, NilImplication nilImplication, + Action setter<#= CancellationTokenParameter( isAsync ) #> + ) + { #if ASSERT Contract.Assert( unpacker != null ); - Contract.Assert( context != null ); + Contract.Assert( unpackingContext != null ); Contract.Assert( itemsCount >= 0 ); Contract.Assert( unpacked >= 0 ); Contract.Assert( memberName != null ); @@ -449,34 +820,21 @@ foreach ( var forMap in new [] { false, true } ) if ( unpacked < itemsCount ) { <# - if ( !isAsync ) - { + if ( !isAsync ) + { #> if ( !unpacker.Read() ) <# - } - else - { + } + else + { #> if ( !( await unpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) ) <# - } + } #> { -<# - if ( !forMap ) - { -#> - SerializationExceptions.ThrowMissingItem( unpacked, unpacker ); -<# - } - else - { -#> SerializationExceptions.ThrowMissingItem( unpacked, memberName, unpacker ); -<# - } -#> } nullable = unpacker.LastReadData; @@ -502,19 +860,18 @@ foreach ( var forMap in new [] { false, true } ) } } - setter( context, nullable ); + setter( unpackingContext, nullable ); } <# - if ( isAsync ) - { + if ( isAsync ) + { #> #endif // FEATURE_TAP <# - } - } // foreach ( var isAsync ) -} // foreach ( var forMap ) + } +} // foreach ( var isAsync ) foreach ( var forMap in new [] { false, true } ) { @@ -524,101 +881,135 @@ foreach ( var forMap in new [] { false, true } ) { #> #if FEATURE_TAP - <# } + + var methodName = "UnpackFrom" + ( forMap ? "Map" : "Array" ) + MethodSuffix( isAsync ); + foreach ( var isExpandedParameters in new [] { true, false } ) + { #> + /// - /// Unpacks object from msgpack array<#= SummarySuffix( isAsync )#>. + /// Unpacks object from msgpack <#= forMap ? "map" : "array" #><#= SummarySuffix( isAsync )#>. /// /// The type of the context. /// The type of the unpacked object. +<# + if ( isExpandedParameters ) + { +#> /// The unpacker. /// The context which holds intermediate states. This value may be null when the caller implementation allows it. /// A delegate to the factory method which creates the result from the context. <# - if ( !forMap ) - { + if ( !forMap ) + { #> - /// The names of the membesr for pretty exception. + /// The names of the members for pretty exception message. <# - } + } #> /// /// Delegates each ones unpack single member in order. <# - if ( forMap ) - { + if ( forMap ) + { #> /// The key of this dictionary must be member name. <# - } + } #> /// The 1st argument will be , 2nd argument will be , /// and 3rd argument is index of current item. /// <# - if ( isAsync ) - { + if ( isAsync ) + { #> /// The token to monitor for cancellation requests. The default value is . +<# + } + } + else + { +#> + /// The reference to object. <# } #> /// <# - if ( isAsync ) - { + if ( isAsync ) + { #> /// A that represents the asynchronous operation. /// The value of the TResult parameter contains a value whether the operation was succeeded and /// an unpacked object. <# - } - else - { + } + else + { #> /// An unpacked object. <# - } + } #> /// /// +<# + if ( isExpandedParameters ) + { +#> /// is null. /// Or, is null. /// Or, is null. +<# + } + else + { +#> + /// of is null. + /// Or, of is null. + /// Or, of is null. +<# + } +#> /// #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL +<# + if ( isExpandedParameters ) + { +#> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] <# - if ( !forMap ) - { + if ( !forMap ) + { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "itemNames", Justification = "For tracing." )] <# - } - else - { + } + else + { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "False positive because never reached." )] <# - } + } #> - public static <#= AsyncTResult( isAsync ) #> UnpackFrom<#= forMap ? "Map" : "Array" #><#= MethodSuffix( isAsync ) #>( + public static <#= TaskTResult( isAsync ) #> <#= methodName #>( Unpacker unpacker, TContext context, Func factory, <# - if ( !forMap ) - { + if ( !forMap ) + { #> IList itemNames, <# - } + } #> <#= OperationDelegateList( forMap, isAsync ) #> operations<#= CancellationTokenParameter( isAsync ) #> ) @@ -637,6 +1028,105 @@ foreach ( var forMap in new [] { false, true } ) { SerializationExceptions.ThrowArgumentNullException( "operations" ); } + + var parameter = + new <#= methodName #>Parameters + { + Unpacker = unpacker, + UnpackingContext = context, + Factory = factory, +<# + if ( !forMap ) + { +#> + ItemNames = itemNames, +<# + } +#> + Operations = operations, +<# + if ( isAsync ) + { +#> + CancellationToken = cancellationToken +<# + } +#> + }; + return <#= methodName #>( ref parameter ); + } +<# + } + else // isExpandedParameters + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static <#= TaskTResult( isAsync ) #> <#= methodName #>( + ref <#= methodName #>Parameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Factory == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Factory" ); + } + + if ( parameter.Operations == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Operations" ); + } + + return + <#= methodName #>Core( + parameter.Unpacker, + parameter.UnpackingContext, + parameter.Factory, +<# + if ( !forMap ) + { +#> + parameter.ItemNames, +<# + } +#> + parameter.Operations +<# + if ( isAsync ) + { +#> + , parameter.CancellationToken +<# + } +#> + ); + } + +<# + if ( !forMap ) + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "itemNames", Justification = "For DEBUG build." )] +<# + } +#> + private static <#= AsyncTResult( isAsync ) #> <#= methodName #>Core( + Unpacker unpacker, TContext unpackingContext, + Func factory, +<# + if ( !forMap ) + { +#> + IList itemNames, +<# + } +#> + <#= OperationDelegateList( forMap, isAsync ) #> operations<#= CancellationTokenParameter( isAsync ) #> + ) + { #if ASSERT Contract.Assert( unpacker != null ); Contract.Assert( factory != null ); @@ -650,31 +1140,31 @@ foreach ( var forMap in new [] { false, true } ) InitializeUnpackerTrace( unpacker, ref ctx ); <# - if ( !forMap ) - { + if ( !forMap ) + { #> var limit = Math.Min( count, operations.Count ); <# - } - else - { + } + else + { #> var limit = count; <# - } + } #> for ( var i = 0; i < limit; i++ ) { <# - if ( !forMap ) - { + if ( !forMap ) + { #> - <#= Await( isAsync ) #>operations[ i ]( unpacker, context, i, count<#= CancellationTokenArgument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>operations[ i ]( unpacker, unpackingContext, i, count<#= CancellationTokenArgument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; Trace( ctx, "ReadItem", unpacker, i, itemNames ); <# - } - else - { + } + else + { #> var key = <#= Await( isAsync ) #>UnpackStringValue<#= MethodSuffix( isAsync ) #>( unpacker, typeof( TResult ), "MemberName"<#= CancellationTokenArgument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; Trace( ctx, "ReadKey", unpacker, i, key ); @@ -682,7 +1172,7 @@ foreach ( var forMap in new [] { false, true } ) <#= EachOperationDelegate( "TContext", isAsync ) #> operation; if ( key != null && operations.TryGetValue( key, out operation ) ) { - <#= Await( isAsync ) #>operation( unpacker, context, i, count<#= CancellationTokenArgument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; + <#= Await( isAsync ) #>operation( unpacker, unpackingContext, i, count<#= CancellationTokenArgument( isAsync ) #> )<#= ConfigureAwait( isAsync ) #>; Trace( ctx, "ReadValue", unpacker, i, key ); } else @@ -692,7 +1182,7 @@ foreach ( var forMap in new [] { false, true } ) Trace( ctx, "Skip", unpacker, i, key ?? "(null)" ); } <# - } + } #> } @@ -704,10 +1194,13 @@ foreach ( var forMap in new [] { false, true } ) } } - return factory( context ); + return factory( unpackingContext ); } <# + } // isExpandedParameters + } // foreach( var isExpandedParameters ) + if ( isAsync ) { #> @@ -727,11 +1220,19 @@ foreach ( var isAsync in new [] { false, true } ) <# } + + var methodName = "UnpackCollection" + MethodSuffix( isAsync ); + foreach ( var isExpandedParameters in new [] { true, false } ) + { #> /// - /// Unpacks the collection from MessagePack stream. + /// Unpacks the collection from MessagePack stream<#= SummarySuffix( isAsync ) #>. /// /// The type of the collection to be unpacked. +<# + if ( isExpandedParameters ) + { +#> /// The unpacker where position is located at array or map header. /// The collection count gotten from the . /// The collection instance to be added unpacked items. @@ -748,10 +1249,17 @@ foreach ( var isAsync in new [] { false, true } ) /// If parameter is not null, this parameter will be ignored. /// <# - if ( isAsync ) - { + if ( isAsync ) + { #> /// The token to monitor for cancellation requests. The default value is . +<# + } + } + else + { +#> + /// The reference to object. <# } #> @@ -776,16 +1284,88 @@ foreach ( var isAsync in new [] { false, true } ) #if !UNITY || MSGPACK_UNITY_FULL [EditorBrowsable( EditorBrowsableState.Never )] #endif // !UNITY || MSGPACK_UNITY_FULL +<# + if ( isExpandedParameters ) + { +#> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "False positive because never reached." )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "False positive because never reached." )] - public static <#= AsyncT( isAsync ) #> UnpackCollection<#= MethodSuffix( isAsync ) #>( Unpacker unpacker, int itemsCount, T collection, <#= BulkOperationDelegate( "T", isAsync ) #> bulkOperation, <#= EachOperationDelegate( "T", isAsync ) #> eachOperation<#= CancellationTokenParameter( isAsync ) #> ) + public static <#= TaskT( isAsync ) #> <#= methodName #>( + Unpacker unpacker, int itemsCount, T collection, <#= BulkOperationDelegate( "T", isAsync ) #> bulkOperation, <#= EachOperationDelegate( "T", isAsync ) #> eachOperation<#= CancellationTokenParameter( isAsync ) #> + ) { + if ( unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "unpacker" ); + } + if ( collection == null ) { SerializationExceptions.ThrowArgumentNullException( "collection" ); } + var parameters = + new <#= methodName #>Parameters + { + Unpacker = unpacker, + ItemsCount = itemsCount, + Collection = collection, + BulkOperation = bulkOperation, + EachOperation = eachOperation, +<# + if ( isAsync ) + { +#> + CancellationToken = cancellationToken +<# + } +#> + }; + return <#= methodName #>( ref parameters ); + } +<# + } + else // isExpandedParameters + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Avoiding memcpy is critical here." )] + public static <#= TaskT( isAsync ) #> <#= methodName #>( + ref <#= methodName #>Parameters parameter + ) + { + if ( parameter.Unpacker == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Unpacker" ); + } + + if ( parameter.Collection == null ) + { + SerializationExceptions.ThrowArgumentNullException( "parameter", "Collection" ); + } + + return + <#= methodName #>Core( + parameter.Unpacker, + parameter.ItemsCount, + parameter.Collection, + parameter.BulkOperation, + parameter.EachOperation +<# + if ( isAsync ) + { +#> + , parameter.CancellationToken +<# + } +#> + ); + } + + private static <#= AsyncT( isAsync ) #> <#= methodName #>Core( + Unpacker unpacker, int itemsCount, T collection, <#= BulkOperationDelegate( "T", isAsync ) #> bulkOperation, <#= EachOperationDelegate( "T", isAsync ) #> eachOperation<#= CancellationTokenParameter( isAsync ) #> + ) + { // ReSharper disable once RedundantAssignment var ctx = default( UnpackerTraceContext ); InitializeUnpackerTrace( unpacker, ref ctx ); @@ -818,6 +1398,9 @@ foreach ( var isAsync in new [] { false, true } ) } <# + } // isExpandedParameters + } // foreach ( var isExpandedParameters ) + if ( isAsync ) { #> @@ -868,16 +1451,31 @@ private static string SummarySuffix( bool isAsync ) return isAsync ? " asyncronously" : String.Empty; } +private static string TaskVoid( bool isAsync ) +{ + return isAsync ? "Task" : "void"; +} + private static string AsyncVoid( bool isAsync ) { return isAsync ? "async Task" : "void"; } +private static string TaskT( bool isAsync ) +{ + return isAsync ? "Task" : "T"; +} + private static string AsyncT( bool isAsync ) { return isAsync ? "async Task" : "T"; } +private static string TaskTResult( bool isAsync ) +{ + return isAsync ? "Task" : "TResult"; +} + private static string AsyncTResult( bool isAsync ) { return isAsync ? "async Task" : "TResult"; @@ -913,10 +1511,15 @@ private static string ConfigureAwait( bool isAsync ) return isAsync ? ".ConfigureAwait( false )" : String.Empty; } +private static string ReturnVoid( bool isAsync ) +{ + return isAsync ? "return " : String.Empty; +} + private enum TypeKind { Value, Reference, Nullable } -#> \ No newline at end of file +#> diff --git a/src/MsgPack/SetOperation.cs b/src/MsgPack/SetOperation.cs index b7593196a..fb01401fd 100644 --- a/src/MsgPack/SetOperation.cs +++ b/src/MsgPack/SetOperation.cs @@ -25,11 +25,11 @@ #if !UNITY using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; @@ -41,7 +41,7 @@ namespace MsgPack internal static class SetOperation { [Pure] -#if NETFX_35 +#if NET35 public static bool IsProperSubsetOf( ICollection set, IEnumerable other ) #else public static bool IsProperSubsetOf( ISet set, IEnumerable other ) @@ -80,7 +80,7 @@ public static bool IsProperSubsetOf( ISet set, IEnumerable other ) } [Pure] -#if NETFX_35 +#if NET35 public static bool IsSubsetOf( ICollection set, IEnumerable other ) #else public static bool IsSubsetOf( ISet set, IEnumerable other ) @@ -111,7 +111,7 @@ public static bool IsSubsetOf( ISet set, IEnumerable other ) } [Pure] -#if NETFX_35 +#if NET35 private static bool IsSubsetOfCore( ICollection set, IEnumerable other, out int otherCount ) #else private static bool IsSubsetOfCore( ISet set, IEnumerable other, out int otherCount ) @@ -121,7 +121,7 @@ private static bool IsSubsetOfCore( ISet set, IEnumerable other, out in // Other must be set to handle duplicated items. // e.x., [1,2,3] is proper subset of [1,2,3,4,1] but not [1,1,1,1,1] -#if NETFX_35 +#if NET35 var asSet = other as HashSet; #else var asSet = other as ISet; @@ -148,7 +148,7 @@ private static bool IsSubsetOfCore( ISet set, IEnumerable other, out in } [Pure] -#if NETFX_35 +#if NET35 public static bool IsProperSupersetOf( ICollection set, IEnumerable other ) #else public static bool IsProperSupersetOf( ISet set, IEnumerable other ) @@ -182,7 +182,7 @@ public static bool IsProperSupersetOf( ISet set, IEnumerable other ) } [Pure] -#if NETFX_35 +#if NET35 public static bool IsSupersetOf( ICollection set, IEnumerable other ) #else public static bool IsSupersetOf( ISet set, IEnumerable other ) @@ -216,7 +216,7 @@ public static bool IsSupersetOf( ISet set, IEnumerable other ) } [Pure] -#if NETFX_35 +#if NET35 private static bool IsSupersetOfCore( ICollection set, IEnumerable other, out int otherCount ) #else private static bool IsSupersetOfCore( ISet set, IEnumerable other, out int otherCount ) @@ -226,7 +226,7 @@ private static bool IsSupersetOfCore( ISet set, IEnumerable other, out // Other must be set to handle duplicated items. // e.x., [1,2,3] is proper superset of [1,2] and [1,2,1] -#if NETFX_35 +#if NET35 var asSet = other as HashSet; #else var asSet = other as ISet; @@ -251,7 +251,7 @@ private static bool IsSupersetOfCore( ISet set, IEnumerable other, out } [Pure] -#if NETFX_35 +#if NET35 public static bool Overlaps( ICollection set, IEnumerable other ) #else public static bool Overlaps( ISet set, IEnumerable other ) @@ -275,7 +275,7 @@ public static bool Overlaps( ISet set, IEnumerable other ) } [Pure] -#if NETFX_35 +#if NET35 public static bool SetEquals( ICollection set, IEnumerable other ) #else public static bool SetEquals( ISet set, IEnumerable other ) @@ -300,7 +300,7 @@ public static bool SetEquals( ISet set, IEnumerable other ) } // Cannot use other.All() here because it always returns true for empty source. -#if NETFX_35 +#if NET35 var asSet = other as HashSet ?? new HashSet( other ); #else var asSet = other as ISet ?? new HashSet( other ); diff --git a/src/MsgPack/SingleArrayBufferAllocator.cs b/src/MsgPack/SingleArrayBufferAllocator.cs new file mode 100644 index 000000000..a0e6c93be --- /dev/null +++ b/src/MsgPack/SingleArrayBufferAllocator.cs @@ -0,0 +1,70 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; + +namespace MsgPack +{ + /// + /// An implementation of which reallocte a new single array and copy old contents to it. + /// + internal sealed class SingleArrayBufferAllocator : ByteBufferAllocator + { + public static readonly SingleArrayBufferAllocator Default = new SingleArrayBufferAllocator( Allocate ); + + private readonly Func _allocator; + + public SingleArrayBufferAllocator( Func allocator ) + { + this._allocator = allocator; + } + + private static byte[] Allocate( byte[] old, int requestSize ) + { + if ( old.Length < 256 ) + { + return new byte[ 256 ]; + } + + // Use golden ratio to improve linear memory range reusability (of LOH) + var newSize = Math.Max( ( long )( old.Length * 1.1618 ), requestSize + ( long )old.Length ); + if ( newSize > Int32.MaxValue ) + { + return null; + } + + return new byte[ newSize ]; + } + + public override bool TryAllocate( byte[] oldBuffer, int requestSize, out byte[] newBuffer ) + { + newBuffer = this._allocator( oldBuffer, requestSize ); + if ( newBuffer == null || newBuffer.Length < ( oldBuffer.Length + requestSize ) ) + { + newBuffer = null; + return false; + } + + Buffer.BlockCopy( oldBuffer, 0, newBuffer, 0, oldBuffer.Length ); + return true; + } + } +} diff --git a/src/MsgPack/StreamPacker.cs b/src/MsgPack/StreamPacker.cs deleted file mode 100644 index af19e7f2a..000000000 --- a/src/MsgPack/StreamPacker.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2015 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -using System.IO; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - /// - /// Basic implementation using managed . - /// - internal class StreamPacker : Packer - { - private readonly Stream _stream; - private readonly bool _ownsStream; - - public sealed override bool CanSeek - { - get { return this._stream.CanSeek; } - } - - public sealed override long Position - { - get { return this._stream.Position; } - } - - public StreamPacker( Stream stream, PackerCompatibilityOptions compatibilityOptions, PackerUnpackerStreamOptions streamOptions ) - : base( compatibilityOptions ) - { - if ( stream == null ) - { - throw new ArgumentNullException( "stream" ); - } - - var options = streamOptions ?? PackerUnpackerStreamOptions.None; - - this._stream = options.WrapStream( stream ); - - this._ownsStream = options.OwnsStream; - } - - protected sealed override void Dispose( bool disposing ) - { - if ( this._ownsStream ) - { - this._stream.Dispose(); - } - - base.Dispose( disposing ); - } - - protected sealed override void SeekTo( long offset ) - { - if ( !this.CanSeek ) - { - ThrowCannotSeekException(); - } - - this._stream.Seek( offset, SeekOrigin.Current ); - } - - protected sealed override void WriteByte( byte value ) - { - this._stream.WriteByte( value ); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )] - protected sealed override void WriteBytes( byte[] asArray, bool isImmutable ) - { - this._stream.Write( asArray, 0, asArray.Length ); - } - -#if FEATURE_TAP - - protected override Task WriteByteAsync( byte value, CancellationToken cancellationToken ) - { - return this._stream.WriteAsync( new [] { value }, 0, 1, cancellationToken ); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] - protected override Task WriteBytesAsync( byte[] asArray, bool isImmutable, CancellationToken cancellationToken ) - { - return this._stream.WriteAsync( asArray, 0, asArray.Length, cancellationToken ); - } - -#endif // FEATURE_TAP - - private static void ThrowCannotSeekException() - { - throw new NotSupportedException("The underlying stream does not support seeking."); - } - } -} diff --git a/src/MsgPack/SubtreeUnpacker.Unpacking.cs b/src/MsgPack/SubtreeUnpacker.Unpacking.cs index 5ef1816c8..c30625515 100644 --- a/src/MsgPack/SubtreeUnpacker.Unpacking.cs +++ b/src/MsgPack/SubtreeUnpacker.Unpacking.cs @@ -23,8 +23,8 @@ namespace MsgPack { - // This file was generated from SubtreeUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit SubtreeUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude instead. + // This file was generated from SubtreeUnpacker.Unpacking.tt and Core.ttinclude T4Template. + // Do not modify this file. Edit SubtreeUnpacker.Unpacking.tt and Core.ttinclude instead. partial class SubtreeUnpacker { @@ -38,23 +38,23 @@ public override bool ReadBoolean( out Boolean result ) return false; } - if ( !this._root.ReadSubtreeBoolean( out result ) ) + if ( !this._root.ReadBoolean( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -79,23 +79,23 @@ public override bool ReadNullableBoolean( out Boolean? result ) return false; } - if ( !this._root.ReadSubtreeNullableBoolean( out result ) ) + if ( !this._root.ReadNullableBoolean( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -120,23 +120,23 @@ public override bool ReadByte( out Byte result ) return false; } - if ( !this._root.ReadSubtreeByte( out result ) ) + if ( !this._root.ReadByte( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -161,23 +161,23 @@ public override bool ReadNullableByte( out Byte? result ) return false; } - if ( !this._root.ReadSubtreeNullableByte( out result ) ) + if ( !this._root.ReadNullableByte( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -202,23 +202,23 @@ public override bool ReadSByte( out SByte result ) return false; } - if ( !this._root.ReadSubtreeSByte( out result ) ) + if ( !this._root.ReadSByte( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -243,23 +243,23 @@ public override bool ReadNullableSByte( out SByte? result ) return false; } - if ( !this._root.ReadSubtreeNullableSByte( out result ) ) + if ( !this._root.ReadNullableSByte( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -284,23 +284,23 @@ public override bool ReadInt16( out Int16 result ) return false; } - if ( !this._root.ReadSubtreeInt16( out result ) ) + if ( !this._root.ReadInt16( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -325,23 +325,23 @@ public override bool ReadNullableInt16( out Int16? result ) return false; } - if ( !this._root.ReadSubtreeNullableInt16( out result ) ) + if ( !this._root.ReadNullableInt16( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -366,23 +366,23 @@ public override bool ReadUInt16( out UInt16 result ) return false; } - if ( !this._root.ReadSubtreeUInt16( out result ) ) + if ( !this._root.ReadUInt16( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -407,23 +407,23 @@ public override bool ReadNullableUInt16( out UInt16? result ) return false; } - if ( !this._root.ReadSubtreeNullableUInt16( out result ) ) + if ( !this._root.ReadNullableUInt16( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -448,23 +448,23 @@ public override bool ReadInt32( out Int32 result ) return false; } - if ( !this._root.ReadSubtreeInt32( out result ) ) + if ( !this._root.ReadInt32( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -489,23 +489,23 @@ public override bool ReadNullableInt32( out Int32? result ) return false; } - if ( !this._root.ReadSubtreeNullableInt32( out result ) ) + if ( !this._root.ReadNullableInt32( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -530,23 +530,23 @@ public override bool ReadUInt32( out UInt32 result ) return false; } - if ( !this._root.ReadSubtreeUInt32( out result ) ) + if ( !this._root.ReadUInt32( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -571,23 +571,23 @@ public override bool ReadNullableUInt32( out UInt32? result ) return false; } - if ( !this._root.ReadSubtreeNullableUInt32( out result ) ) + if ( !this._root.ReadNullableUInt32( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -612,23 +612,23 @@ public override bool ReadInt64( out Int64 result ) return false; } - if ( !this._root.ReadSubtreeInt64( out result ) ) + if ( !this._root.ReadInt64( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -653,23 +653,23 @@ public override bool ReadNullableInt64( out Int64? result ) return false; } - if ( !this._root.ReadSubtreeNullableInt64( out result ) ) + if ( !this._root.ReadNullableInt64( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -694,23 +694,23 @@ public override bool ReadUInt64( out UInt64 result ) return false; } - if ( !this._root.ReadSubtreeUInt64( out result ) ) + if ( !this._root.ReadUInt64( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -735,23 +735,23 @@ public override bool ReadNullableUInt64( out UInt64? result ) return false; } - if ( !this._root.ReadSubtreeNullableUInt64( out result ) ) + if ( !this._root.ReadNullableUInt64( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -776,23 +776,23 @@ public override bool ReadSingle( out Single result ) return false; } - if ( !this._root.ReadSubtreeSingle( out result ) ) + if ( !this._root.ReadSingle( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -817,23 +817,23 @@ public override bool ReadNullableSingle( out Single? result ) return false; } - if ( !this._root.ReadSubtreeNullableSingle( out result ) ) + if ( !this._root.ReadNullableSingle( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -858,23 +858,23 @@ public override bool ReadDouble( out Double result ) return false; } - if ( !this._root.ReadSubtreeDouble( out result ) ) + if ( !this._root.ReadDouble( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -899,23 +899,23 @@ public override bool ReadNullableDouble( out Double? result ) return false; } - if ( !this._root.ReadSubtreeNullableDouble( out result ) ) + if ( !this._root.ReadNullableDouble( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -941,23 +941,23 @@ public override bool ReadArrayLength( out long result ) return false; } - if ( !this._root.ReadSubtreeArrayLength( out result ) ) + if ( !this._root.ReadArrayLength( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -982,23 +982,23 @@ public override bool ReadMapLength( out long result ) return false; } - if ( !this._root.ReadSubtreeMapLength( out result ) ) + if ( !this._root.ReadMapLength( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -1023,23 +1023,23 @@ public override bool ReadBinary( out byte[] result ) return false; } - if ( !this._root.ReadSubtreeBinary( out result ) ) + if ( !this._root.ReadBinary( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -1064,23 +1064,23 @@ public override bool ReadString( out string result ) return false; } - if ( !this._root.ReadSubtreeString( out result ) ) + if ( !this._root.ReadString( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -1105,23 +1105,23 @@ public override bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedT return false; } - if ( !this._root.ReadSubtreeMessagePackExtendedTypeObject( out result ) ) + if ( !this._root.ReadMessagePackExtendedTypeObject( out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -1146,23 +1146,23 @@ public override bool ReadObject( out MessagePackObject result ) return false; } - if ( !this._root.ReadSubtreeObject( /* isDeep */true, out result ) ) + if ( !this._internalRoot.ReadObject( /* isDeep */true, out result ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; diff --git a/src/MsgPack/SubtreeUnpacker.Unpacking.tt b/src/MsgPack/SubtreeUnpacker.Unpacking.tt index e7e66a95e..3b18d78fb 100644 --- a/src/MsgPack/SubtreeUnpacker.Unpacking.tt +++ b/src/MsgPack/SubtreeUnpacker.Unpacking.tt @@ -32,8 +32,8 @@ using System; namespace MsgPack { - // This file was generated from SubtreeUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit SubtreeUnpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude instead. + // This file was generated from SubtreeUnpacker.Unpacking.tt and Core.ttinclude T4Template. + // Do not modify this file. Edit SubtreeUnpacker.Unpacking.tt and Core.ttinclude instead. partial class SubtreeUnpacker { @@ -140,23 +140,23 @@ if ( this._itemsCount.Count == 0 ) return false; } -if ( !this._root.ReadSubtree<#= typeName #>( <#= isDeep #>out result ) ) +if ( !this._root.Read<#= typeName #>( <#= isDeep #>out result ) ) { return false; } -switch ( this._root.InternalCollectionType ) +switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; diff --git a/src/MsgPack/SubtreeUnpacker.cs b/src/MsgPack/SubtreeUnpacker.cs index dcc67b0d6..18bcaf478 100644 --- a/src/MsgPack/SubtreeUnpacker.cs +++ b/src/MsgPack/SubtreeUnpacker.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; @@ -46,7 +46,8 @@ namespace MsgPack /// internal sealed partial class SubtreeUnpacker : Unpacker { - private readonly ItemsUnpacker _root; + private readonly Unpacker _root; + private readonly IRootUnpacker _internalRoot; private readonly SubtreeUnpacker _parent; private readonly BooleanStack _isMap; private readonly Int64Stack _unpacked; @@ -60,53 +61,51 @@ public override long ItemsCount public override bool IsArrayHeader { - get { return this._root.InternalCollectionType == ItemsUnpacker.CollectionType.Array; } + get { return this._internalRoot.CollectionType == CollectionType.Array; } } public override bool IsMapHeader { - get { return this._root.InternalCollectionType == ItemsUnpacker.CollectionType.Map; } + get { return this._internalRoot.CollectionType == CollectionType.Map; } } public override bool IsCollectionHeader { - get { return this._root.InternalCollectionType != ItemsUnpacker.CollectionType.None; } + get { return this._internalRoot.CollectionType != CollectionType.None; } } [Obsolete( "Consumer should not use this property. Query LastReadData instead." )] public override MessagePackObject? Data { - get { return this._root.InternalData; } - protected set { this._root.InternalData = value.GetValueOrDefault(); } + get { return this._internalRoot.Data; } + protected set { this._internalRoot.Data = value; } } public override MessagePackObject LastReadData { - get { return this._root.InternalData; } - protected set { this._root.InternalData = value; } + get { return this._internalRoot.LastReadData; } + protected set { this._internalRoot.LastReadData = value; } } #if DEBUG internal override long? UnderlyingStreamPosition { - get { return this._root.UnderlyingStreamPosition; } + get { return this._internalRoot.UnderlyingStreamPosition; } } #endif - internal override bool GetPreviousPosition( out long offsetOrPosition ) - { - return this._root.GetPreviousPosition( out offsetOrPosition ); - } - - public SubtreeUnpacker( ItemsUnpacker parent ) : this( parent, null ) { } + public SubtreeUnpacker( Unpacker parent ) : this( parent, null ) { } - private SubtreeUnpacker( ItemsUnpacker root, SubtreeUnpacker parent ) + private SubtreeUnpacker( Unpacker root, SubtreeUnpacker parent ) { + var internalRoot = root as IRootUnpacker; #if DEBUG Contract.Assert( root != null, "root != null" ); - Contract.Assert( root.IsArrayHeader || root.IsMapHeader, "root.IsArrayHeader || root.IsMapHeader" ); + Contract.Assert( internalRoot != null, "root is IRootUnpacker" ); + Contract.Assert( internalRoot.CollectionType == CollectionType.Array || internalRoot.CollectionType == CollectionType.Map, "root.IsArrayHeader || root.IsMapHeader" ); #endif // DEBUG this._root = root; + this._internalRoot = internalRoot; this._parent = parent; this._unpacked = new Int64Stack( 2 ); @@ -115,9 +114,9 @@ private SubtreeUnpacker( ItemsUnpacker root, SubtreeUnpacker parent ) if ( root.ItemsCount > 0 ) { - this._itemsCount.Push( root.InternalItemsCount * ( ( int )root.InternalCollectionType ) ); + this._itemsCount.Push( root.ItemsCount * ( ( int )internalRoot.CollectionType ) ); this._unpacked.Push( 0 ); - this._isMap.Push( root.InternalCollectionType == ItemsUnpacker.CollectionType.Map ); + this._isMap.Push( internalRoot.CollectionType == CollectionType.Map ); } this._state = State.InHead; @@ -204,7 +203,7 @@ protected override Unpacker ReadSubtreeCore() ThrowInTailException(); } - if ( this._root.InternalCollectionType == ItemsUnpacker.CollectionType.None ) + if ( this._internalRoot.CollectionType == CollectionType.None ) { ThrowNotInHeadOfCollectionException(); } @@ -226,23 +225,23 @@ protected override bool ReadCore() { this.DiscardCompletedStacks(); - if ( this._itemsCount.Count == 0 || !this._root.ReadSubtreeItem() ) + if ( this._itemsCount.Count == 0 || !this._root.ReadInternal() ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -264,23 +263,23 @@ protected override async Task ReadAsyncCore( CancellationToken cancellatio { this.DiscardCompletedStacks(); - if ( this._itemsCount.Count == 0 || !( await this._root.ReadSubtreeItemAsync( cancellationToken ).ConfigureAwait( false ) ) ) + if ( this._itemsCount.Count == 0 || !( await this._root.ReadInternalAsync( cancellationToken ).ConfigureAwait( false ) ) ) { return false; } - switch ( this._root.InternalCollectionType ) + switch ( this._internalRoot.CollectionType ) { - case ItemsUnpacker.CollectionType.Array: + case CollectionType.Array: { - this._itemsCount.Push( this._root.InternalItemsCount ); + this._itemsCount.Push( this._root.ItemsCount ); this._unpacked.Push( 0 ); this._isMap.Push( false ); break; } - case ItemsUnpacker.CollectionType.Map: + case CollectionType.Map: { - this._itemsCount.Push( this._root.InternalItemsCount * 2 ); + this._itemsCount.Push( this._root.ItemsCount * 2 ); this._unpacked.Push( 0 ); this._isMap.Push( true ); break; @@ -307,7 +306,7 @@ protected override async Task ReadAsyncCore( CancellationToken cancellatio return 0; } - var result = this._root.SkipSubtreeItem(); + var result = this._root.Skip(); if ( result != null ) { this._unpacked.Push( this._unpacked.Pop() + 1 ); @@ -327,7 +326,7 @@ protected override async Task ReadAsyncCore( CancellationToken cancellatio return 0; } - var result = await this._root.SkipSubtreeItemAsync( cancellationToken ).ConfigureAwait( false ); + var result = await this._root.SkipAsync( cancellationToken ).ConfigureAwait( false ); if ( result != null ) { this._unpacked.Push( this._unpacked.Pop() + 1 ); diff --git a/src/MsgPack/TaskAugument.cs b/src/MsgPack/TaskAugument.cs new file mode 100644 index 000000000..ad90d16e7 --- /dev/null +++ b/src/MsgPack/TaskAugument.cs @@ -0,0 +1,45 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Threading.Tasks; + +namespace MsgPack +{ + /// + /// Auguments for class. + /// + internal static class TaskAugument + { + public static Task CompletedTask + { + get + { +#if NET45 || NETSTANDARD1_1 + var tcs = new TaskCompletionSource(); + tcs.SetResult( null ); + return tcs.Task; +#else + return Task.CompletedTask; +#endif // NET45 || NETSTANDARD1_1 + } + } + } +} diff --git a/src/MsgPack/Timestamp.Calculation.cs b/src/MsgPack/Timestamp.Calculation.cs new file mode 100644 index 000000000..67f55ef9b --- /dev/null +++ b/src/MsgPack/Timestamp.Calculation.cs @@ -0,0 +1,240 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +#if !NET35 && !UNITY +#if !WINDOWS_PHONE +#if !UNITY || MSGPACK_UNITY_FULL +using System.Numerics; +#endif // !WINDOWS_PHONE +#endif // !UNITY || MSGPACK_UNITY_FULL +#endif // !NET35 && !UNITY + +namespace MsgPack +{ + partial struct Timestamp + { +#if !NET35 && !UNITY +#if !WINDOWS_PHONE +#if !UNITY || MSGPACK_UNITY_FULL + private static readonly BigInteger NanoToSecondsAsBigInteger = new BigInteger( 1000 * 1000 * 1000 ); +#endif // !WINDOWS_PHONE +#endif // !UNITY || MSGPACK_UNITY_FULL +#endif // !NET35 && !UNITY + + /// + /// Adds a specified to this instance. + /// + /// A which represents offset. Note that this value can be negative. + /// The result . + /// + /// The result of calculation overflows or underflows . + /// + public Timestamp Add( TimeSpan offset ) + { + long secondsOffset; + int nanosOffset; + FromOffsetTicks( offset.Ticks, out secondsOffset, out nanosOffset ); + var seconds = checked( this.unixEpochSeconds + secondsOffset ); + var nanos = this.nanoseconds + nanosOffset; + if ( nanos > MaxNanoSeconds ) + { + checked + { + seconds++; + } + nanos -= ( MaxNanoSeconds + 1 ); + } + else if ( nanos < 0 ) + { + checked + { + seconds--; + } + nanos = ( MaxNanoSeconds + 1 ) + nanos; + } + + return new Timestamp( seconds, unchecked(( int )nanos) ); + } + + /// + /// Subtracts a specified from this instance. + /// + /// A which represents offset. Note that this value can be negative. + /// The result . + /// + /// The result of calculation overflows or underflows . + /// + public Timestamp Subtract( TimeSpan offset ) + { + return this.Add( -offset ); + } + +#if !NET35 && !UNITY +#if !WINDOWS_PHONE +#if !UNITY || MSGPACK_UNITY_FULL + + /// + /// Adds a specified nanoseconds represented as a from this instance. + /// + /// A which represents offset. Note that this value can be negative. + /// The result . + /// + /// The result of calculation overflows or underflows . + /// + public Timestamp Add( BigInteger offsetNanoseconds ) + { + BigInteger nanosecondsOffset; + var secondsOffset = ( long )BigInteger.DivRem( offsetNanoseconds, NanoToSecondsAsBigInteger, out nanosecondsOffset ); + + var seconds = checked( this.unixEpochSeconds + secondsOffset ); + var nanos = this.nanoseconds + unchecked( ( int )nanosecondsOffset ); + if ( nanos > MaxNanoSeconds ) + { + checked + { + seconds++; + } + nanos -= ( MaxNanoSeconds + 1 ); + } + else if ( nanos < 0 ) + { + checked + { + seconds--; + } + nanos = ( MaxNanoSeconds + 1 ) + nanos; + } + + return new Timestamp( seconds, unchecked(( int )nanos) ); + } + + /// + /// Subtracts a specified nanoseconds represented as a from this instance. + /// + /// A which represents offset. Note that this value can be negative. + /// The result . + /// + /// The result of calculation overflows or underflows . + /// + public Timestamp Subtract( BigInteger offsetNanoseconds ) + { + return this.Add( -offsetNanoseconds ); + } + + /// + /// Calculates a difference this instance and a specified in nanoseconds. + /// + /// A to be differentiated. + /// A which represents difference in nanoseconds. + public BigInteger Subtract( Timestamp other ) + { + var seconds = new BigInteger( this.unixEpochSeconds ) - other.unixEpochSeconds; + var nanos = ( long )this.nanoseconds - other.nanoseconds; +#if DEBUG + Contract.Assert( nanos <= MaxNanoSeconds, nanos + " <= MaxNanoSeconds" ); +#endif // DEBUG + if ( nanos < 0 ) + { + // move down + seconds--; + nanos = ( MaxNanoSeconds + 1 ) + nanos; + } + + return seconds * SecondsToNanos + nanos; + } + +#endif // !WINDOWS_PHONE +#endif // !UNITY || MSGPACK_UNITY_FULL +#endif // !NET35 && !UNITY + + /// + /// Calculates a with specified and an offset represented as . + /// + /// A . + /// An offset in . This value can be negative. + /// A . + public static Timestamp operator +( Timestamp value, TimeSpan offset ) + { + return value.Add( offset ); + } + + /// + /// Calculates a with specified and an offset represented as . + /// + /// A . + /// An offset in . This value can be negative. + /// A . + public static Timestamp operator -( Timestamp value, TimeSpan offset ) + { + return value.Subtract( offset ); + } + +#if !NET35 && !UNITY +#if !WINDOWS_PHONE +#if !UNITY || MSGPACK_UNITY_FULL + + /// + /// Calculates a with specified and a nanoseconds offset represented as . + /// + /// A . + /// An offset in nanoseconds as . This value can be negative. + /// A . + public static Timestamp operator +( Timestamp value, BigInteger offsetNanoseconds ) + { + return value.Add( offsetNanoseconds ); + } + + /// + /// Calculates a with specified and a nanoseconds represented as . + /// + /// A . + /// An offset in nanoseconds as . This value can be negative. + /// A . + public static Timestamp operator -( Timestamp value, BigInteger offsetNanoseconds ) + { + return value.Subtract( offsetNanoseconds ); + } + + /// + /// Calculates a difference between specified two s in nanoseconds. + /// + /// A . + /// A . + /// A which represents difference in nanoseconds. + public static BigInteger operator -( Timestamp left, Timestamp right ) + { + return left.Subtract( right ); + } + +#endif // !WINDOWS_PHONE +#endif // !UNITY || MSGPACK_UNITY_FULL +#endif // !NET35 && !UNITY + } +} diff --git a/src/MsgPack/Timestamp.Comparison.cs b/src/MsgPack/Timestamp.Comparison.cs new file mode 100644 index 000000000..f92f05e18 --- /dev/null +++ b/src/MsgPack/Timestamp.Comparison.cs @@ -0,0 +1,213 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + partial struct Timestamp : IComparable, IEquatable , IComparable + { + /// + /// Compares this instance to the specified . + /// + /// A to be compared. + /// + /// If this instance is greater than the , then 1. + /// If this instance is less than the , then -1. + /// Else, this instance is equal to the , then 0. + /// + public int CompareTo( Timestamp other ) + { + var result = this.unixEpochSeconds.CompareTo( other.unixEpochSeconds ); + if ( result != 0 ) + { + return result; + } + + return this.nanoseconds.CompareTo( other.nanoseconds ); + } + + /// + /// Compares two instances. + /// + /// A to be compared. + /// A to be compared. + /// + /// If the is greater than the , then 1. + /// If the is less than the , then -1. + /// Else, the is equal to the , then 0. + /// + public static int Compare( Timestamp left, Timestamp right ) + { + return left.CompareTo( right ); + } + + /// + /// Compares this instance to the specified object. + /// + /// An to be compared. + /// + /// If this instance is greater than the or the is null, then 1. + /// If this instance is less than the , then -1. + /// Else, this instance is equal to the , then 0. + /// + /// + /// is not a boxed . + /// + int IComparable.CompareTo( object obj ) + { + if ( obj == null ) + { + return 1; + } + + if ( !( obj is Timestamp ) ) + { + throw new ArgumentException( "obj is not MsgPack.Timestamp object.", "obj" ); + } + + return this.CompareTo( ( Timestamp )obj ); + } + + /// + /// Determines the specified is equal to this instance. + /// + /// An to be compared. + /// + /// true, if the is boxed and its value is equal to this instance; + /// otherwise, false. + /// + public override bool Equals( object obj ) + { + if ( !( obj is Timestamp ) ) + { + return false; + } + + return this.Equals( ( Timestamp )obj ); + } + + /// + /// Determines the specified is equal to this instance. + /// + /// A to be compared. + /// + /// true, if the is equal to this instance; + /// otherwise, false. + /// + public bool Equals( Timestamp other ) + { + return this.unixEpochSeconds == other.unixEpochSeconds && this.nanoseconds == other.nanoseconds; + } + + /// + /// Gets a hash code of this instance. + /// + /// A hash code of this instance. + public override int GetHashCode() + { + return this.unixEpochSeconds.GetHashCode() ^ this.nanoseconds.GetHashCode(); + } + + /// + /// Determines the is greater than the . + /// + /// A . + /// A . + /// + /// true, if is greater than the ; + /// Otherwise, false. + /// + public static bool operator >( Timestamp left, Timestamp right ) + { + return left.CompareTo( right ) > 0; + } + + /// + /// Determines the is less than the . + /// + /// A . + /// A . + /// + /// true, if is less than the ; + /// Otherwise, false. + /// + public static bool operator <( Timestamp left, Timestamp right ) + { + return left.CompareTo( right ) < 0; + } + + /// + /// Determines the is greater than or equal to the . + /// + /// A . + /// A . + /// + /// true, if is greater than or equal to the ; + /// Otherwise, false. + /// + public static bool operator >=( Timestamp left, Timestamp right ) + { + return left.CompareTo( right ) >= 0; + } + + /// + /// Determines the is less than or equal to the . + /// + /// A . + /// A . + /// + /// true, if is less than or equal to the ; + /// Otherwise, false. + /// + public static bool operator <=( Timestamp left, Timestamp right ) + { + return left.CompareTo( right ) <= 0; + } + + /// + /// Determines two instances are equal. + /// + /// A . + /// A . + /// + /// true, if is equal to ; + /// Otherwise, false. + /// + public static bool operator ==( Timestamp left, Timestamp right ) + { + return left.Equals( right ); + } + + /// + /// Determines two instances are not equal. + /// + /// A . + /// A . + /// + /// true, if is not equal to ; + /// Otherwise, false. + /// + public static bool operator !=( Timestamp left, Timestamp right ) + { + return !left.Equals( right ); + } + } +} diff --git a/src/MsgPack/Timestamp.Conversion.cs b/src/MsgPack/Timestamp.Conversion.cs new file mode 100644 index 000000000..56b28063c --- /dev/null +++ b/src/MsgPack/Timestamp.Conversion.cs @@ -0,0 +1,297 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Globalization; + +namespace MsgPack +{ + partial struct Timestamp + { + private long ToTicks( Type destination ) + { + if ( this.unixEpochSeconds < MinUnixEpochSecondsForTicks ) + { + throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "This value is too small for '{0}'.", destination ) ); + } + + if ( this.unixEpochSeconds > MaxUnixEpochSecondsForTicks ) + { + throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "This value is too large for '{0}'.", destination ) ); + } + + return ( UnixEpochInSeconds + this.unixEpochSeconds ) * SecondsToTicks + this.nanoseconds / NanoToTicks; + } + + /// + /// Converts this instance to equivalant instance with . + /// + /// An equivalant instance with . + /// + /// This instance represents before or after . + /// + public DateTime ToDateTime() + { + return new DateTime( this.ToTicks( typeof( DateTime ) ), DateTimeKind.Utc ); + } + + /// + /// Converts this instance to equivalant instance with offset 0. + /// + /// An equivalant instance with offset 0 + /// + /// This instance represents before or after . + /// + public DateTimeOffset ToDateTimeOffset() + { + return new DateTimeOffset( this.ToTicks( typeof( DateTimeOffset ) ), TimeSpan.Zero ); + } + + /// + /// Encodes this instance to a . + /// + /// A which equivalant to this instance. + public MessagePackExtendedTypeObject Encode() + { + if ( ( this.unixEpochSeconds >> 34 ) != 0 ) + { + // timestamp 96 + var value = this; + var body = new byte[ 12 ]; + body[ 0 ] = unchecked( ( byte )( ( this.nanoseconds >> 24 ) & 0xFF ) ); + body[ 1 ] = unchecked( ( byte )( ( this.nanoseconds >> 16 ) & 0xFF ) ); + body[ 2 ] = unchecked( ( byte )( ( this.nanoseconds >> 8 ) & 0xFF ) ); + body[ 3 ] = unchecked( ( byte )( ( this.nanoseconds ) & 0xFF ) ); + body[ 4 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 56 ) & 0xFF ) ); + body[ 5 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 48 ) & 0xFF ) ); + body[ 6 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 40 ) & 0xFF ) ); + body[ 7 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 32 ) & 0xFF ) ); + body[ 8 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 24 ) & 0xFF ) ); + body[ 9 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 16 ) & 0xFF ) ); + body[ 10 ] = unchecked( ( byte )( ( this.unixEpochSeconds >> 8 ) & 0xFF ) ); + body[ 11 ] = unchecked( ( byte )( this.unixEpochSeconds & 0xFF ) ); + + return MessagePackExtendedTypeObject.Unpack( TypeCode, body ); + } + else + { + var encoded = ( ( ( ulong )this.nanoseconds ) << 34 ) | unchecked( ( ulong )this.unixEpochSeconds ); + if ( ( encoded & 0xFFFFFFFF00000000L ) == 0 ) + { + // timestamp 32 + var value = unchecked( ( uint )encoded ); + var body = new byte[ 4 ]; + body[ 0 ] = unchecked( ( byte )( ( encoded >> 24 ) & 0xFF ) ); + body[ 1 ] = unchecked( ( byte )( ( encoded >> 16 ) & 0xFF ) ); + body[ 2 ] = unchecked( ( byte )( ( encoded >> 8 ) & 0xFF ) ); + body[ 3 ] = unchecked( ( byte )( encoded & 0xFF ) ); + + return MessagePackExtendedTypeObject.Unpack( TypeCode, body ); + } + else + { + // timestamp 64 + var body = new byte[ 8 ]; + body[ 0 ] = unchecked( ( byte )( ( encoded >> 56 ) & 0xFF ) ); + body[ 1 ] = unchecked( ( byte )( ( encoded >> 48 ) & 0xFF ) ); + body[ 2 ] = unchecked( ( byte )( ( encoded >> 40 ) & 0xFF ) ); + body[ 3 ] = unchecked( ( byte )( ( encoded >> 32 ) & 0xFF ) ); + body[ 4 ] = unchecked( ( byte )( ( encoded >> 24 ) & 0xFF ) ); + body[ 5 ] = unchecked( ( byte )( ( encoded >> 16 ) & 0xFF ) ); + body[ 6 ] = unchecked( ( byte )( ( encoded >> 8 ) & 0xFF ) ); + body[ 7 ] = unchecked( ( byte )( encoded & 0xFF ) ); + + return MessagePackExtendedTypeObject.Unpack( TypeCode, body ); + } + } + } + + private static void FromDateTimeTicks( long ticks, out long unixEpocSeconds, out int nanoSeconds ) + { + FromOffsetTicks( ticks - UnixEpochTicks, out unixEpocSeconds, out nanoSeconds ); + } + + private static void FromOffsetTicks( long ticks, out long unixEpocSeconds, out int nanoSeconds ) + { + long remaining; + unixEpocSeconds = DivRem( ticks, SecondsToTicks, out remaining ); + nanoSeconds = unchecked( ( int )remaining ) * 100; + if ( nanoSeconds < 0 ) + { + // In this case, we must adjust these values + // from "negative nanosec from nearest larger negative integer" + // to "positive nanosec from nearest smaller nagative integer". + unixEpocSeconds -= 1; + nanoSeconds = ( MaxNanoSeconds + 1 ) + nanoSeconds; + } + } + + /// + /// Gets an equivalant to specified . + /// + /// A . + /// An equivalant to specified + public static Timestamp FromDateTime( DateTime value ) + { + long unixEpocSeconds; + int nanoSeconds; + FromDateTimeTicks( ( value.Kind == DateTimeKind.Local ? value.ToUniversalTime() : value ).Ticks, out unixEpocSeconds, out nanoSeconds ); + return new Timestamp( unixEpocSeconds, nanoSeconds ); + } + + /// + /// Gets an equivalant to specified . + /// + /// A . + /// An equivalant to specified + public static Timestamp FromDateTimeOffset( DateTimeOffset value ) + { + long unixEpocSeconds; + int nanoSeconds; + FromDateTimeTicks( value.UtcTicks, out unixEpocSeconds, out nanoSeconds ); + return new Timestamp( unixEpocSeconds, nanoSeconds ); + } + + /// + /// Decodes specified and returns an equivalant . + /// + /// which is native representation of . + /// . + /// + /// does not represent msgpack timestamp. Specifically, the type code is not equal to value. + /// Or, does not have valid msgpack timestamp structure. + /// + /// + /// have invalid nanoseconds value. + /// + /// + /// A definition of valid msgpack time stamp is: + /// + /// Its type code is 0xFF(-1). + /// Its length is 4, 8, or 12 bytes. + /// Its nanoseconds part is between 0 and 999,999,999. + /// + /// + public static Timestamp Decode( MessagePackExtendedTypeObject value ) + { + if ( value.TypeCode != TypeCode ) + { + throw new ArgumentException( "The value's type code must be 0xFF.", "value" ); + } + + switch( value.Body.Length ) + { + case 4: + { + // timespan32 format + return new Timestamp( BigEndianBinary.ToUInt32( value.Body, 0 ), 0 ); + } + case 8: + { + // timespan64 format + var payload = BigEndianBinary.ToUInt64( value.Body, 0 ); + return new Timestamp( unchecked( ( long )( payload & 0x00000003ffffffffL ) ), unchecked( ( int )( payload >> 34 ) ) ); + } + case 12: + { + // timespan96 format + return new Timestamp( BigEndianBinary.ToInt64( value.Body, sizeof( int ) ), unchecked( ( int )BigEndianBinary.ToUInt32( value.Body, 0 ) ) ); + } + default: + { + throw new ArgumentException( "The value's length is not valid.", "value" ); + } + } + } + + /// + /// Converts a value to a value with . + /// + /// A . + /// A with . + /// + /// This instance represents before or after . + /// + public static explicit operator DateTime( Timestamp value ) + { + return value.ToDateTime(); + } + + /// + /// Converts a value to a value with offset 0. + /// + /// A . + /// A value with offset 0. + /// + /// This instance represents before or after . + /// + public static explicit operator DateTimeOffset( Timestamp value ) + { + return value.ToDateTimeOffset(); + } + + /// + /// Converts a value to a . + /// + /// A . + /// A . + public static implicit operator MessagePackExtendedTypeObject( Timestamp value ) + { + return value.Encode(); + } + + /// + /// Converts a value to a . + /// + /// A . + /// A . + public static implicit operator Timestamp( DateTime value ) + { + return FromDateTime( value ); + } + + /// + /// Converts a value to a . + /// + /// A . + /// A . + public static implicit operator Timestamp( DateTimeOffset value ) + { + return FromDateTimeOffset( value ); + } + + /// + /// Converts a value to a . + /// + /// A . + /// A . + /// + /// does not represent msgpack timestamp. Specifically, the type code is not equal to value. + /// Or, does not have valid msgpack timestamp structure. + /// + /// + /// have invalid nanoseconds value. + /// + public static explicit operator Timestamp( MessagePackExtendedTypeObject value ) + { + return Decode( value ); + } + } +} diff --git a/src/MsgPack/Timestamp.ParseExact.cs b/src/MsgPack/Timestamp.ParseExact.cs new file mode 100644 index 000000000..36347ce13 --- /dev/null +++ b/src/MsgPack/Timestamp.ParseExact.cs @@ -0,0 +1,324 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; + +namespace MsgPack +{ + partial struct Timestamp + { + /// + /// Converts specified representation of a msgpack timestamp to its equivalant + /// with specified format and culture-specific format information provider. + /// + /// An input representation of a msgpack timestamp. The format must be match exactly to the . + /// An expected format string. + /// An to provide culture specific information to parse . + /// The converted . + /// + /// + /// Currently, supported date-time format is only 'o' and 'O' (round-trip) or 's' (sortable, ISO-8601). + /// Other any standard date-time formats and custom date-time formats are not supported. + /// + /// + /// The rount-trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff which "fffffffff" is nanoseconds. + /// + /// + /// The sign mark can be culture-specific, and leading/trailing whitespaces can be allowed when specify appropriate . + /// + /// + /// + /// is null. + /// Or, is null. + /// + /// + /// The specified is not supported. + /// + /// + /// The specified is not valid for the specified and . + /// + public static Timestamp ParseExact( string input, string format, IFormatProvider formatProvider ) + { + return ParseExact( input, format, formatProvider, DateTimeStyles.None ); + } + + /// + /// Converts specified representation of a msgpack timestamp to its equivalant + /// with specified format, culture-specific format information provider, and . + /// + /// An input representation of a msgpack timestamp. The format must be match exactly to the . + /// An expected format string. + /// An to provide culture specific information to parse . + /// + /// Specify bitwise value combination of to control detailed parsing behavior. + /// The typical value is . + /// + /// The converted . + /// + /// + /// Currently, supported date-time format is only 'o' and 'O' (round-trip) or 's' (sortable, ISO-8601). + /// Other any standard date-time formats and custom date-time formats are not supported. + /// + /// + /// The rount-trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff which "fffffffff" is nanoseconds. + /// + /// + /// The sign mark can be culture-specific, and leading/trailing whitespaces can be allowed when specify appropriate . + /// + /// + /// + /// is null. + /// Or, is null. + /// + /// + /// The specified is not supported. + /// Or the specified has invalid combination. + /// + /// + /// The specified is not valid for the specified , , and . + /// + public static Timestamp ParseExact( string input, string format, IFormatProvider formatProvider, DateTimeStyles styles ) + { + Timestamp result; + HandleParseResult( TryParseExactCore( input, format, formatProvider, styles, out result ), "Cannot parse specified input with specified format." ); + return result; + } + + /// + /// Converts specified representation of a msgpack timestamp to its equivalant + /// with specified format, culture-specific format information provider, and . + /// + /// The input representation of a msgpack timestamp. The format must be match exactly to one of the . + /// The array of expected format strings. Unsupported format will be ignored. + /// The culture specific information to control + /// + /// Specify bitwise value combination of to control detailed parsing behavior. + /// The typical value is . + /// + /// The converted . + /// + /// + /// Currently, supported date-time format is only 'o' and 'O' (round-trip) or 's' (sortable, ISO-8601). + /// Other any standard date-time formats and custom date-time formats are not supported. + /// + /// + /// The rount-trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff which "fffffffff" is nanoseconds. + /// + /// + /// The sign mark can be culture-specific, and leading/trailing whitespaces can be allowed when specify appropriate . + /// + /// + /// + /// is null. + /// Or, is null. + /// + /// + /// The specified is empty. + /// Or the specified has invalid combination. + /// + /// + /// The specified is not valid for any specified , , and . + /// + public static Timestamp ParseExact( string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles ) + { + Timestamp result; + HandleParseResult( TryParseExactCore( input, formats, formatProvider, styles, out result ), "Cannot parse specified input with any specified formats." ); + return result; + } + + private static void HandleParseResult( TimestampParseResult result, string messageForInvalidInput ) + { + if ( result == TimestampParseResult.Success ) + { + return; + } + + string parameterName; + string message; + + var parameter = result & TimestampParseResult.ParameterMask; + switch( parameter ) + { + case TimestampParseResult.ParameterFormat: + { + parameterName = "format"; + break; + } + default: + { + Contract.Assert( parameter == TimestampParseResult.ParameterInput, parameter + " == TimestampParseResult.Input" ); + parameterName = "input"; + break; + } + } + + var kind = result & TimestampParseResult.KindMask; + + switch ( kind ) + { + case TimestampParseResult.KindEmpty: + { + message = String.Format( CultureInfo.CurrentCulture, "'{0}' must not be empty.", parameterName ); + break; + } + case TimestampParseResult.KindExtraCharactors: + { + message = "The input contains extra charactors."; + break; + } + case TimestampParseResult.KindInvalidDateTimeDelimiter: + { + message = "A date-time delimiter of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidDay: + { + message = "Format of the day portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidHour: + { + message = "Format of the hour portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidHourMinuteDelimiter: + { + message = "A hour-miniute delimiter of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidMinute: + { + message = "Format of the minute portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidMinuteSecondDelimiter: + { + message = "A miniute-second delimiter of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidMonth: + { + message = "Format of the month portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidMonthDayDelimiter: + { + message = "A month-day delimiter of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidNanoSecond: + { + message = "Format of the nanosecond portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidSecond: + { + message = "Format of the second portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidSubsecondDelimiter: + { + message = "A second-nanosecond delimiter of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidYear: + { + message = "Format of the year portion of the input is not valid."; + break; + } + case TimestampParseResult.KindInvalidYearMonthDeilimiter: + { + message = "A year-month delimiter of the input is not valid."; + break; + } + case TimestampParseResult.KindLeadingWhitespaceNotSupported: + { + message = "Leading whitespaces in the input is not allowed."; + break; + } + case TimestampParseResult.KindMissingUtcSign: + { + message = "No time offset specifier 'Z' is missing in the input."; + break; + } + case TimestampParseResult.KindNull: + { + Contract.Assert( + ( result & TimestampParseResult.ExceptionTypeMask ) == TimestampParseResult.ArgumentNullException, + ( result & TimestampParseResult.ExceptionTypeMask ) + " == TimestampParseResult.ArgumentNullException" + ); + message = null; + break; + } + case TimestampParseResult.KindTrailingWhitespaceNotSupported: + { + message = "Trailing whitespaces in the input is not allowed."; + break; + } + case TimestampParseResult.KindUnsupported: + { + message = "The specified format is not supported."; + break; + } + case TimestampParseResult.KindYearOutOfRange: + { + message = "The specified year is too small or too large."; + break; + } + default: + { + Contract.Assert( kind == TimestampParseResult.KindNoMatchedFormats, kind + " == TimestampParseResult.KindNoMatchedFormats" ); + message = "The input is not valid Timestamp."; + break; + } + } + + switch( result & TimestampParseResult.ExceptionTypeMask ) + { + case TimestampParseResult.ArgumentNullException: + { + throw new ArgumentNullException( parameterName ); + } + case TimestampParseResult.ArgumentException: + { + throw new ArgumentException( message, parameterName ); + } + default: + { + Contract.Assert( + ( result & TimestampParseResult.ExceptionTypeMask ) == TimestampParseResult.FormatException, + ( result & TimestampParseResult.ExceptionTypeMask ) + " == TimestampParseResult.FormatException" + ); + throw new FormatException( message ); + } + } + } + } +} diff --git a/src/MsgPack/Timestamp.Properties.cs b/src/MsgPack/Timestamp.Properties.cs new file mode 100644 index 000000000..a42f82453 --- /dev/null +++ b/src/MsgPack/Timestamp.Properties.cs @@ -0,0 +1,502 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT + +namespace MsgPack +{ + partial struct Timestamp + { + private const int SecondsPerMinutes = 60; + private const int SecondsPerHours = SecondsPerMinutes * 60; + private const int SecondsPerDay = SecondsPerHours * 24; + + private const int DaysPerYear = 365; + private const int DaysPer4Years = DaysPerYear * 4 + 1; + private const int DaysPer100Years = DaysPer4Years * 25 - 1; + private const int DaysPer400Years = DaysPer100Years * 4 + 1; + + private const int DayOfWeekOfEpoc = 4; // day of week of 1970-01-01 + + private static readonly uint[] DaysToMonth365 = new uint[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; + private static readonly uint[] DaysToMonth366 = new uint[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; + private static readonly uint[] ReversedDaysToMonth365 = new uint[] { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 334, 365 }; + private static readonly uint[] ReversedDaysToMonth366 = new uint[] { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 335, 366 }; + + /// + /// Gets a unix epoch seconds part of msgpack timestamp spec. + /// + /// A value of unix epoch seconds part of msgpack timestamp spec. This value may be negative, BC dates, and dates after 9999-12-31. + /// + /// If you want to get "nanosecond" portion of this instance, use property instead. + /// + public long UnixEpochSecondsPart + { + get { return this.unixEpochSeconds; } + } + + /// + /// Gets a nanoseconds part of msgpack timestamp spec. + /// + /// A value of nanoseconds part of msgpack timestamp spec. This value will be between 0 to 999,999,999. + /// + /// If you want to get "nanosecond" portion of this instance, use property instead. + /// + public int NanosecondsPart + { + get { return unchecked( ( int )this.nanoseconds ); } + } + + /// + /// Gets an year portion of this instance. + /// + /// An year portion of this instance. The value may be zero or negative, and may exceed 9,999. + public long Year + { + get + { + long year; + int month, day, dayOfYear; + this.GetDatePart( out year, out month, out day, out dayOfYear ); + return year; + } + } + + /// + /// Gets a month portion of this instance. + /// + /// A month portion of this instance. The value will be between 1 and 12. + public int Month + { + get + { + long year; + int month, day, dayOfYear; + this.GetDatePart( out year, out month, out day, out dayOfYear ); + return month; + } + } + + /// + /// Gets a day portion of this instance. + /// + /// A day portion of this instance. The value will be valid day of . + public int Day + { + get + { + long year; + int month, day, dayOfYear; + this.GetDatePart( out year, out month, out day, out dayOfYear ); + return day; + } + } + + /// + /// Gets an hour portion of this instance. + /// + /// An hour portion of this instance. The value will be between 0 and 59. + public int Hour + { + get + { + long remainder; + var hour = DivRem( this.unixEpochSeconds, SecondsPerHours, out remainder ) % 24; + unchecked + { + return + ( int )( this.unixEpochSeconds < 0 + ? hour + ( remainder != 0 ? 23 : ( hour < 0 ? 24 : 0 ) ) + : hour + ); + } + } + } + + /// + /// Gets a minute portion of this instance. + /// + /// A minute portion of this instance. The value will be between 0 and 59. + public int Minute + { + get + { + long remainder; + var minute = DivRem( this.unixEpochSeconds, SecondsPerMinutes, out remainder ) % 60; + unchecked + { + return + ( int )( this.unixEpochSeconds < 0 + ? minute + ( remainder != 0 ? 59 : ( minute < 0 ? 60 : 0 ) ) + : minute + ); + } + } + } + + /// + /// Gets a second portion of this instance. + /// + /// A second portion of this instance. The value will be between 0 and 59. + public int Second + { + get + { + var second = unchecked( ( int )( this.unixEpochSeconds % 60 ) ); + return second < 0 ? second + 60 : second; + } + } + + /// + /// Gets a millisecond portion of this instance. + /// + /// A millisecond portion of this instance. The value will be between 0 and 999. + public int Millisecond + { + get { return this.NanosecondsPart / ( 1000 * 1000 ); } + } + + /// + /// Gets a microsecond portion of this instance. + /// + /// A microsecond portion of this instance. The value will be between 0 and 999. + public int Microsecond + { + get { return ( this.NanosecondsPart / 1000 ) % 1000; } + } + + /// + /// Gets a nanosecond portion of this instance. + /// + /// A nanosecond portion of this instance. The value will be between 0 and 999. + /// + /// If you want to get "nanoseconds" part of msgpack timestamp spec, use property instead. + /// + public int Nanosecond + { + get { return ( this.NanosecondsPart ) % 1000; } + } + + /// + /// Gets a which only contains date portion of this instance. + /// + /// A which only contains date portion of this instance. + public Timestamp Date + { + get + { + return new Timestamp( this.unixEpochSeconds - this.TimeOfDay.unixEpochSeconds, 0 ); + } + } + + /// + /// Gets a which only contains time portion of this instance. + /// + /// A which only contains time portion of this instance. + public Timestamp TimeOfDay + { + get + { + return + new Timestamp( + this.unixEpochSeconds < 0 ? ( this.unixEpochSeconds % SecondsPerDay + SecondsPerDay ) : ( this.unixEpochSeconds % SecondsPerDay ), + this.NanosecondsPart + ); + } + } + + /// + /// Gets a of this day. + /// + /// A of this day. + public DayOfWeek DayOfWeek + { + get + { + long remainder; + var divided = unchecked( ( int )DivRem( this.unixEpochSeconds, SecondsPerDay, out remainder )); + return + ( DayOfWeek )( + ( + ( this.unixEpochSeconds < 0 + ? ( ( divided + ( ( int )remainder < 0 ? -1 : 0 ) ) % 7 + 7 ) + : divided + ) + DayOfWeekOfEpoc + ) % 7 + ); + } + } + + /// + /// Gets a number of days of this year. + /// + /// A number of days of this year. + public int DayOfYear + { + get + { + long year; + int month, day, dayOfYear; + this.GetDatePart( out year, out month, out day, out dayOfYear ); + return dayOfYear; + } + } + + /// + /// Gets a value which indicates is leap year or not. + /// + /// + /// true, when is leap year; otherwise, false. + /// + /// + /// A of B.C.1 is 0, so if the is 0 then it is leap year. + /// In addition, B.C.3 (the is -3) is leap year, B.C.99 (the is -100) is not, + /// and B.C.399 (the is -400) is leap year. + /// + public bool IsLeapYear + { + get { return IsLeapYearInternal( this.Year ); } + } + + internal static bool IsLeapYearInternal( long year ) + { + // Note: This algorithm assumes that BC uses leap year same as AD and B.C.1 is 0. + // This algorithm avoids remainder operation as possible. + return !( year % 4 != 0 || ( year % 100 == 0 && year % 400 != 0 ) ); + } + + internal static int GetLastDay( int month, bool isLeapYear ) + { + var lastDay = LastDays[ month ]; + if ( month == 2 ) + { + lastDay = isLeapYear ? 29 : 28; + } + + return lastDay; + } + + private void GetDatePart( out long year, out int month, out int day, out int dayOfYear ) + { + if ( this.unixEpochSeconds < -UnixEpochInSeconds ) + { + this.GetDatePartBC( out year, out month, out day, out dayOfYear ); + } + else + { + this.GetDatePartAD( out year, out month, out day, out dayOfYear ); + } + } + + private void GetDatePartAD( out long year, out int month, out int day, out int dayOfYear ) + { + Contract.Assert( this.unixEpochSeconds >= -UnixEpochInSeconds, this.unixEpochSeconds + " > " + ( -UnixEpochInSeconds ) ); + + // From coreclr System.DateTime.cs + // https://github.com/dotnet/coreclr/blob/0825741447c14a6a70c60b7c429e16f95214e74e/src/mscorlib/shared/System/DateTime.cs#L863 + + // First, use 0001-01-01 as epoch to simplify leap year calculation + var seconds = unchecked( ( ulong )( this.unixEpochSeconds + UnixEpochInSeconds ) ); + + // number of days since 0001-01-01 + var daysOffset = seconds / SecondsPerDay; + + // number of whole 400-year periods since 0001-01-01 + var numberOf400Years = daysOffset / DaysPer400Years; + // day number within 400-year period + var daysIn400Years = unchecked( ( uint )( daysOffset - numberOf400Years * DaysPer400Years ) ); + + // number of whole 100-year periods within 400-year period + var numberOf100Years = daysIn400Years / DaysPer100Years; + // Last 100-year period has an extra day, so decrement result if 4 + if ( numberOf100Years == 4 ) + { + numberOf100Years = 3; + } + + // day number within 100-year period + var daysIn100Years = daysIn400Years - numberOf100Years * DaysPer100Years; + + // number of whole 4-year periods within 100-year period + var numberOf4years = daysIn100Years / DaysPer4Years; + // day number within 4-year period + var daysIn4Years = daysIn100Years - numberOf4years * DaysPer4Years; + + // number of whole years within 4-year period + var numberOf1Year = daysIn4Years / DaysPerYear; + // Last year has an extra day, so decrement result if 4 + if ( numberOf1Year == 4 ) + { + numberOf1Year = 3; + } + + // compute year + year = unchecked( ( long )( numberOf400Years * 400 + numberOf100Years * 100 + numberOf4years * 4 + numberOf1Year + 1 ) ); + // day number within year + var daysInYear = daysIn4Years - numberOf1Year * DaysPerYear; + dayOfYear = unchecked( ( int )( daysInYear + 1 ) ); + // Leap year calculation + var isLeapYear = numberOf1Year == 3 && ( numberOf4years != 24 || numberOf100Years == 3 ); + var days = isLeapYear ? DaysToMonth366 : DaysToMonth365; + // All months have less than 32 days, so n >> 5 is a good conservative + // estimate for the month + var numberOfMonth = ( daysInYear >> 5 ) + 1; +#if DEBUG + Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); +#endif // DEBUG + // m = 1-based month number + while ( daysInYear >= days[ numberOfMonth ] ) + { + numberOfMonth++; +#if DEBUG + Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); +#endif // DEBUG + } + // compute month and day + month = unchecked( ( int )numberOfMonth ); + day = unchecked( ( int )( daysInYear - days[ numberOfMonth - 1 ] + 1 ) ); + } + + private void GetDatePartBC( out long year, out int month, out int day, out int dayOfYear ) + { + Contract.Assert( this.unixEpochSeconds < -UnixEpochInSeconds, this.unixEpochSeconds + " > " + ( -UnixEpochInSeconds ) ); + + // From coreclr System.DateTime.cs + // https://github.com/dotnet/coreclr/blob/0825741447c14a6a70c60b7c429e16f95214e74e/src/mscorlib/shared/System/DateTime.cs#L863 + + // First, use 0001-01-01 as epoch to simplify leap year calculation. + // This method calculate negative offset from 0001-01-01. + var seconds = unchecked( ( ulong )( ( this.unixEpochSeconds + UnixEpochInSeconds ) * -1 ) ); + + // number of days since 0001-01-01 + var daysOffset = seconds / SecondsPerDay; + daysOffset += ( seconds % SecondsPerDay ) > 0 ? 1u : 0u; + + // number of whole 400-year periods since 0001-01-01 + var numberOf400Years = ( daysOffset - 1 ) / DaysPer400Years; // decrement offset 1 to adjust 1 to 12-31 + // day number within 400-year period + var daysIn400Years = unchecked( ( uint )( daysOffset - numberOf400Years * DaysPer400Years ) ); + + // number of whole 100-year periods within 400-year period + var numberOf100Years = + daysIn400Years <= ( DaysPer100Years + 1 ) // 1st year is leap year (power of 400) + ? 0 + : ( ( daysIn400Years - 2 ) / DaysPer100Years ); // decrement 1st leap year day and offset 1 to adjust 1 to 12-31 + + // day number within 100-year period + var daysIn100Years = daysIn400Years - numberOf100Years * DaysPer100Years; + + // number of whole 4-year periods within 100-year period + var numberOf4years = + daysIn100Years == 0 + ? 0 + : ( ( daysIn100Years - 1 ) / DaysPer4Years ); // decrement offset 1 to adjust 1 to 12-31 + + // day number within 4-year period + var daysIn4Years = daysIn100Years - numberOf4years * DaysPer4Years; + + // number of whole years within 4-year period + var numberOf1Year = + daysIn4Years <= ( DaysPerYear + ( numberOf4years != 0 ? 1 : 0 ) ) // is leap year in 4 years range? + ? 0 + : ( ( daysIn4Years - 2 ) / DaysPerYear ); // decrement 1st leap year day and offset 1 to adjust 1 to 12-31 + + // compute year, note that 0001 -1 is 0000 (=B.C.1) + year = -unchecked( ( long )( numberOf400Years * 400 + numberOf100Years * 100 + numberOf4years * 4 + numberOf1Year ) ); + var isLeapYear = numberOf1Year == 0 && ( numberOf4years != 0 || numberOf100Years == 0 ); + // day number within year + var daysInYear = + isLeapYear + ? ( 366 - daysIn4Years ) + : ( 365 - ( daysIn4Years - 1 - numberOf1Year * DaysPerYear ) ); + + dayOfYear = unchecked( ( int )( daysInYear + 1 ) ); + // Leap year calculation + var days = isLeapYear ? DaysToMonth366 : DaysToMonth365; + // All months have more than 32 days, so n >> 5 is a good conservative + // estimate for the month + var numberOfMonth = ( daysInYear >> 5 ) + 1; +#if DEBUG + Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); +#endif // DEBUG + // m = 1-based month number + while ( daysInYear >= days[ numberOfMonth ] ) + { + numberOfMonth++; +#if DEBUG + Contract.Assert( numberOfMonth <= 12, numberOfMonth + "<= 12, daysInYear = " + daysInYear ); +#endif // DEBUG + } + // compute month and day + month = unchecked( ( int )numberOfMonth ); + day = unchecked( ( int )( daysInYear - days[ numberOfMonth - 1 ] + 1 ) ); + } + + /// + /// Gets a instance which represents today on UTC. The result only contains date part. + /// + /// A instance which represents today on UTC. The result only contains date part. + /// + /// For underlying system API restriction, this method cannot work after 9999-12-31 in current implementation. + /// + public static Timestamp Today + { + get { return UtcNow.Date; } + } + + /// + /// Gets a instance of now on UTC. + /// + /// A instance of now on UTC. + /// + /// + /// For underlying system API restriction, this method cannot work after 9999-12-31T23:59:59.999999900 in current implementation. + /// + /// + /// In addition, the precision of the returned will be restricted by underlying platform. + /// In current implementation, the precision is 100 nano-seconds at most, and about 1/60 milliseconds on normal Windows platform. + /// + /// + public static Timestamp UtcNow + { + get + { + var now = DateTimeOffset.UtcNow; + return new Timestamp( +#if !NET35 && !NET45 && !NETSTANDARD1_1 && !UNITY && !SILVERLIGHT + now.ToUnixTimeSeconds(), +#else // !NET35 && !NET45 && !NETSTANDARD1_1 && !UNITY && !SILVERLIGHT + ( now.Ticks / TimeSpan.TicksPerSecond ) - UnixEpochInSeconds, +#endif // !NET35 && !NET45 && !NETSTANDARD1_1 && !UNITY && !SILVERLIGHT + unchecked( ( int )( now.Ticks % 10000000 * 100 ) ) + ); + } + } + } +} diff --git a/src/MsgPack/Timestamp.ToString.cs b/src/MsgPack/Timestamp.ToString.cs new file mode 100644 index 000000000..36ed4a429 --- /dev/null +++ b/src/MsgPack/Timestamp.ToString.cs @@ -0,0 +1,137 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Globalization; +using System.Text; + +namespace MsgPack +{ + partial struct Timestamp : IFormattable + { + /// + /// Returns a representation of this instance with the default format and the default format provider. + /// + /// + /// A representation of this instance. + /// + /// + /// + /// As of recommendation of the msgpack specification and consistency with and , + /// this overload uses "o" for the format parameter and null for formatProvider parameter. + /// + /// + /// The round trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff'Z' which 'fffffffff' nanoseconds. + /// + /// + public override string ToString() + { + return this.ToString( null, null ); + } + + /// + /// Returns a representation of this instance with the default format and the specified format provider. + /// + /// + /// An to provide culture specific format information. + /// You can specify null for default behavior, which uses . + /// + /// + /// A representation of this instance. + /// + /// + /// + /// As of recommendation of the msgpack specification and consistency with and , + /// this overload uses "o" for format parameter. + /// + /// + /// The round trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff'Z' which 'fffffffff' nanoseconds. + /// + /// + public string ToString( IFormatProvider formatProvider ) + { + return this.ToString( null, formatProvider ); + } + + /// + /// Returns a representation of this instance with the specified format and the default format provider. + /// + /// + /// A format string to specify output format. You can specify null for default behavior, which is interpreted as "o". + /// + /// + /// A representation of this instance. + /// + /// + /// + /// Currently, only "o" and "O" (ISO 8601 like round trip format) and "s" (ISO 8601 format) are supported. + /// Other standard date time format and any custom date time format are not supported. + /// + /// + /// The round trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff'Z' which 'fffffffff' nanoseconds. + /// + /// + /// As of recommendation of the msgpack specification and consistency with and , + /// this overload uses null for formatProvider parameter. + /// + /// + public string ToString( string format ) + { + return this.ToString( format, null ); + } + + /// + /// Returns a representation of this instance with the default format and the specified format provider. + /// + /// + /// A format string to specify output format. You can specify null for default behavior, which is interpreted as "o". + /// + /// + /// An to provide culture specific format information. + /// You can specify null for default behavior, which uses . + /// + /// + /// A representation of this instance. + /// + /// + /// is not valid. + /// + /// + /// + /// Currently, only "o" and "O" (ISO 8601 like round trip format) and "s" (ISO 8601 format) are supported. + /// Other standard date time format and any custom date time format are not supported. + /// + /// + /// The round trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff'Z' which 'fffffffff' nanoseconds. + /// + /// + /// As of recommendation of the msgpack specification and consistency with and , + /// the default value of the is "o" (ISO 8601 like round-trip format) + /// and the default value of the is null (. + /// If you want to ensure interoperability for other implementation, specify "s" and resepectively. + /// + /// + public string ToString( string format, IFormatProvider formatProvider ) + { + var value = new Value( this ); + return TimestampStringConverter.ToString( format, formatProvider, ref value ); + } + } +} diff --git a/src/MsgPack/Timestamp.TryParseExact.cs b/src/MsgPack/Timestamp.TryParseExact.cs new file mode 100644 index 000000000..da1b4c2ca --- /dev/null +++ b/src/MsgPack/Timestamp.TryParseExact.cs @@ -0,0 +1,195 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT +using System.Globalization; + +namespace MsgPack +{ + partial struct Timestamp + { + /// + /// Converts specified representation of a msgpack timestamp to its equivalant + /// with specified format, culture-specific format information provider, and . + /// + /// An input representation of a msgpack timestamp. The format must be match exactly to the . + /// An expected format string. + /// An to provide culture specific information to parse . + /// + /// Specify bitwise value combination of to control detailed parsing behavior. + /// The typical value is . + /// + /// If the conversion succeeded, the conversion result will be stored; otherwise, the default value will be stored. + /// true, if the conversion succeeded; otherwise, false. + /// + /// + /// Currently, supported date-time format is only 'o' and 'O' (round-trip) or 's' (sortable, ISO-8601). + /// Other any standard date-time formats and custom date-time formats are not supported. + /// + /// + /// The rount-trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff'Z' which "fffffffff" is nanoseconds. + /// + /// + /// The sign mark can be culture-specific, and leading/trailing whitespaces can be allowed when specify appropriate . + /// + /// + /// + /// is null. + /// Or, is null. + /// + /// + /// The specified is not supported. + /// Or the specified has invalid combination. + /// + public static bool TryParseExact( string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result ) + { + return TryParseExactCore( input, format, formatProvider, styles, out result ) == TimestampParseResult.Success; + } + + /// + /// Converts specified representation of a msgpack timestamp to its equivalant + /// with specified format, culture-specific format information provider, and . + /// + /// The input representation of a msgpack timestamp. The format must be match exactly to one of the . + /// The array of expected format strings. Unsupported format will be ignored. + /// The culture specific information to control + /// + /// Specify bitwise value combination of to control detailed parsing behavior. + /// The typical value is . + /// + /// If the conversion succeeded, the conversion result will be stored; otherwise, the default value will be stored. + /// true, if the conversion succeeded; otherwise, false. + /// + /// + /// Currently, supported date-time format is only 'o' and 'O' (round-trip) or 's' (sortable, ISO-8601). + /// Other any standard date-time formats and custom date-time formats are not supported. + /// + /// + /// The rount-trip format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffff'Z' which "fffffffff" is nanoseconds. + /// + /// + /// The sign mark can be culture-specific, and leading/trailing whitespaces can be allowed when specify appropriate . + /// + /// + /// + /// is null. + /// Or, is null. + /// + /// + /// The specified is empty. + /// Or the specified has invalid combination. + /// + public static bool TryParseExact( string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result ) + { + return TryParseExactCore( input, formats, formatProvider, styles, out result ) == TimestampParseResult.Success; + } + + private static TimestampParseResult TryParseExactCore( string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result ) + { + ValidateParseInput( input ); + + if ( input.Length == 0 ) + { + result = default( Timestamp ); + return TimestampParseResult.EmptyInput; + } + + if ( format == null ) + { + throw new ArgumentNullException( "format" ); + } + + if ( format.Length == 0 ) + { + throw new ArgumentException( "The 'format' must not be empty.", "format" ); + } + + ValidateParseStyles( styles ); + + var error = TimestampStringConverter.TryParseExact( input, format, formatProvider, styles, out result ); + if ( error == TimestampParseResult.UnsupportedFormat ) + { + // UnsupportedFormat should throw Exception instead of returning false. + HandleParseResult( error, "Cannot parse specified input with specified format." ); + } + + return error; + } + + private static TimestampParseResult TryParseExactCore( string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result ) + { + ValidateParseInput( input ); + + if ( formats == null ) + { + throw new ArgumentNullException( "formats" ); + } + + if ( formats.Length == 0 ) + { + throw new ArgumentException( "The 'formats' must not be empty.", "formats" ); + } + + ValidateParseStyles( styles ); + + if ( input.Length == 0 ) + { + result = default( Timestamp ); + return TimestampParseResult.EmptyInput; + } + + foreach ( var format in formats ) + { + if ( TimestampStringConverter.TryParseExact( input, format, formatProvider, styles, out result ) == TimestampParseResult.Success ) + { + return TimestampParseResult.Success; + } + } + + result = default( Timestamp ); + return TimestampParseResult.NoMatchedFormats; + } + + private static void ValidateParseInput( string input ) + { + if ( input == null ) + { + throw new ArgumentNullException( "input" ); + } + } + + private static void ValidateParseStyles( DateTimeStyles styles ) + { + if ( styles != DateTimeStyles.None && ( styles & ~( DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite ) ) != 0 ) + { + throw new ArgumentException( "Timestamp currently only support DateTimeStyles.None, DateTimeStyles.AllowLeadingWhite, and DateTimeStyles.AllowTrailingWhite.", "styles" ); + } + } + } +} diff --git a/src/MsgPack/Timestamp.cs b/src/MsgPack/Timestamp.cs new file mode 100644 index 000000000..8043dff75 --- /dev/null +++ b/src/MsgPack/Timestamp.cs @@ -0,0 +1,233 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; + +namespace MsgPack +{ + /// + /// Represents high resolution timestamp for MessagePack eco-system. + /// + /// + /// The timestamp consists of 64bit Unix epoc seconds and 32bit unsigned nanoseconds offset from the calculated datetime with the epoc. + /// So this type supports wider range than and and supports 1 or 10 nano seconds precision. + /// However, this type does not support local date time and time zone information, so this type always represents UTC time. + /// +#if FEATURE_BINARY_SERIALIZATION + [Serializable] +#endif // FEATURE_BINARY_SERIALIZATION + public partial struct Timestamp + { + /// + /// MessagePack ext type code for msgpack timestamp type. + /// + public const byte TypeCode = 0xFF; + + /// + /// An instance represents zero. This is 1970-01-01T00:00:00.000000000. + /// + public static readonly Timestamp Zero = new Timestamp( 0, 0 ); + + /// + /// An instance represents minimum value of this instance. This is [, 0] in encoded format. + /// + public static readonly Timestamp MinValue = new Timestamp( Int64.MinValue, 0 ); + + /// + /// An instance represents maximum value of this instance. This is [, 999999999] in encoded format. + /// + public static readonly Timestamp MaxValue = new Timestamp( Int64.MaxValue, MaxNanoSeconds ); + + private static readonly int[] LastDays = + new[] + { + 0, // There are no month=0 + 31, + 0, // 28 or 29 + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + }; + + private const long MinUnixEpochSecondsForTicks = -62135596800L; + private const long MaxUnixEpochSecondsForTicks = 253402300799; + + private const int MaxNanoSeconds = 999999999; + + private const long UnixEpochTicks = 621355968000000000; + private const long UnixEpochInSeconds = 62135596800; + private const int SecondsToTicks = 10 * 1000 * 1000; + private const int NanoToTicks = 100; + private const int SecondsToNanos = 1000 * 1000 * 1000; + + private readonly long unixEpochSeconds; + private readonly uint nanoseconds; // 0 - 999,999,999 + + /// + /// Initializes a new instance of structure. + /// + /// A unit epoc seconds part of the msgpack timestamp. + /// A unit nanoseconds part of the msgpack timestamp. + /// + /// is negative or is greater than 999,999,999 exclusive. + /// + public Timestamp( long unixEpochSeconds, int nanoseconds ) + { + if ( nanoseconds > MaxNanoSeconds || nanoseconds < 0 ) + { + throw new ArgumentOutOfRangeException( "nanoseconds", "nanoseconds must be non negative value and lessor than 999,999,999." ); + } + + this.unixEpochSeconds = unixEpochSeconds; + this.nanoseconds = unchecked( ( uint )nanoseconds ); + } + + internal static Timestamp FromComponents( ref Value value, bool isLeapYear ) + { + long epoc; + checked + { + var days = YearsToDaysOfNewYear( value.Year ) + ToDaysOffsetFromNewYear( value.Month, value.Day, isLeapYear ) - Timestamp.UnixEpochInSeconds / Timestamp.SecondsPerDay; + // First set time offset to avoid overflow. + epoc = value.Hour * 60 * 60; + epoc += value.Minute * 60; + epoc += value.Second; + if ( days < 0 ) + { + // Avoid right side overflow. + epoc += ( days + 1 ) * Timestamp.SecondsPerDay; + epoc -= Timestamp.SecondsPerDay; + } + else + { + epoc += days * Timestamp.SecondsPerDay; + } + } + + return new Timestamp( epoc, unchecked( ( int )value.Nanoseconds ) ); + } + + private static long YearsToDaysOfNewYear( long years ) + { + long remainOf400Years, remainOf100Years, remainOf4Years; + + // For AD, uses offset from 0001, so decrement 1 at first. + var numberOf400Years = DivRem( years > 0 ? ( years - 1 ) : years, 400, out remainOf400Years ); + var numberOf100Years = DivRem( remainOf400Years, 100, out remainOf100Years ); + var numberOf4Years = DivRem( remainOf100Years, 4, out remainOf4Years ); + var days = + DaysPer400Years * numberOf400Years + + DaysPer100Years * numberOf100Years + + DaysPer4Years * numberOf4Years + + DaysPerYear * remainOf4Years; + if ( years <= 0 ) + { + // For BC, subtract year 0000 offset. + days -= ( DaysPerYear + 1 ); + } + + return days; + } + + private static int ToDaysOffsetFromNewYear( int month, int day, bool isLeapYear ) + { + var result = -1; // 01-01 should be 0, so starts with -1. + for ( var i = 1; i < month; i++ ) + { + result += LastDays[ i ]; + if ( i == 2 ) + { + result += isLeapYear ? 29 : 28; + } + } + + result += day; + return result; + } + +#if NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT + + // Slow alternative + internal static long DivRem( long dividend, long divisor, out long remainder ) + { + remainder = dividend % divisor; + return dividend / divisor; + } + +#else // NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT + + internal static long DivRem( long dividend, long divisor, out long remainder ) + { + return Math.DivRem( dividend, divisor, out remainder ); + } + +#endif // NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT + +#if UNITY && DEBUG + public +#else + internal +#endif + struct Value + { + public long Year; + public int Month; + public int Day; + public int Hour; + public int Minute; + public int Second; + public uint Nanoseconds; + + public Value( Timestamp encoded ) + { + int dayOfYear; + encoded.GetDatePart( out this.Year, out this.Month, out this.Day, out dayOfYear ); + this.Hour = encoded.Hour; + this.Minute = encoded.Minute; + this.Second = encoded.Second; + this.Nanoseconds = encoded.nanoseconds; + } + +#if DEBUG + public Value( long year, int month, int day, int hour, int minute, int second, uint nanoseconds ) + { + this.Year = year; + this.Month = month; + this.Day = day; + this.Hour = hour; + this.Minute = minute; + this.Second = second; + this.Nanoseconds = nanoseconds; + } +#endif // DEBUG + } + } +} diff --git a/src/MsgPack/TimestampParseResult.cs b/src/MsgPack/TimestampParseResult.cs new file mode 100644 index 000000000..518022df1 --- /dev/null +++ b/src/MsgPack/TimestampParseResult.cs @@ -0,0 +1,97 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +namespace MsgPack +{ + /// + /// Represents internal result. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + enum TimestampParseResult + { + Success = 0, + + KindMask = 0xFFFF, + KindNull = 1, + KindEmpty = 2, + KindUnsupported = 3, + KindLeadingWhitespaceNotSupported = 11, + KindTrailingWhitespaceNotSupported = 12, + KindMissingUtcSign = 13, + KindExtraCharactors = 14, + KindInvalidYear = 21, + KindInvalidMonth = 22, + KindInvalidDay = 23, + KindInvalidHour = 24, + KindInvalidMinute = 25, + KindInvalidSecond = 26, + KindInvalidNanoSecond = 27, + KindYearOutOfRange = 31, + KindInvalidYearMonthDeilimiter = 101, + KindInvalidMonthDayDelimiter = 102, + KindInvalidDateTimeDelimiter = 103, + KindInvalidHourMinuteDelimiter = 104, + KindInvalidMinuteSecondDelimiter = 105, + KindInvalidSubsecondDelimiter = 106, + KindNoMatchedFormats = 1001, + + ParameterMask = 0xFF << 16, + ParameterInput = 1 << 16, + ParameterFormat = 2 << 16, + + ExceptionTypeMask = 0xFF << 24, + ArgumentNullException = 1 << 24, + ArgumentException = 2 << 24, + FormatException = 3 << 24, + + NullInput = ArgumentNullException | ParameterInput | KindNull, + NullFormat = ArgumentNullException | ParameterFormat | KindNull, + EmptyInput = FormatException | ParameterInput | KindEmpty, + EmptyFormat = ArgumentException | ParameterFormat | KindEmpty, + UnsupportedFormat = ArgumentException | ParameterFormat | KindUnsupported, + LeadingWhitespaceNotAllowed = FormatException | ParameterInput | KindLeadingWhitespaceNotSupported, + TrailingWhitespaceNotAllowed = FormatException | ParameterInput | KindTrailingWhitespaceNotSupported, + MissingUtcSign = FormatException | ParameterInput | KindMissingUtcSign, + ExtraCharactors = FormatException | ParameterInput | KindExtraCharactors, + InvalidYear = FormatException | ParameterInput | KindInvalidYear, + InvalidMonth = FormatException | ParameterInput | KindInvalidMonth, + InvalidDay = FormatException | ParameterInput | KindInvalidDay, + InvalidHour = FormatException | ParameterInput | KindInvalidHour, + InvalidMinute = FormatException | ParameterInput | KindInvalidMinute, + InvalidSecond = FormatException | ParameterInput | KindInvalidSecond, + InvalidNanoSecond = FormatException | ParameterInput | KindInvalidNanoSecond, + YearOutOfRange = FormatException | ParameterInput | KindYearOutOfRange, + InvalidYearMonthDeilimiter = FormatException | ParameterInput | KindInvalidYearMonthDeilimiter, + InvalidMonthDayDelimiter = FormatException | ParameterInput | KindInvalidMonthDayDelimiter, + InvalidDateTimeDelimiter = FormatException | ParameterInput | KindInvalidDateTimeDelimiter, + InvalidHourMinuteDelimiter = FormatException | ParameterInput | KindInvalidHourMinuteDelimiter, + InvalidMinuteSecondDelimiter = FormatException | ParameterInput | KindInvalidMinuteSecondDelimiter, + InvalidSubsecondDelimiter = FormatException | ParameterInput | KindInvalidSubsecondDelimiter, + NoMatchedFormats = FormatException | ParameterInput | KindNoMatchedFormats + } +} diff --git a/src/MsgPack/TimestampStringConverter.Parse.cs b/src/MsgPack/TimestampStringConverter.Parse.cs new file mode 100644 index 000000000..e7f5e351e --- /dev/null +++ b/src/MsgPack/TimestampStringConverter.Parse.cs @@ -0,0 +1,349 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Globalization; + +namespace MsgPack +{ + partial class TimestampStringConverter + { + // Currently, custom format and normal date time format except 'o' or 'O' 's' are NOT supported. + public static TimestampParseResult TryParseExact( string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result ) + { + if ( format != "o" && format != "O" && format != "s" ) + { + result = default( Timestamp ); + return TimestampParseResult.UnsupportedFormat; + } + + var numberFormat = NumberFormatInfo.GetInstance( formatProvider ); + + var position = 0; + if ( !ParseWhitespace( input, ref position, ( styles & DateTimeStyles.AllowLeadingWhite ) != 0, /* isTrailing */false ) ) + { + result = default( Timestamp ); + return TimestampParseResult.LeadingWhitespaceNotAllowed; + } + + long year; + if ( !ParseYear( input, ref position, numberFormat, out year ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidYear; + } + + if ( !ParseDelimiter( input, ref position, DateDelimiter ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidYearMonthDeilimiter; + } + + var isLeapYear = Timestamp.IsLeapYearInternal( year ); + + int month; + if ( !ParseDigitRange( input, 2, ref position, 1, 12, out month ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidMonth; + } + + if ( !ParseDelimiter( input, ref position, DateDelimiter ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidMonthDayDelimiter; + } + + int day; + if ( !ParseDay( input, ref position, month, isLeapYear, out day ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidDay; + } + + if ( !ParseDelimiter( input, ref position, DateTimeDelimiter ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidDateTimeDelimiter; + } + + int hour; + if ( !ParseDigitRange( input, 2, ref position, 0, 23, out hour ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidHour; + } + + if ( !ParseDelimiter( input, ref position, TimeDelimiter ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidHourMinuteDelimiter; + } + + int minute; + if ( !ParseDigitRange( input, 2, ref position, 0, 59, out minute ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidMinute; + } + + if ( !ParseDelimiter( input, ref position, TimeDelimiter ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidMinuteSecondDelimiter; + } + + int second; + if ( !ParseDigitRange( input, 2, ref position, 0, 59, out second ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidSecond; + } + + var nanosecond = 0; + if ( format != "s" ) + { + // "o" or "O" + if ( !ParseDelimiter( input, ref position, SubsecondDelimiter ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidSubsecondDelimiter; + } + + if ( !ParseDigitRange( input, 9, ref position, 0, 999999999, out nanosecond ) ) + { + result = default( Timestamp ); + return TimestampParseResult.InvalidNanoSecond; + } + } + + if ( !ParseDelimiter( input, ref position, UtcSign ) ) + { + result = default( Timestamp ); + return TimestampParseResult.MissingUtcSign; + } + + if ( !ParseWhitespace( input, ref position, ( styles & DateTimeStyles.AllowTrailingWhite ) != 0, /* isTrailing */true ) ) + { + result = default( Timestamp ); + return TimestampParseResult.TrailingWhitespaceNotAllowed; + } + + if ( position != input.Length ) + { + result = default( Timestamp ); + return TimestampParseResult.ExtraCharactors; + } + + var components = new Timestamp.Value(); + components.Year = year; + components.Month = month; + components.Day = day; + components.Hour = hour; + components.Minute = minute; + components.Second = second; + components.Nanoseconds = unchecked( ( uint )nanosecond ); + + try + { + result = Timestamp.FromComponents( ref components, isLeapYear ); + } + catch ( OverflowException ) + { + result = default( Timestamp ); + return TimestampParseResult.YearOutOfRange; + } + + return TimestampParseResult.Success; + } + + private static bool ParseWhitespace( string input, ref int position, bool allowWhitespace, bool isTrailing ) + { + if ( input.Length <= position ) + { + return isTrailing; + } + + if ( !allowWhitespace ) + { + return !Char.IsWhiteSpace( input[ position ] ); + } + + while ( position < input.Length && Char.IsWhiteSpace( input[ position ] ) ) + { + position++; + } + + return true; + } + + private static bool ParseDelimiter( string input, ref int position, char delimiter ) + { + if ( input.Length <= position ) + { + return false; + } + + if ( input[ position ] != delimiter ) + { + return false; + } + + position++; + return true; + } + + private static bool ParseSign( string input, ref int position, NumberFormatInfo numberFormat, out int sign ) + { + if ( input.Length <= position ) + { + sign = default( int ); + return false; + } + + if ( IsDigit( input[ position ] ) ) + { + sign = 1; + return true; + } + + if ( StartsWith( input, position, numberFormat.NegativeSign ) ) + { + position += numberFormat.NegativeSign.Length; + sign = -1; + return true; + } + + if ( StartsWith( input, position, numberFormat.PositiveSign ) ) + { + position += numberFormat.NegativeSign.Length; + sign = 1; + return true; + } + + sign = default( int ); + return false; + } + + private static bool StartsWith( string input, int startIndex, string comparison ) + { + for ( var i = 0; i < comparison.Length; i++ ) + { + if ( i + startIndex >= input.Length ) + { + return false; + } + + if ( input[ i + startIndex ] != comparison[ i ] ) + { + return false; + } + } + + return true; + } + + private static bool ParseDigit( string input, int minLength, ref int position, out long digit ) + { + var startPosition = position; + var bits = 0L; + while ( position < input.Length ) + { + var c = input[ position ]; + if ( !IsDigit( c ) ) + { + break; + } + + bits = bits * 10 + ( c - '0' ); + position++; + } + + digit = bits; + return position >= startPosition + minLength; + } + + private static bool IsDigit( char c ) + { + return '0' <= c && c <= '9'; + } + + private static bool ParseDigitRange( string input, int minLength, ref int position, int min, int max, out int result ) + { + long digit; + if ( !ParseDigit( input, minLength, ref position, out digit ) ) + { + result = default( int ); + return false; + } + + if ( digit < min || max < digit ) + { + result = default( int ); + return false; + } + + result = unchecked( ( int )digit ); + return true; + } + + private static bool ParseYear( string input, ref int position, NumberFormatInfo numberFormat, out long year ) + { + int sign; + if ( !ParseSign( input, ref position, numberFormat, out sign ) ) + { + year = default( long ); + return false; + } + + long digit; + if ( !ParseDigit( input, 4, ref position, out digit ) ) + { + year = default( long ); + return false; + } + + // as of ISO 8601, 0001-01-01 -1 day is 0000-12-31. + year = digit * sign; + return true; + } + + private static bool ParseDay( string input, ref int position, int month, bool isLeapYear, out int day ) + { + long digit; + if ( !ParseDigit( input, 2, ref position, out digit ) ) + { + day = default( int ); + return false; + } + + var lastDay = Timestamp.GetLastDay( month, isLeapYear ); + + if ( digit < 1 || lastDay < digit ) + { + day = default( int ); + return false; + } + + day = unchecked( ( int )digit ); + return true; + } + } +} diff --git a/src/MsgPack/TimestampStringConverter.ToString.cs b/src/MsgPack/TimestampStringConverter.ToString.cs new file mode 100644 index 000000000..b695e296a --- /dev/null +++ b/src/MsgPack/TimestampStringConverter.ToString.cs @@ -0,0 +1,82 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Globalization; +using System.Text; + +namespace MsgPack +{ + partial class TimestampStringConverter + { + private const string DefaultFormat = "o"; + + public static string ToString( string format, IFormatProvider formatProvider, ref Timestamp.Value value ) + { + switch ( format ?? DefaultFormat ) + { + case "o": + case "O": + { + // round-trip + return ToIso8601String( formatProvider, /* containsNanoseconds */true, ref value ); + } + case "s": + { + // sortable(ISO-8601) + return ToIso8601String( formatProvider, /* containsNanoseconds */false, ref value ); + } + default: + { + throw new ArgumentException( "The specified format is not supported.", "format" ); + } + } + } + + private static string ToIso8601String( IFormatProvider formatProvider, bool containsNanosecons, ref Timestamp.Value value ) + { + var numberFormat = NumberFormatInfo.GetInstance( formatProvider ); + + // Most cases are yyyy-MM-ddTHH:mm:ss[.fffffffff]Z -- 50 or 60 chars. + var buffer = new StringBuilder( 49 + ( containsNanosecons ? 11 : 1 ) ); + buffer.Append( value.Year.ToString( "0000", formatProvider ) ); + buffer.Append( DateDelimiter ); + buffer.Append( value.Month.ToString( "00", formatProvider ) ); + buffer.Append( DateDelimiter ); + buffer.Append( value.Day.ToString( "00", formatProvider ) ); + buffer.Append( DateTimeDelimiter ); + buffer.Append( value.Hour.ToString( "00", formatProvider ) ); + buffer.Append( TimeDelimiter ); + buffer.Append( value.Minute.ToString( "00", formatProvider ) ); + buffer.Append( TimeDelimiter ); + buffer.Append( value.Second.ToString( "00", formatProvider ) ); + + if ( containsNanosecons ) + { + buffer.Append( SubsecondDelimiter ); + buffer.Append( value.Nanoseconds.ToString( "000000000", formatProvider ) ); + } + + buffer.Append( UtcSign ); + + return buffer.ToString(); + } + } +} diff --git a/src/MsgPack/TimestampStringConverter.cs b/src/MsgPack/TimestampStringConverter.cs new file mode 100644 index 000000000..9e80c889a --- /dev/null +++ b/src/MsgPack/TimestampStringConverter.cs @@ -0,0 +1,46 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.Globalization; + +namespace MsgPack +{ + /// + /// An internal parser and stringifier. + /// +#if UNITY && DEBUG + public +#else + internal +#endif + static partial class TimestampStringConverter + { + private const char DateDelimiter = '-'; + private const char TimeDelimiter = ':'; + private const char DateTimeDelimiter = 'T'; + private const char SubsecondDelimiter = '.'; + private const char UtcSign = 'Z'; + } +} diff --git a/src/MsgPack/TupleItems.cs b/src/MsgPack/TupleItems.cs index 83f2dbaac..37963d470 100644 --- a/src/MsgPack/TupleItems.cs +++ b/src/MsgPack/TupleItems.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,15 +25,12 @@ #if !UNITY using System; using System.Collections.Generic; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Linq; -#if NETFX_CORE -using System.Reflection; -#endif namespace MsgPack { @@ -45,56 +42,60 @@ internal static class TupleItems /// /// Creates type list for nested tuples. /// - /// The type list of tuple items, in order. + /// The type of base tuple. /// /// The type list for nested tuples. /// The order is from outer to inner. /// - public static List CreateTupleTypeList( IList itemTypes ) + public static List CreateTupleTypeList( Type rootTupleType ) { - var itemTypesStack = new Stack>( itemTypes.Count / 7 + 1 ); - for ( int i = 0; i < itemTypes.Count / 7; i++ ) + if ( !rootTupleType.GetIsGenericType() ) { - itemTypesStack.Push( itemTypes.Skip( i * 7 ).Take( 7 ).ToList() ); + // arity 0 value tuple + return new List( 1 ) { rootTupleType }; } - if ( itemTypes.Count % 7 != 0 ) + var assembly = rootTupleType.GetAssembly(); + var baseName = rootTupleType.FullName.Remove( rootTupleType.FullName.IndexOf( '`' ) + 1 ); + var result = new List(); + var tupleType = rootTupleType; + while ( true ) { - itemTypesStack.Push( itemTypes.Skip( ( itemTypes.Count / 7 ) * 7 ).Take( itemTypes.Count % 7 ).ToList() ); - } + result.Add( tupleType ); + if ( !tupleType.GetIsGenericType() ) + { + // arity 0 + break; + } - var result = new List( itemTypesStack.Count ); - while ( 0 < itemTypesStack.Count ) - { - var itemTypesStackEntry = itemTypesStack.Pop(); - if ( 0 < result.Count ) + var itemTypes = tupleType.GetGenericArguments(); + if ( itemTypes.Length < 8 ) { - itemTypesStackEntry.Add( result.Last() ); + // leaf tuple + break; } - var tupleType = Type.GetType( "System.Tuple`" + itemTypesStackEntry.Count, true ).MakeGenericType( itemTypesStackEntry.ToArray() ); - result.Add( tupleType ); + tupleType = itemTypes.Last(); } - result.Reverse(); return result; } public static IList GetTupleItemTypes( Type tupleType ) { #if DEBUG - Contract.Assert( tupleType.Name.StartsWith( "Tuple`" ) && tupleType.GetAssembly().Equals( typeof( Tuple ).GetAssembly() ), "tupleType.Name.StartsWith( \"Tuple`\" ) && tupleType.GetAssembly().Equals( typeof( Tuple ).GetAssembly() )" ); + Contract.Assert( IsTuple( tupleType ), "IsTuple( "+ tupleType.AssemblyQualifiedName + " )" ); #endif // DEBUG var arguments = tupleType.GetGenericArguments(); - List itemTypes = new List( tupleType.GetGenericArguments().Length ); + var itemTypes = new List( tupleType.GetGenericArguments().Length ); GetTupleItemTypes( arguments, itemTypes ); return itemTypes; } private static void GetTupleItemTypes( IList itemTypes, IList result ) { - int count = itemTypes.Count == 8 ? 7 : itemTypes.Count; - for ( int i = 0; i < count; i++ ) + var count = itemTypes.Count == 8 ? 7 : itemTypes.Count; + for ( var i = 0; i < count; i++ ) { result.Add( itemTypes[ i ] ); } @@ -103,20 +104,21 @@ private static void GetTupleItemTypes( IList itemTypes, IList result { var trest = itemTypes[ 7 ]; #if DEBUG - Contract.Assert( trest.Name.StartsWith( "Tuple`" ) && trest.GetAssembly().Equals( typeof( Tuple ).GetAssembly() ), "trest.Name.StartsWith( \"Tuple`\" ) && trest.Assembly == typeof( Tuple ).Assembly" ); + Contract.Assert( IsTuple( trest ), "IsTuple( " + trest.AssemblyQualifiedName + " )" ); #endif // DEBUG + // Put nested tuple's item types recursively. GetTupleItemTypes( trest.GetGenericArguments(), result ); } } public static bool IsTuple( Type type ) { - var assembly = type.GetAssembly(); return - ( assembly.Equals( typeof( object ).GetAssembly() ) || - assembly.Equals( typeof( Enumerable ).GetAssembly() ) ) - && type.GetIsPublic() && - type.Name.StartsWith( "Tuple`", StringComparison.Ordinal ); + type.GetIsPublic() + && ( ( type.FullName.StartsWith( "System.ValueTuple`", StringComparison.Ordinal ) && type.GetIsValueType() ) + || ( type.FullName.StartsWith( "System.Tuple`", StringComparison.Ordinal ) && !type.GetIsValueType() ) + || ( type.FullName == "System.ValueTuple" && type.GetIsValueType() ) + ); } } } diff --git a/src/MsgPack.Net35/Tuple`n.cs b/src/MsgPack/Tuple`n.cs similarity index 100% rename from src/MsgPack.Net35/Tuple`n.cs rename to src/MsgPack/Tuple`n.cs diff --git a/src/MsgPack.Net35/Tuple`n.tt b/src/MsgPack/Tuple`n.tt similarity index 100% rename from src/MsgPack.Net35/Tuple`n.tt rename to src/MsgPack/Tuple`n.tt diff --git a/src/MsgPack/Unpacker.Leaf.cs b/src/MsgPack/Unpacker.Leaf.cs new file mode 100644 index 000000000..a442b461a --- /dev/null +++ b/src/MsgPack/Unpacker.Leaf.cs @@ -0,0 +1,183 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.IO; + +namespace MsgPack +{ + // This file was generated from Unpacker.Leaf.tt and Core.ttinclude T4Template. + // Do not modify this file. Edit Unpacker.Leaf.tt and Core.ttinclude instead. + +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class FastStreamUnpacker : MessagePackStreamUnpacker + { + public FastStreamUnpacker( Stream stream, PackerUnpackerStreamOptions streamOptions ) + : base( stream, streamOptions ) { } + + protected override Unpacker ReadSubtreeCore() + { + this.BeginReadSubtree(); + return this; + } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class CollectionValidatingStreamUnpacker : MessagePackStreamUnpacker + { + // ReSharper disable once RedundantDefaultFieldInitializer + private bool _isSubtreeReading = false; + + public CollectionValidatingStreamUnpacker( Stream stream, PackerUnpackerStreamOptions streamOptions ) + : base( stream, streamOptions ) { } + + internal override Unpacker InternalReadSubtree() + { + if ( !this.IsCollectionHeader ) + { + ThrowCannotBeSubtreeModeException(); + } + + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + + var subtreeReader = this.ReadSubtreeCore(); + this._isSubtreeReading = !ReferenceEquals( subtreeReader, this ); + return subtreeReader; + } + + protected override Unpacker ReadSubtreeCore() + { + return new SubtreeUnpacker( this ); + } + + protected internal override void EndReadSubtree() + { + this._isSubtreeReading = false; + base.EndReadSubtree(); + } + + internal override void EnsureNotInSubtreeMode() + { + this.VerifyMode( UnpackerMode.Streaming ); + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + } + + internal override void BeginSkipCore() + { + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class FastByteArrayUnpacker : MessagePackByteArrayUnpacker + { + public FastByteArrayUnpacker( byte[] source, int startOffset ) + : base( source, startOffset ) { } + + protected override Unpacker ReadSubtreeCore() + { + return this; + } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class CollectionValidatingByteArrayUnpacker : MessagePackByteArrayUnpacker + { + // ReSharper disable once RedundantDefaultFieldInitializer + private bool _isSubtreeReading = false; + + public CollectionValidatingByteArrayUnpacker( byte[] source, int startOffset ) + : base( source, startOffset ) { } + + internal override Unpacker InternalReadSubtree() + { + if ( !this.IsCollectionHeader ) + { + ThrowCannotBeSubtreeModeException(); + } + + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + + var subtreeReader = this.ReadSubtreeCore(); + this._isSubtreeReading = !ReferenceEquals( subtreeReader, this ); + return subtreeReader; + } + + protected override Unpacker ReadSubtreeCore() + { + return new SubtreeUnpacker( this ); + } + + protected internal override void EndReadSubtree() + { + this._isSubtreeReading = false; + base.EndReadSubtree(); + } + + internal override void EnsureNotInSubtreeMode() + { + this.VerifyMode( UnpackerMode.Streaming ); + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + } + + internal override void BeginSkipCore() + { + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + } + } +} diff --git a/src/MsgPack/Unpacker.Leaf.tt b/src/MsgPack/Unpacker.Leaf.tt new file mode 100644 index 000000000..07a6b1aa9 --- /dev/null +++ b/src/MsgPack/Unpacker.Leaf.tt @@ -0,0 +1,168 @@ +<#@ template debug="true" hostSpecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ include file="..\Core.ttinclude" #> +<#@ Assembly Name="System.Core.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +using System.IO; + +namespace MsgPack +{ + // This file was generated from Unpacker.Leaf.tt and Core.ttinclude T4Template. + // Do not modify this file. Edit Unpacker.Leaf.tt and Core.ttinclude instead. +<# +foreach ( var spec in + new [] + { + new + { + Kind = "Stream", + ParametersList = + new [] + { + new Dictionary { { "stream", "Stream" }, { "streamOptions", "PackerUnpackerStreamOptions" } } + } + }, + new + { + Kind = "ByteArray", + ParametersList = + new [] + { + new Dictionary { { "source", "byte[]" }, { "startOffset", "int" } } + } + } + } +) +{ +#> + +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class Fast<#= spec.Kind #>Unpacker : MessagePack<#= spec.Kind #>Unpacker + { +<# + foreach ( var parameters in spec.ParametersList ) + { +#> + public Fast<#= spec.Kind #>Unpacker( <#= String.Join( ", ", parameters.Select( kv => kv.Value + " " + kv.Key ).ToArray() ) #> ) + : base( <#= String.Join( ", ", parameters.Keys.ToArray() ) #> ) { } + +<# + } +#> + protected override Unpacker ReadSubtreeCore() + { +<# + if ( spec.Kind == "Stream" ) + { +#> + this.BeginReadSubtree(); +<# + } +#> + return this; + } + } + +#if UNITY && DEBUG + public +#else + internal +#endif + sealed class CollectionValidating<#= spec.Kind #>Unpacker : MessagePack<#= spec.Kind #>Unpacker + { + // ReSharper disable once RedundantDefaultFieldInitializer + private bool _isSubtreeReading = false; + +<# + foreach ( var parameters in spec.ParametersList ) + { +#> + public CollectionValidating<#= spec.Kind #>Unpacker( <#= String.Join( ", ", parameters.Select( kv => kv.Value + " " + kv.Key ).ToArray() ) #> ) + : base( <#= String.Join( ", ", parameters.Keys.ToArray() ) #> ) { } + +<# + } +#> + internal override Unpacker InternalReadSubtree() + { + if ( !this.IsCollectionHeader ) + { + ThrowCannotBeSubtreeModeException(); + } + + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + + var subtreeReader = this.ReadSubtreeCore(); + this._isSubtreeReading = !ReferenceEquals( subtreeReader, this ); + return subtreeReader; + } + + protected override Unpacker ReadSubtreeCore() + { + return new SubtreeUnpacker( this ); + } + + protected internal override void EndReadSubtree() + { + this._isSubtreeReading = false; + base.EndReadSubtree(); + } + + internal override void EnsureNotInSubtreeMode() + { + this.VerifyMode( UnpackerMode.Streaming ); + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + } + + internal override void BeginSkipCore() + { + if ( this._isSubtreeReading ) + { + ThrowInSubtreeModeException(); + } + } + } +<# +} +#> +} diff --git a/src/MsgPack/Unpacker.Unpacking.cs b/src/MsgPack/Unpacker.Unpacking.cs index 1b00b57f3..a9be1b97f 100644 --- a/src/MsgPack/Unpacker.Unpacking.cs +++ b/src/MsgPack/Unpacker.Unpacking.cs @@ -1,8 +1,9 @@ -#region -- License Terms -- + +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2016 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -30,8 +31,8 @@ namespace MsgPack { - // This file was generated from Unpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit Unpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude instead. + // This file was generated from Unpacker.Unpacking.tt and Unpacker.Unpacking.ttinclude T4Template. + // Do not modify this file. Edit Unpacker.Unpacking.tt and Unpacker.Unpacking.ttinclude instead. partial class Unpacker { @@ -1985,7 +1986,6 @@ public virtual bool ReadNullableMessagePackExtendedTypeObject( out MessagePackEx #endif // FEATURE_TAP - /// /// Reads next array length value from current stream. /// @@ -2077,7 +2077,6 @@ public virtual async Task> ReadArrayLengthAsync( Cancellat #endif // FEATURE_TAP - /// /// Reads next map length value from current stream. /// @@ -2371,6 +2370,7 @@ public virtual bool ReadObject( out MessagePackObject result ) /// /// Cannot read a value because the underlying stream unexpectedly ends. /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )] public Task> ReadObjectAsync() { return this.ReadObjectAsync( CancellationToken.None ); @@ -2389,6 +2389,7 @@ public Task> ReadObjectAsync() /// /// Cannot read a value because the underlying stream unexpectedly ends. /// + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )] public virtual async Task> ReadObjectAsync( CancellationToken cancellationToken ) { if( !( await this.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) ) @@ -2400,5 +2401,6 @@ public virtual async Task> ReadObjectAsync( C } #endif // FEATURE_TAP + } } diff --git a/src/MsgPack/Unpacker.Unpacking.tt b/src/MsgPack/Unpacker.Unpacking.tt index c75cb08e4..bde2f5c30 100644 --- a/src/MsgPack/Unpacker.Unpacking.tt +++ b/src/MsgPack/Unpacker.Unpacking.tt @@ -1,770 +1,7 @@ <#@ template debug="true" hostSpecific="true" language="C#" #> <#@ output extension=".cs" #> -<#@ include file="..\Core.ttinclude" #> +<#@ include file=".\Unpacker.Unpacking.ttinclude" #> <#@ Assembly Name="System.Core.dll" #> -<#@ import namespace="System" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Diagnostics" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Collections" #> -<#@ import namespace="System.Collections.Generic" #> -#region -- License Terms -- -// -// MessagePack for CLI -// -// Copyright (C) 2010-2016 FUJIWARA, Yusuke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -- License Terms -- - -#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT -#define UNITY -#endif - -using System; -#if FEATURE_TAP -using System.Threading; -using System.Threading.Tasks; -#endif // FEATURE_TAP - -namespace MsgPack -{ - // This file was generated from Unpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude T4Template. - // Do not modify this file. Edit Unpacker.Unpacking.tt and StreamingUnapkcerBase.ttinclude instead. - - partial class Unpacker - { <# -foreach( var type in - new object [] - { - typeof( bool ), - typeof( byte ), typeof( sbyte ), - typeof( short ), typeof( ushort ), - typeof( int ), typeof( uint ), - typeof( long ), typeof( ulong ), - typeof( float ), typeof( double ), - "MessagePackExtendedTypeObject" - } -) -{ +Write( "Unpacker", "virtual", String.Empty, "Unpacker.Unpacking.tt", /* isBase */true ); #> - /// - /// Reads next value from current stream. - /// - /// - /// The value read from current stream to be stored when operation is succeeded. - /// - /// - /// true if expected value was read from stream; false if no more data on the stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not compatible for the type. - /// -<# - if( IsNotCLSCompliant( type as Type ) ) - { -#> - [CLSCompliant( false )] -<# - } -#> - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] - public virtual bool Read<#= GetTypeName( type ) #>( out <#= GetTypeName( type ) #> result ) - { - if( !this.Read() ) - { - result = default( <#= GetTypeName( type ) #> ); - return false; - } - - result = this.LastReadData.As<#= GetTypeName( type ) #>(); - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// a value read from current stream. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not compatible for the type. - /// -<# - if( IsNotCLSCompliant( type as Type ) ) - { -#> - [CLSCompliant( false )] -<# - } -#> - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Task essentially must be nested generic." )] - public <#= AsyncReturn( type, withCancel ) #> Read<#= GetTypeName( type ) #>Async(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.Read<#= GetTypeName( type ) #>Async( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail<#= "<" + GetTypeName( type ) + ">" #>(); - } - - return AsyncReadResult.Success( this.LastReadData.As<#= GetTypeName( type ) #>() ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - - /// - /// Reads next nullable value from current stream. - /// - /// - /// The nullable value read from current stream to be stored when operation is succeeded. - /// - /// - /// The nullable value read from current data source successfully. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not compatible for the nullable type. - /// -<# - if( IsNotCLSCompliant( type as Type ) ) - { -#> - [CLSCompliant( false )] -<# - } -#> - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Adopting same pattern as non-nullables" )] - public virtual bool ReadNullable<#= GetTypeName( type ) #>( out <#= GetTypeName( type ) #>? result ) - { - if( !this.Read() ) - { - result = null; - return false; - } - - result = this.LastReadData.IsNil ? default( <#= GetTypeName( type ) #>? ) : this.LastReadData.As<#= GetTypeName( type ) #>(); - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next nullable value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// a nullable value read from current stream. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not compatible for the nullable type. - /// -<# - if( IsNotCLSCompliant( type as Type ) ) - { -#> - [CLSCompliant( false )] -<# - } -#> - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nullables essentially must be nested generic." )] - public <#= AsyncReturnNullable( type, withCancel ) #> ReadNullable<#= GetTypeName( type ) #>Async(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.ReadNullable<#= GetTypeName( type ) #>Async( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail<#= "<" + GetTypeName( type ) + "?>" #>(); - } - - return AsyncReadResult.Success( this.LastReadData.IsNil ? default( <#= GetTypeName( type ) #>? ) : this.LastReadData.As<#= GetTypeName( type ) #>() ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - -<# -} -#> - - /// - /// Reads next array length value from current stream. - /// - /// - /// The array length read from current stream to be stored when operation is succeeded. - /// - /// - /// true if expected value was read from stream; false if no more data on the stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not an array. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] - public virtual bool ReadArrayLength( out long result ) - { - if( !this.Read() ) - { - result = 0; - return false; - } - - if( !this.IsArrayHeader ) - { - throw new MessageTypeException( "Not in array header." ); - } - - result = this.LastReadData.AsInt64(); - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next array length value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// an array length read from current stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not an array. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] - public <#= AsyncReturn( "long", withCancel ) #> ReadArrayLengthAsync(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.ReadArrayLengthAsync( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail(); - } - - if( !this.IsArrayHeader ) - { - throw new MessageTypeException( "Not in array header." ); - } - - return AsyncReadResult.Success( this.LastReadData.AsInt64() ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - - - /// - /// Reads next map length value from current stream. - /// - /// - /// The map length read from current stream to be stored when operation is succeeded. - /// - /// - /// true if expected value was read from stream; false if no more data on the stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not a map. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] - public virtual bool ReadMapLength( out long result ) - { - if( !this.Read()) - { - result = 0; - return false; - } - - if( !this.IsMapHeader ) - { - throw new MessageTypeException( "Not in map header." ); - } - - result = this.LastReadData.AsInt64(); - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next map length value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// an map length read from current stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not a map. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] - public <#= AsyncReturn( "long", withCancel ) #> ReadMapLengthAsync(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.ReadMapLengthAsync( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail(); - } - - if( !this.IsMapHeader ) - { - throw new MessageTypeException( "Not in map header." ); - } - - return AsyncReadResult.Success( this.LastReadData.AsInt64() ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - - /// - /// Reads next byte array value from current stream. - /// - /// - /// The byte array read from current stream to be stored when operation is succeeded. - /// - /// - /// true if expected value was read from stream; false if no more data on the stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not a raw. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] - public virtual bool ReadBinary( out byte[] result ) - { - if( !this.Read() ) - { - result = null; - return false; - } - - result = this.LastReadData.AsBinary(); - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next byte array value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// a byte array read from current stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not a raw. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] - public <#= AsyncReturn( "byte[]", withCancel ) #> ReadBinaryAsync(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.ReadBinaryAsync( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail(); - } - - return AsyncReadResult.Success( this.LastReadData.AsBinary() ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - - /// - /// Reads next utf-8 encoded string value from current stream. - /// - /// - /// The decoded utf-8 encoded string read from current stream to be stored when operation is succeeded. - /// - /// - /// true if expected value was read from stream; false if no more data on the stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not a raw. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] - public virtual bool ReadString( out string result ) - { - if( !this.Read() ) - { - result = null; - return false; - } - - result = this.LastReadData.AsString(); - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next utf-8 encoded string value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// a decoded utf-8 encoded string read from current stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - /// - /// A value read from data source is not a raw. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] - public <#= AsyncReturn( "string", withCancel ) #> ReadStringAsync(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.ReadStringAsync( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail(); - } - - return AsyncReadResult.Success( this.LastReadData.AsString() ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - - /// - /// Reads next value from current stream. - /// - /// - /// The which represents a value read from current stream to be stored when operation is succeeded. - /// - /// - /// true if expected value was read from stream; false if no more data on the stream. - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] - public virtual bool ReadObject( out MessagePackObject result ) - { - if( !this.Read() ) - { - result = default( MessagePackObject ); - return false; - } - - result = this.LastReadData; - return true; - } - -#if FEATURE_TAP - -<# -foreach ( var withCancel in new [] { false, true } ) -{ -#> - /// - /// Reads next value from current stream asynchronously. - /// -<# - if ( withCancel ) - { -#> - /// The token to monitor for cancellation requests. The default value is . -<# - } -#> - /// - /// A that represents the asynchronous operation. - /// The value of the TResult parameter contains a value whether the operation was succeeded and - /// a which represents a value read from current stream - /// Note that this method throws exception for unexpected state. See exceptions section. - /// - /// - /// Cannot read a value because the underlying stream unexpectedly ends. - /// - public <#= AsyncReturn( "MessagePackObject", withCancel ) #> ReadObjectAsync(<#= Parameter( withCancel ) #>) - { -<# - if ( !withCancel ) - { -#> - return this.ReadObjectAsync( CancellationToken.None ); -<# - } - else - { -#> - if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) - { - return AsyncReadResult.Fail(); - } - - return AsyncReadResult.Success( this.LastReadData ); -<# - } -#> - } - -<# -} -#> -#endif // FEATURE_TAP - } -} -<#+ -private static bool IsNotCLSCompliant( Type type ) -{ - if( type == null ) - { - // MPETO - return false; - } - - switch( Type.GetTypeCode( type ) ) - { - case TypeCode.SByte: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - { - return true; - } - default: - { - return true; - } - } -} - -private static string GetTypeName( object typeOrTypeName ) -{ - return ( typeOrTypeName as string ) ?? ( typeOrTypeName as Type ).Name; -} - -private static string AsyncReturn( object typeOrTypeName, bool withCancel ) -{ - return ( withCancel ? "virtual async " : string.Empty ) + "Task>"; -} - -private static string AsyncReturnNullable( object typeOrTypeName, bool withCancel ) -{ - return ( withCancel ? "virtual async " : string.Empty ) + "Task>"; -} - - -private static string Parameter( bool withCancel ) -{ - return withCancel ? " CancellationToken cancellationToken " : String.Empty; -} - -private static string Argument( bool withCancel ) -{ - return withCancel ? " cancellationToken " : String.Empty; -} -#> \ No newline at end of file diff --git a/src/MsgPack/Unpacker.Unpacking.ttinclude b/src/MsgPack/Unpacker.Unpacking.ttinclude new file mode 100644 index 000000000..5adacf77d --- /dev/null +++ b/src/MsgPack/Unpacker.Unpacking.ttinclude @@ -0,0 +1,1086 @@ +<#@ include file="..\Core.ttinclude" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Runtime.InteropServices" #> +<#@ import namespace="System.Text" #> +<#+ +private void Write( string typeName, string qualifier, string readerType, string fileName, bool isBase ) +{ +#> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT +#define UNITY +#endif + +using System; +#if FEATURE_TAP +using System.Threading; +using System.Threading.Tasks; +#endif // FEATURE_TAP + +namespace MsgPack +{ + // This file was generated from <#= fileName #> and Unpacker.Unpacking.ttinclude T4Template. + // Do not modify this file. Edit <#= fileName #> and Unpacker.Unpacking.ttinclude instead. + + partial class <#= typeName #> + { +<#+ + if ( !isBase ) + { +#> +#if DEBUG + internal +#endif // DEBUG + protected MessagePackUnpacker<<#= readerType #>> Core { get; } + + [Obsolete( "Consumer should not use this property. Query LastReadData instead." )] + public override MessagePackObject? Data + { + get { return this.Core.Data; } + protected set { this.Core.Data = value.GetValueOrDefault(); } + } + + public override bool IsArrayHeader + { + get { return this.Core.CollectionType == CollectionType.Array; } + } + + public override bool IsMapHeader + { + get { return this.Core.CollectionType == CollectionType.Map; } + } + + + public override long ItemsCount + { + get { return this.Core.CollectionType == CollectionType.None ? 0 : this.Core.ItemsCount; } + } + + protected override bool ReadCore() + { + return this.Core.Read(); + } + + protected override long? SkipCore() + { + return this.Core.Skip(); + } + +#if FEATURE_TAP + + protected override Task SkipAsyncCore( CancellationToken cancellationToken ) + { + return this.Core.SkipAsync( cancellationToken ); + } + +#endif // FEATURE_TAP + +<#+ + } + + foreach ( var type in + new object [] + { + typeof( bool ), + typeof( byte ), typeof( sbyte ), + typeof( short ), typeof( ushort ), + typeof( int ), typeof( uint ), + typeof( long ), typeof( ulong ), + typeof( float ), typeof( double ), + "MessagePackExtendedTypeObject" + } + ) + { + if ( isBase ) + { +#> + /// + /// Reads next value from current stream. + /// + /// + /// The value read from current stream to be stored when operation is succeeded. + /// + /// + /// true if expected value was read from stream; false if no more data on the stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not compatible for the type. + /// +<#+ + if ( IsNotCLSCompliant( type as Type ) ) + { +#> + [CLSCompliant( false )] +<#+ + } + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] + public <#= qualifier #> bool Read<#= GetTypeName( type ) #>( out <#= GetTypeName( type ) #> result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read() ) + { + result = default( <#= GetTypeName( type ) #> ); + return false; + } + + result = this.LastReadData.As<#= GetTypeName( type ) #>(); + return true; +<#+ + } + else + { +#> + return this.Core.Read<#= GetTypeName( type ) #>( out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// a value read from current stream. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not compatible for the type. + /// +<#+ + if( IsNotCLSCompliant( type as Type ) ) + { +#> + [CLSCompliant( false )] +<#+ + } + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Task essentially must be nested generic." )] + public <#= AsyncReturn( type, withCancel, isBase ) #> Read<#= GetTypeName( type ) #>Async(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.Read<#= GetTypeName( type ) #>Async( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail<#= "<" + GetTypeName( type ) + ">" #>(); + } + + return AsyncReadResult.Success( this.LastReadData.As<#= GetTypeName( type ) #>() ); +<#+ + } + else + { +#> + return this.Core.Read<#= GetTypeName( type ) #>Async(<#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + +<#+ + if ( isBase ) + { +#> + /// + /// Reads next nullable value from current stream. + /// + /// + /// The nullable value read from current stream to be stored when operation is succeeded. + /// + /// + /// The nullable value read from current data source successfully. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not compatible for the nullable type. + /// +<#+ + if ( IsNotCLSCompliant( type as Type ) ) + { +#> + [CLSCompliant( false )] +<#+ + } + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Adopting same pattern as non-nullables" )] + public <#= qualifier #> bool ReadNullable<#= GetTypeName( type ) #>( out <#= GetTypeName( type ) #>? result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read() ) + { + result = null; + return false; + } + + result = this.LastReadData.IsNil ? default( <#= GetTypeName( type ) #>? ) : this.LastReadData.As<#= GetTypeName( type ) #>(); + return true; +<#+ + } + else + { +#> + return this.Core.ReadNullable<#= GetTypeName( type ) #>( out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next nullable value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// a nullable value read from current stream. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not compatible for the nullable type. + /// +<#+ + if( IsNotCLSCompliant( type as Type ) ) + { +#> + [CLSCompliant( false )] +<#+ + } + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nullables essentially must be nested generic." )] + public <#= AsyncReturnNullable( type, withCancel, isBase ) #> ReadNullable<#= GetTypeName( type ) #>Async(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.ReadNullable<#= GetTypeName( type ) #>Async( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail<#= "<" + GetTypeName( type ) + "?>" #>(); + } + + return AsyncReadResult.Success( this.LastReadData.IsNil ? default( <#= GetTypeName( type ) #>? ) : this.LastReadData.As<#= GetTypeName( type ) #>() ); +<#+ + } + else + { +#> + return this.Core.ReadNullable<#= GetTypeName( type ) #>Async(<#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + +<#+ + } // foreach (type) +#> + +<#+ + if ( isBase ) + { +#> + /// + /// Reads next array length value from current stream. + /// + /// + /// The array length read from current stream to be stored when operation is succeeded. + /// + /// + /// true if expected value was read from stream; false if no more data on the stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not an array. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] + public <#= qualifier #> bool ReadArrayLength( out long result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read() ) + { + result = 0; + return false; + } + + if( !this.IsArrayHeader ) + { + throw new MessageTypeException( "Not in array header." ); + } + + result = this.LastReadData.AsInt64(); + return true; +<#+ + } + else + { +#> + return this.Core.ReadArrayLength( out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next array length value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// an array length read from current stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not an array. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] + public <#= AsyncReturn( "long", withCancel, isBase ) #> ReadArrayLengthAsync(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.ReadArrayLengthAsync( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail(); + } + + if( !this.IsArrayHeader ) + { + throw new MessageTypeException( "Not in array header." ); + } + + return AsyncReadResult.Success( this.LastReadData.AsInt64() ); +<#+ + } + else + { +#> + return this.Core.ReadArrayLengthAsync(<#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + +<#+ + if ( isBase ) + { +#> + /// + /// Reads next map length value from current stream. + /// + /// + /// The map length read from current stream to be stored when operation is succeeded. + /// + /// + /// true if expected value was read from stream; false if no more data on the stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not a map. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] + public <#= qualifier #> bool ReadMapLength( out long result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read()) + { + result = 0; + return false; + } + + if( !this.IsMapHeader ) + { + throw new MessageTypeException( "Not in map header." ); + } + + result = this.LastReadData.AsInt64(); + return true; +<#+ + } + else + { +#> + return this.Core.ReadMapLength( out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next map length value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// an map length read from current stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not a map. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] + public <#= AsyncReturn( "long", withCancel, isBase ) #> ReadMapLengthAsync(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.ReadMapLengthAsync( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail(); + } + + if( !this.IsMapHeader ) + { + throw new MessageTypeException( "Not in map header." ); + } + + return AsyncReadResult.Success( this.LastReadData.AsInt64() ); +<#+ + } + else + { +#> + return this.Core.ReadMapLengthAsync(<#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + +<#+ + if ( isBase ) + { +#> + /// + /// Reads next byte array value from current stream. + /// + /// + /// The byte array read from current stream to be stored when operation is succeeded. + /// + /// + /// true if expected value was read from stream; false if no more data on the stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not a raw. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] + public <#= qualifier #> bool ReadBinary( out byte[] result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read() ) + { + result = null; + return false; + } + + result = this.LastReadData.AsBinary(); + return true; +<#+ + } + else + { +#> + return this.Core.ReadBinary( out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next byte array value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// a byte array read from current stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not a raw. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] + public <#= AsyncReturn( "byte[]", withCancel, isBase ) #> ReadBinaryAsync(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.ReadBinaryAsync( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail(); + } + + return AsyncReadResult.Success( this.LastReadData.AsBinary() ); +<#+ + } + else + { +#> + return this.Core.ReadBinaryAsync(<#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + +<#+ + if ( isBase ) + { +#> + /// + /// Reads next utf-8 encoded string value from current stream. + /// + /// + /// The decoded utf-8 encoded string read from current stream to be stored when operation is succeeded. + /// + /// + /// true if expected value was read from stream; false if no more data on the stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not a raw. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] + public <#= qualifier #> bool ReadString( out string result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read() ) + { + result = null; + return false; + } + + result = this.LastReadData.AsString(); + return true; +<#+ + } + else + { +#> + return this.Core.ReadString( out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next utf-8 encoded string value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// a decoded utf-8 encoded string read from current stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// + /// + /// A value read from data source is not a raw. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Collections/Delegates/Nullables/Task essentially must be nested generic." )] + public <#= AsyncReturn( "string", withCancel, isBase ) #> ReadStringAsync(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.ReadStringAsync( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail(); + } + + return AsyncReadResult.Success( this.LastReadData.AsString() ); +<#+ + } + else + { +#> + return this.Core.ReadStringAsync(<#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + +<#+ + if ( isBase ) + { +#> + /// + /// Reads next value from current stream. + /// + /// + /// The which represents a value read from current stream to be stored when operation is succeeded. + /// + /// + /// true if expected value was read from stream; false if no more data on the stream. + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Using nullable return value is very slow" )] + public <#= qualifier #> bool ReadObject( out MessagePackObject result ) + { +<#+ + if ( isBase ) + { +#> + if( !this.Read() ) + { + result = default( MessagePackObject ); + return false; + } + + result = this.LastReadData; + return true; +<#+ + } + else + { +#> + return this.Core.ReadObject( /* isDeep*/true, out result ); +<#+ + } +#> + } + +#if FEATURE_TAP + +<#+ + foreach ( var withCancel in new [] { false, true } ) + { + if ( !isBase ) + { + if ( !withCancel ) + { + continue; + } + } + else + { +#> + /// + /// Reads next value from current stream asynchronously. + /// +<#+ + if ( withCancel ) + { +#> + /// The token to monitor for cancellation requests. The default value is . +<#+ + } +#> + /// + /// A that represents the asynchronous operation. + /// The value of the TResult parameter contains a value whether the operation was succeeded and + /// a which represents a value read from current stream + /// Note that this method throws exception for unexpected state. See exceptions section. + /// + /// + /// Cannot read a value because the underlying stream unexpectedly ends. + /// +<#+ + } +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design" )] + public <#= AsyncReturn( "MessagePackObject", withCancel, isBase ) #> ReadObjectAsync(<#= Parameter( withCancel ) #>) + { +<#+ + if ( !withCancel ) + { +#> + return this.ReadObjectAsync( CancellationToken.None ); +<#+ + } + else if ( isBase ) + { +#> + if( !( await this.ReadAsync(<#= Argument( withCancel ) #>).ConfigureAwait( false ) ) ) + { + return AsyncReadResult.Fail(); + } + + return AsyncReadResult.Success( this.LastReadData ); +<#+ + } + else + { +#> + return this.Core.ReadObjectAsync( /* isDeep*/true, <#= Argument( withCancel ) #>); +<#+ + } +#> + } + +<#+ + } // foreach (withCancel) +#> +#endif // FEATURE_TAP + + } +} +<#+ +} // Write + +private static bool IsNotCLSCompliant( Type type ) +{ + if( type == null ) + { + // MPETO + return false; + } + + switch( Type.GetTypeCode( type ) ) + { + case TypeCode.SByte: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + { + return true; + } + default: + { + return true; + } + } +} + +private static string GetTypeName( object typeOrTypeName ) +{ + return ( typeOrTypeName as string ) ?? ( typeOrTypeName as Type ).Name; +} + +private static string AsyncReturn( object typeOrTypeName, bool withCancel, bool isBase ) +{ + return ( withCancel ? ( isBase ? "virtual async " : "override " ) : string.Empty ) + "Task>"; +} + +private static string AsyncReturnNullable( object typeOrTypeName, bool withCancel, bool isBase ) +{ + return ( withCancel ? ( isBase ? "virtual async " : "override " ) : string.Empty ) + "Task>"; +} + + +private static string Parameter( bool withCancel ) +{ + return withCancel ? " CancellationToken cancellationToken " : String.Empty; +} + +private static string Argument( bool withCancel ) +{ + return withCancel ? " cancellationToken " : String.Empty; +} +#> diff --git a/src/MsgPack/Unpacker.cs b/src/MsgPack/Unpacker.cs index 7c0098ddb..72cfa9ae5 100644 --- a/src/MsgPack/Unpacker.cs +++ b/src/MsgPack/Unpacker.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,6 +25,11 @@ using System; using System.Collections; using System.Collections.Generic; +#if FEATURE_MPCONTRACT +using Contract = MsgPack.MPContract; +#else +using System.Diagnostics.Contracts; +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.IO; #if FEATURE_TAP @@ -32,7 +37,6 @@ using System.Threading.Tasks; #endif // FEATURE_TAP - namespace MsgPack { /// @@ -74,10 +78,10 @@ public abstract MessagePackObject? Data /// public virtual MessagePackObject LastReadData { -#pragma warning disable 612,618 +#pragma warning disable 612, 618 get { return this.Data.GetValueOrDefault(); } protected set { this.Data = value; } -#pragma warning restore 612,618 +#pragma warning restore 612, 618 } /// @@ -128,8 +132,6 @@ public abstract long ItemsCount } private UnpackerMode _mode = UnpackerMode.Unknown; - // ReSharper disable once RedundantDefaultFieldInitializer - private bool _isSubtreeReading = false; /// /// Verifies the mode. @@ -141,7 +143,7 @@ public abstract long ItemsCount /// /// Is in incompatible mode. /// - private void VerifyMode( UnpackerMode mode ) + internal void VerifyMode( UnpackerMode mode ) { this.VerifyIsNotDisposed(); @@ -160,7 +162,7 @@ private void VerifyMode( UnpackerMode mode ) /// /// Verifies this instance is not disposed. /// - private void VerifyIsNotDisposed() + internal void VerifyIsNotDisposed() { if ( this._mode == UnpackerMode.Disposed ) { @@ -173,7 +175,7 @@ private void ThrowObjectDisposedException() throw new ObjectDisposedException( this.GetType().FullName ); } - private void ThrowInvalidModeException() + internal void ThrowInvalidModeException() { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "Reader is in '{0}' mode.", this._mode ) ); } @@ -194,7 +196,7 @@ internal virtual long? UnderlyingStreamPosition { get { return null; } } -#endif +#endif /// /// Gets the previous position before last operation for debugging. @@ -215,7 +217,8 @@ internal virtual bool GetPreviousPosition( out long offsetOrPosition ) /// Creates the new from specified stream. /// /// The stream to be unpacked. This stream will be closed when is called. - /// instance. + /// instance. This value will not be null. + /// is null. public static Unpacker Create( Stream stream ) { return Create( stream, true ); @@ -229,10 +232,11 @@ public static Unpacker Create( Stream stream ) /// true to close when this instance is disposed; /// false, otherwise. /// - /// instance. + /// instance. This value will not be null. + /// is null. public static Unpacker Create( Stream stream, bool ownsStream ) { - return new ItemsUnpacker( stream, ownsStream ? PackerUnpackerStreamOptions.SingletonOwnsStream : null ); + return Create( stream, ownsStream ? PackerUnpackerStreamOptions.SingletonOwnsStream : null, null ); } /// @@ -240,10 +244,94 @@ public static Unpacker Create( Stream stream, bool ownsStream ) /// /// The stream to be unpacked. /// which specifies stream handling options. - /// instance. + /// instance. This value will not be null. + /// is null. public static Unpacker Create( Stream stream, PackerUnpackerStreamOptions streamOptions ) { - return new ItemsUnpacker( stream, streamOptions ); + return Create( stream, streamOptions, null ); + } + + /// + /// Creates the new from specified stream. + /// + /// The stream to be unpacked. + /// which specifies stream handling options. + /// which specifies various options. Specify null to use default options. + /// instance. This value will not be null. + /// is null. + public static Unpacker Create( Stream stream, PackerUnpackerStreamOptions streamOptions, UnpackerOptions unpackerOptions ) + { + if ( unpackerOptions == null || unpackerOptions.ValidationLevel == UnpackerValidationLevel.Collection ) + { + return new CollectionValidatingStreamUnpacker( stream, streamOptions ); + } + else + { + return new FastStreamUnpacker( stream, streamOptions ); + } + } + + /// + /// Creates a new from specified byte array. + /// + /// The source byte array. + /// instance. This value will not be null. + /// is null. + public static ByteArrayUnpacker Create( byte[] source ) + { + return Create( source, null ); + } + + /// + /// Creates a new from specified byte array. + /// + /// The source byte array. + /// The effective start offset of the . + /// instance. This value will not be null. + /// is null. + /// + /// is negative. + /// + /// The array length of is too small. + public static ByteArrayUnpacker Create( byte[] source, int startOffset ) + { + return Create( source, startOffset, null ); + } + + /// + /// Creates a new from specified byte array. + /// + /// The source byte array. + /// which specifies various options. Specify null to use default options. + /// instance. This value will not be null. + /// is null. + public static ByteArrayUnpacker Create( byte[] source, UnpackerOptions unpackerOptions ) + { + return Create( source, 0, unpackerOptions ); + } + + /// + /// Creates a new from specified byte array. + /// + /// The source byte array. + /// The effective start offset of the . + /// which specifies various options. Specify null to use default options. + /// instance. This value will not be null. + /// is null. + /// + /// is negative. + /// + /// The array length of is too small. + public static ByteArrayUnpacker Create( byte[] source, int startOffset, UnpackerOptions unpackerOptions ) + { + if ( unpackerOptions == null || unpackerOptions.ValidationLevel == UnpackerValidationLevel.Collection ) + { + return new CollectionValidatingByteArrayUnpacker( source, startOffset ); + } + else + { + return new FastByteArrayUnpacker( source, startOffset ); + } } #endregion -- Factories -- @@ -357,27 +445,20 @@ public virtual Task DrainAsync( CancellationToken cancellationToken ) /// public Unpacker ReadSubtree() { - if ( !this.IsCollectionHeader ) - { - ThrowCannotBeSubtreeModeException(); - } - - if ( this._isSubtreeReading ) - { - ThrowInSubtreeModeException(); - } + return this.InternalReadSubtree(); + } - var subtreeReader = this.ReadSubtreeCore(); - this._isSubtreeReading = !ReferenceEquals( subtreeReader, this ); - return subtreeReader; + internal virtual Unpacker InternalReadSubtree() + { + return this.ReadSubtreeCore(); } - private static void ThrowCannotBeSubtreeModeException() + internal static void ThrowCannotBeSubtreeModeException() { throw new InvalidOperationException( "Unpacker does not locate on array nor map header." ); } - private static void ThrowInSubtreeModeException() + internal static void ThrowInSubtreeModeException() { throw new InvalidOperationException( "Unpacker is in 'Subtree' mode." ); } @@ -400,7 +481,6 @@ private static void ThrowInSubtreeModeException() /// protected internal virtual void EndReadSubtree() { - this._isSubtreeReading = false; this.SetStable(); } @@ -420,7 +500,11 @@ protected internal virtual void EndReadSubtree() public bool Read() { this.EnsureNotInSubtreeMode(); + return this.ReadInternal(); + } + internal bool ReadInternal() + { bool result = this.ReadCore(); if ( result && !this.IsCollectionHeader ) { @@ -430,14 +514,7 @@ public bool Read() return result; } - internal void EnsureNotInSubtreeMode() - { - this.VerifyMode( UnpackerMode.Streaming ); - if ( this._isSubtreeReading ) - { - ThrowInSubtreeModeException(); - } - } + internal virtual void EnsureNotInSubtreeMode() { } private void SetStable() { @@ -490,10 +567,14 @@ public Task ReadAsync() /// /// The underying stream unexpectedly ended. /// - public async Task ReadAsync( CancellationToken cancellationToken ) + public Task ReadAsync( CancellationToken cancellationToken ) { this.EnsureNotInSubtreeMode(); + return this.ReadInternalAsync( cancellationToken ); + } + internal async Task ReadInternalAsync( CancellationToken cancellationToken ) + { bool result = await this.ReadAsyncCore( cancellationToken ).ConfigureAwait( false ); if ( result && !this.IsCollectionHeader ) { @@ -579,14 +660,11 @@ private void BeginSkip() this.ThrowInvalidModeException(); } - if ( this._isSubtreeReading ) - { - ThrowInSubtreeModeException(); - } - this._mode = UnpackerMode.Skipping; } + internal virtual void BeginSkipCore() { } + private void EndSkip( long? result ) { if ( result != null ) @@ -689,9 +767,9 @@ private void EndSkip( long? result ) this.UnpackSubtree(); -#pragma warning disable 612,618 +#pragma warning disable 612, 618 return this.Data; -#pragma warning restore 612,618 +#pragma warning restore 612, 618 } /// @@ -748,9 +826,9 @@ public MessagePackObject ReadItemData() await this.UnpackSubtreeAsync( cancellationToken ).ConfigureAwait( false ); -#pragma warning disable 612,618 +#pragma warning disable 612, 618 return this.Data; -#pragma warning restore 612,618 +#pragma warning restore 612, 618 } /// @@ -997,7 +1075,7 @@ internal async Task> UnpackSubtreeDataAsyncCo #endif // FEATURE_TAP - private enum UnpackerMode + internal enum UnpackerMode { Unknown = 0, Skipping, diff --git a/src/MsgPack/UnpackerOptions.cs b/src/MsgPack/UnpackerOptions.cs new file mode 100644 index 000000000..aa2ca76bb --- /dev/null +++ b/src/MsgPack/UnpackerOptions.cs @@ -0,0 +1,43 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Represents various option settings. + /// + public sealed class UnpackerOptions + { + /// + /// Gets or sets validation level of the . + /// + public UnpackerValidationLevel ValidationLevel { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public UnpackerOptions() + { + this.ValidationLevel = UnpackerValidationLevel.Collection; + } + } +} diff --git a/src/MsgPack/UnpackerValidationLevel.cs b/src/MsgPack/UnpackerValidationLevel.cs new file mode 100644 index 000000000..d1aa87e2e --- /dev/null +++ b/src/MsgPack/UnpackerValidationLevel.cs @@ -0,0 +1,40 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + /// + /// Specifies validation behavior level of . + /// + public enum UnpackerValidationLevel + { + /// + /// No validation. Although this improves unpacking performance, trouble shooting becomes hard. + /// + None = 0, + + /// + /// Validates collection nesting. This options is default for backward compatibility. + /// + Collection + } +} diff --git a/src/MsgPack/Unpacking.Numerics.cs b/src/MsgPack/Unpacking.Numerics.cs index fe9252e58..de6fdfcf6 100644 --- a/src/MsgPack/Unpacking.Numerics.cs +++ b/src/MsgPack/Unpacking.Numerics.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.IO; namespace MsgPack @@ -1300,4 +1300,4 @@ private static Double UnpackDoubleCore( Stream source ) } } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Unpacking.Numerics.tt b/src/MsgPack/Unpacking.Numerics.tt index 0defe268b..b6f34a40f 100644 --- a/src/MsgPack/Unpacking.Numerics.tt +++ b/src/MsgPack/Unpacking.Numerics.tt @@ -1,4 +1,4 @@ -<# +<# // // MessagePack for CLI // @@ -70,11 +70,11 @@ Func __isClsCompliant = #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.IO; namespace MsgPack @@ -241,4 +241,4 @@ foreach( var __type in __numericTypes ) } #> } -} \ No newline at end of file +} diff --git a/src/MsgPack/Unpacking.Others.cs b/src/MsgPack/Unpacking.Others.cs index f667831e3..4fc34d91a 100644 --- a/src/MsgPack/Unpacking.Others.cs +++ b/src/MsgPack/Unpacking.Others.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -25,11 +25,11 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.IO; namespace MsgPack diff --git a/src/MsgPack/Unpacking.Others.tt b/src/MsgPack/Unpacking.Others.tt index 239a831ba..19f97bdf4 100644 --- a/src/MsgPack/Unpacking.Others.tt +++ b/src/MsgPack/Unpacking.Others.tt @@ -1,4 +1,4 @@ -<# +<# // // MessagePack for CLI // @@ -70,11 +70,11 @@ var __methods = new [] using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.IO; namespace MsgPack @@ -317,4 +317,4 @@ private static string ToSeeElement( string typeName ) return buffer.ToString(); } -#> \ No newline at end of file +#> diff --git a/src/MsgPack/Unpacking.Streaming.cs b/src/MsgPack/Unpacking.Streaming.cs index 2389c23a6..31f6be1d0 100644 --- a/src/MsgPack/Unpacking.Streaming.cs +++ b/src/MsgPack/Unpacking.Streaming.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.IO; using System.Text; diff --git a/src/MsgPack/Unpacking.String.cs b/src/MsgPack/Unpacking.String.cs index 76fe610cc..145c791e6 100644 --- a/src/MsgPack/Unpacking.String.cs +++ b/src/MsgPack/Unpacking.String.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.IO; using System.Text; diff --git a/src/MsgPack/UnpackingStream.cs b/src/MsgPack/UnpackingStream.cs index 6e7b9a444..bbfcc8bc7 100644 --- a/src/MsgPack/UnpackingStream.cs +++ b/src/MsgPack/UnpackingStream.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.IO; namespace MsgPack diff --git a/src/MsgPack/UnsafeNativeMethods.cs b/src/MsgPack/UnsafeNativeMethods.cs index 664958deb..b870a2ff3 100644 --- a/src/MsgPack/UnsafeNativeMethods.cs +++ b/src/MsgPack/UnsafeNativeMethods.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -29,9 +29,9 @@ namespace MsgPack #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 [SuppressUnmanagedCodeSecurity] #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 -#if !NETFX_35 +#if !NET35 [SecurityCritical] -#endif // !NETFX_35 +#endif // !NET35 internal static class UnsafeNativeMethods { private static int _libCAvailability = 0; @@ -40,18 +40,20 @@ internal static class UnsafeNativeMethods private const int _libCAvailability_LibC = 2; private const int _libCAvailability_None = -1; -#if NETFX_35 +#if !XAMARIN +#if NET35 [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "OK, this is SecurityCritical" )] -#endif // NETFX_35 +#endif // NET35 [DllImport( "msvcrt", CallingConvention = CallingConvention.Cdecl, EntryPoint = "memcmp", ExactSpelling = true, SetLastError = false )] private static extern int memcmpVC( byte[] s1, byte[] s2, /*SIZE_T*/UIntPtr size ); +#endif // !XAMARIN #if !NETFX_CORE // libc is for non Windows environment. // Note that libc caused compilation error on .NET Native, so the DllImport itself should not be included in the first time. -#if NETFX_35 +#if NET35 [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "OK, this is SecurityCritical" )] -#endif // NETFX_35 +#endif // NET35 [DllImport( "libc", CallingConvention = CallingConvention.Cdecl, EntryPoint = "memcmp", ExactSpelling = true, SetLastError = false )] private static extern int memcmpLibC( byte[] s1, byte[] s2, /*SIZE_T*/UIntPtr size ); #endif // !NETFX_CORE @@ -64,6 +66,7 @@ public static bool TryMemCmp( byte[] s1, byte[] s2, /*SIZE_T*/UIntPtr size, out return false; } +#if !XAMARIN if ( _libCAvailability <= _libCAvailability_MSVCRT ) { try @@ -80,6 +83,7 @@ public static bool TryMemCmp( byte[] s1, byte[] s2, /*SIZE_T*/UIntPtr size, out #endif // !NETFX_CORE } } +#endif // !XAMARIN #if !NETFX_CORE if ( _libCAvailability <= _libCAvailability_LibC ) @@ -100,4 +104,4 @@ public static bool TryMemCmp( byte[] s1, byte[] s2, /*SIZE_T*/UIntPtr size, out return false; } } -} \ No newline at end of file +} diff --git a/src/MsgPack/Validation.cs b/src/MsgPack/Validation.cs index 1a42a31a4..91c933372 100644 --- a/src/MsgPack/Validation.cs +++ b/src/MsgPack/Validation.cs @@ -23,11 +23,11 @@ #endif using System; -#if CORE_CLR || UNITY +#if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; -#endif // CORE_CLR || UNITY +#endif // FEATURE_MPCONTRACT using System.Globalization; using System.Text.RegularExpressions; diff --git a/src/MsgPack.Net35/Volatile.cs b/src/MsgPack/Volatile.cs similarity index 100% rename from src/MsgPack.Net35/Volatile.cs rename to src/MsgPack/Volatile.cs diff --git a/src/mpu/AssetFileImporter.cs b/src/mpu/AssetFileImporter.cs index 5f8a0b85d..481e3f2cc 100644 --- a/src/mpu/AssetFileImporter.cs +++ b/src/mpu/AssetFileImporter.cs @@ -51,11 +51,11 @@ public sealed class AssetFileImporter public AssetFileImporter() { } /// - /// Assembles the asset tree from MsgPack.Unity3D.csproj file. + /// Assembles the asset tree from MsgPack.Unity.csproj file. /// /// /// The source project file path which points to MsgPack.Unity3D.csproj. - /// If omitted, ./src/MsgPack.Unity3D/MsgPack.Unity3D.csproj will be used. + /// If omitted, ./src/MsgPack.Unity/MsgPack.Unity.csproj will be used. /// /// /// The output directory path the copied source file (assets file) will be placed. @@ -77,7 +77,7 @@ public void AssembleAssetTree( string sourceProjectPath, string outputDirectoryP sourceProjectPath = String.Format( CultureInfo.InvariantCulture, - ".{0}src{0}MsgPack.Unity3D{0}MsgPack.Unity3D.csproj", + ".{0}src{0}MsgPack.Unity{0}MsgPack.Unity.csproj", Path.DirectorySeparatorChar ); } @@ -94,17 +94,19 @@ public void AssembleAssetTree( string sourceProjectPath, string outputDirectoryP var sourceDirectoryPath = Path.GetDirectoryName( sourceProjectPath ); var relativePrefix = ".." + Path.DirectorySeparatorChar; - foreach ( var sourceFileRelativePath in this.ParseProjectFile( sourceProjectPath ).Select( p => p.Replace( '\\', Path.DirectorySeparatorChar )) ) + foreach ( var sourceFileRelativePath in this.ParseProjectFile( sourceProjectPath ).Select( p => p.Replace( '\\', Path.DirectorySeparatorChar ) ) ) { var destinationFilePath = Path.Combine( outputDirectoryPath, - new String( - ( sourceFileRelativePath.StartsWith( relativePrefix ) ? sourceFileRelativePath.Substring( 3 ) : sourceFileRelativePath ) // remove relative + sourceFileRelativePath.StartsWith( relativePrefix ) + ? new String( + sourceFileRelativePath.Substring( 3 ) // remove relative .SkipWhile( c => c != Path.DirectorySeparatorChar) // remove project name portion .Skip( 1 ) .ToArray() ) + : sourceFileRelativePath // descendant path only ); // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory( Path.GetDirectoryName( destinationFilePath ) ); diff --git a/src/mpu/Program.cs b/src/mpu/Program.cs index 9fcc6fcd6..46b4474f1 100644 --- a/src/mpu/Program.cs +++ b/src/mpu/Program.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2014 FUJIWARA, Yusuke +// Copyright (C) 2014-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ using Mono.Options; +using MsgPack; using MsgPack.Serialization; namespace mpu @@ -82,6 +83,7 @@ private static int Execute( IEnumerable args ) var excludingPattern = default( string ); var treatWarningsAsErrors = false; var warningLevel = 4; + var admitNonPublicTypes = false; var configuration = new SerializerCodeGenerationConfiguration { @@ -138,12 +140,32 @@ private static int Execute( IEnumerable args ) }, { "singular", "[serializer, optional] Specify avoid recursive serializer generation for target type(s).", - _ => configuration.PreferReflectionBasedSerializer = false + _ => configuration.IsRecursive = false }, { "avoid-reflection-based", "[serializer, optional] Specify avoid built-in reflection based serializer and generates alternative serializers.", _ => configuration.PreferReflectionBasedSerializer = false }, + { + "prohibit-non-collection-enumerable-types", "[serializer, optional] Specify prevent serializer generation for types which implemnent IEnumerable but do not have add for backward compatibility.", + _ => configuration.CompatibilityOptions.AllowNonCollectionEnumerableTypes = false + }, + { + "ignore-packability-for-collection", "[serializer, optional] Specify generate normal collection serializer logic for types which implemnent IEnumerable and IPackable/IUnpackble/IAsyncPackable/IAsyncUnpackable for backward compatiblity.", + _ => configuration.CompatibilityOptions.IgnorePackabilityForCollection = false + }, + { + "one-bound-data-member-order", "[serializer, optional] Specify generating serializers use 1-based DataMemberAttribute.order instead of 0-based for compatibility of some other serialization libraries.", + _ => configuration.CompatibilityOptions.OneBoundDataMemberOrder = false + }, + { + "classic-packer", "[serializer, optional] Specify that packer does not emit new bin, str8, and ext types.", + _ => configuration.CompatibilityOptions.PackerCompatibilityOptions = PackerCompatibilityOptions.Classic + }, + { + "with-async", "[serializer, optional] Specify generating async methods on serializers. This option causes compilation error for legacy environments including Unity.", + _ => configuration.WithAsync = true + }, { "indent=", "[serializer, optional] Specify indent string for generated serializers. Default is a horizontal tab charactor (U+0009).", value => configuration.CodeIndentString = value @@ -161,12 +183,20 @@ private static int Execute( IEnumerable args ) value => excludingPattern = value }, { - "treatWarningsAsErrors", "[serializer, optional] Specify to generate error for compiler warnings for serialization target types.", + "admit-non-public-types", "[serializer, optional] Specify to enable code generation for non-public types.", + _ => admitNonPublicTypes = true + }, + { + "treat-warning-as-errors|treatWarningsAsErrors", "[serializer, optional] Specify to generate error for compiler warnings for serialization target types.", _ => treatWarningsAsErrors = true }, { - "warningLevel=", "[serializer, optional] Specify compiler warning level for serialization target types. Default is '4'.", - (int value) => warningLevel = value + "warning-level|warningLevel=", "[serializer, optional] Specify compiler warning level for serialization target types. Default is '4'.", + ( int value ) => warningLevel = value + }, + { + "suppress-debugger-non-user-code-attr", "[serializer, optional] Specify supressing DebuggerNonUserCodeAttribute in the output code to enable debugger stepping.", + _ => configuration.SuppressDebuggerNonUserCodeAttribute = true } }; @@ -195,6 +225,7 @@ private static int Execute( IEnumerable args ) excludingPattern, treatWarningsAsErrors, warningLevel, + admitNonPublicTypes, configuration ); return 0; @@ -263,6 +294,7 @@ private static void GenerateSerializers( string excludingPattern, bool treatWarningsAsErrors, int warningLevel, + bool admitNonPublicTypes, SerializerCodeGenerationConfiguration configuration ) { @@ -286,8 +318,9 @@ SerializerCodeGenerationConfiguration configuration referenceAssemblies ?? new string[ 0 ] ), includingPattern, - excludingPattern - ); + excludingPattern, + admitNonPublicTypes + ); } else { @@ -295,8 +328,9 @@ SerializerCodeGenerationConfiguration configuration generator.GenerateSerializers( sourceFilePathes[ 0 ], includingPattern, - excludingPattern - ); + excludingPattern, + admitNonPublicTypes + ); } foreach ( var outputFilePath in result ) diff --git a/src/mpu/SerializerCodeGenerator.cs b/src/mpu/SerializerCodeGenerator.cs index 04019a8ed..7b335b7d4 100644 --- a/src/mpu/SerializerCodeGenerator.cs +++ b/src/mpu/SerializerCodeGenerator.cs @@ -71,15 +71,17 @@ public SerializerCodeGenerator( SerializerCodeGenerationConfiguration configurat public IEnumerable GenerateSerializers( string sourceAssemblyFile, string includingPattern, - string excludingPattern - ) + string excludingPattern, + bool admitNonPublicTypes + ) { return this.GenerateSerializers( Assembly.LoadFrom( sourceAssemblyFile ), includingPattern, - excludingPattern - ); + excludingPattern, + admitNonPublicTypes + ); } /// @@ -95,8 +97,9 @@ string excludingPattern public IEnumerable GenerateSerializers( Assembly sourceAssembly, string includingPattern, - string excludingPattern - ) + string excludingPattern, + bool admitNonPublicTypes + ) { if ( sourceAssembly == null ) { @@ -129,13 +132,13 @@ string excludingPattern sourceAssembly.GetTypes() .Where( type => - type.IsPublic + (admitNonPublicTypes || type.IsPublic) && !type.IsAbstract && !type.IsInterface && ( includingRegex == null || includingRegex.IsMatch( type.FullName ) ) && ( excludingRegex == null || !excludingRegex.IsMatch( type.FullName ) ) ).ToArray() - ); + ); } } diff --git a/src/mpu/SerializerTargetCompiler.cs b/src/mpu/SerializerTargetCompiler.cs index c4575d3c4..27eb00049 100644 --- a/src/mpu/SerializerTargetCompiler.cs +++ b/src/mpu/SerializerTargetCompiler.cs @@ -104,7 +104,7 @@ IEnumerable referenceAssemblies : this.ErrorWriter == Console.Error ? ColorizedTextWriter.ForConsoleError() : ColorizedTextWriter.ForTextWriter( this.ErrorWriter ) - ); + ); if ( sourceAssembly == null ) { @@ -150,7 +150,7 @@ ColorizedTextWriter errorWriter CodeDomProvider.CreateProvider( "C#" ).CompileAssemblyFromFile( compilerParameters, sourceFilePathes.ToArray() - ); + ); foreach ( var stdout in results.Output ) { @@ -171,7 +171,7 @@ ColorizedTextWriter errorWriter error.Column, error.ErrorNumber, error.ErrorText - ); + ); if ( error.IsWarning ) { diff --git a/src/mpu/app.config b/src/mpu/app.config new file mode 100644 index 000000000..51278a456 --- /dev/null +++ b/src/mpu/app.config @@ -0,0 +1,3 @@ + + + diff --git a/src/mpu/mpu.csproj b/src/mpu/mpu.csproj index b286aed44..f8f124698 100644 --- a/src/mpu/mpu.csproj +++ b/src/mpu/mpu.csproj @@ -1,6 +1,5 @@  - - + Debug AnyCPU @@ -9,10 +8,10 @@ Properties mpu mpu - v3.5 + net35;net45 512 - ..\..\ true + false AnyCPU @@ -23,6 +22,7 @@ DEBUG;TRACE prompt 4 + false AnyCPU @@ -32,6 +32,7 @@ TRACE prompt 4 + false @@ -43,37 +44,11 @@ Properties\CommonAssemblyInfo.cs - - - - - - - - - + - - {c5490cdc-3b79-42dc-acfb-75a62e55862c} - MsgPack.Net35 - + - - - - - このプロジェクトは、このコンピューターにはない NuGet パッケージを参照しています。これらをダウンロードするには、NuGet パッケージの復元を有効にしてください。詳細については、http://go.microsoft.com/fwlink/?LinkID=322105 を参照してください。不足しているファイルは {0} です。 - - - - \ No newline at end of file diff --git a/src/mpu/packages.config b/src/mpu/packages.config deleted file mode 100644 index cb52cc4bd..000000000 --- a/src/mpu/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/netstandard/build/NetStandardProjectBuilder.csproj b/src/netstandard/build/NetStandardProjectBuilder.csproj index 3f4ebe01c..da72b56e0 100644 --- a/src/netstandard/build/NetStandardProjectBuilder.csproj +++ b/src/netstandard/build/NetStandardProjectBuilder.csproj @@ -36,7 +36,6 @@ - @@ -44,7 +43,10 @@ $(ProjectDir)\build.cmd $(SolutionDir) $(ConfigurationName) - bash $(ProjectDir)/build.sh $(SolutionDir) $(ConfigurationName) + echo This project supports only Windows specific builds. + + + $(ProjectDir)\build.cmd $(SolutionDir) $(ConfigurationName) + $(DefineConstants);NETSTANDARD1_3 + + + + $(DefineConstants);NETSTANDARD2_0 - - ..\..\packages\NUnit.3.2.1\lib\net45\nunit.framework.dll - True - - - - ..\..\packages\System.Collections.Immutable.1.1.37\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll - True - - - - - - - + + + + + + + + + + + + + + + + + + Serialization\RoslynCodeGeneration.cs + + + Serialization\TempFileDependentAssemblyManager.cs + - - + ArrayCodeDomBasedCustomCollectionSerializersTest.tt True True - + ArrayFieldBasedCustomCollectionSerializersTest.tt True True - + True True ArrayReflectionBaedCustomCollectionSerializersTest.tt - + MapCodeDomBasedCustomCollectionSerializersTest.tt True True - + MapFieldBasedCustomCollectionSerializersTest.tt True True - + True True MapReflectionBasedCustomCollectionSerializersTest.tt + + + - - {5bcec32e-990e-4de5-945f-bd27326a7418} - MsgPack - + MsgPack.snk - - - ImmutableCollectionsTest1.cs - - + + + TextTemplatingFileGenerator ArrayCodeDomBasedCustomCollectionSerializersTest.cs - + TextTemplatingFileGenerator ArrayFieldBasedCustomCollectionSerializersTest.cs - + TextTemplatingFileGenerator MapCodeDomBasedCustomCollectionSerializersTest.cs - + TextTemplatingFileGenerator MapFieldBasedCustomCollectionSerializersTest.cs @@ -124,17 +108,18 @@ - + TextTemplatingFileGenerator ArrayReflectionBaedCustomCollectionSerializersTest.cs - - + + TextTemplatingFileGenerator MapReflectionBasedCustomCollectionSerializersTest.cs - + + + + - - + $(DefineConstants);NETSTANDARD2_0 - - ..\..\packages\NUnit.3.2.1\lib\net45\nunit.framework.dll - True - + + + + + + + + + + + - - - - - + + - - + True True ArrayCodeDomBasedEnumSerializationTest.tt - + CodeDomBasedNilImplicationTest.tt True True - + MapCodeDomBasedAutoMessagePackSerializerTest.tt True True - + ArrayCodeDomBasedAutoMessagePackSerializerTest.tt True True - + True True MapCodeDomBasedEnumSerializationTest.tt - - - {5bcec32e-990e-4de5-945f-bd27326a7418} - MsgPack - - - {3889c9be-0473-4b41-80e8-c4c923e837e7} - MsgPack.UnitTest - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MsgPack.snk - - + + TextTemplatingFileGenerator ArrayCodeDomBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator CodeDomBasedNilImplicationTest.cs - + TextTemplatingFileGenerator MapCodeDomBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator ArrayCodeDomBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator MapCodeDomBasedEnumSerializationTest.cs @@ -123,8 +126,6 @@ - - + + v3.5 + + + + + $(DefineConstants);SILVERLIGHT;SILVERLIGHT_PRIVILEGED + true + true + + + + + + + + + $(TargetFrameworkDirectory)System.Core.dll + + + + + + + + System\Collections\Generic\BigHelper.cs + + + System\Collections\Generic\EnumerableHelpers.cs + + + System\Collections\Generic\SortedDictionary`2.cs + + + System\Collections\Generic\SortedSet`1.cs + + + System\MidpointRouding.cs + + + Augments.cs + + + BigEndianBinaryTest.cs + + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + + + CollectionAssertEx.cs + + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + + + DirectConversionTest.cs + + + DirectConversionTest.Scalar.cs + + + EqualsTest.cs + + + ExceptionTest.cs + + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + + + GenericExceptionTester.cs + + + Image.cs + + + LegacyJapaneseCultureInfo.cs + + + MessagePackConvertTest.cs + + + MessagePackExtendedTypeObjectTest.cs + + + MessagePackMemberSkipTest.cs + + + MessagePackObjectDictionaryTest.cs + + + MessagePackObjectTest.Conversion.cs + + + MessagePackObjectTest.Equals.cs + + + MessagePackObjectTest.Equals.Integer.cs + + + MessagePackObjectTest.Equals.Real.cs + + + MessagePackObjectTest.Exceptionals.Conversion.cs + + + MessagePackObjectTest.Exceptionals.cs + + + MessagePackObjectTest.IPackable.cs + + + MessagePackObjectTest.IsTypeOf.Array.cs + + + MessagePackObjectTest.IsTypeOf.cs + + + MessagePackObjectTest.IsTypeOf.Integer.cs + + + MessagePackObjectTest.IsTypeOf.Map.cs + + + MessagePackObjectTest.IsTypeOf.Raw.cs + + + MessagePackObjectTest.Miscs.cs + + + MessagePackObjectTest.Objects.cs + + + MessagePackObjectTest.RuntimeSerialization.cs + + + MessagePackObjectTest.Strings.cs + + + MessagePackStringTest.cs + + + MessageUnpackableTest.cs + + + PackerFactoryTest.cs + + + PackerTest.cs + + + PackerTest.Pack.cs + + + PackerTest.PackBinary.cs + + + PackerTest.PackExtendedType.cs + + + PackerTest.PackObject.cs + + + PackerTest.PackT.cs + + + PackUnpackTest.cs + + + PackUnpackTest.Scalar.cs + + + Serialization\AddOnlyCollection`1.cs + + + Serialization\ArrayReflectionBasedAutoMessagePackSerializerTest.cs + + + Serialization\ArrayReflectionBasedEnumSerializationTest.cs + + + Serialization\ArraySegmentEqualityComparer`1.cs + + + Serialization\AutoMessagePackSerializerTest.Types.cs + + + Serialization\BaseCollections.cs + + + Serialization\ComplexType.cs + + + Serialization\ComplexTypeWithDataContract.cs + + + Serialization\ComplexTypeWithDataContractWithOrder.cs + + + Serialization\ComplexTypeWithNonSerialized.cs + + + Serialization\ComplexTypeWithOneBaseOrder.cs + + + Serialization\ComplexTypeWithoutAnyAttribute.cs + + + Serialization\ComplexTypeWithTwoMember.cs + + + Serialization\DataContractAndNonSerializedMixedTarget.cs + + + Serialization\DataMemberAttributeNamedPropertyTestTarget.cs + + + Serialization\EchoKeyedCollection_2MessagePackSerializer`2.cs + + + Serialization\EnumSerializationTest.EnumDefinitions.cs + + + Serialization\InheritanceTest.cs + + + Serialization\IVerifiable.cs + + + Serialization\IVerifiable`1.cs + + + Serialization\KeyNameTransformersTest.cs + + + Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs + + + Serialization\MapReflectionBasedEnumSerializationTest.cs + + + Serialization\MessagePackMemberAndDataMemberMixedTarget.cs + + + Serialization\MessagePackMemberAttributeTest.cs + + + Serialization\MessagePackSerializerTest.cs + + + Serialization\MessagePackSerializerTTest.cs + + + Serialization\MillisecondsDateTimeComparer.cs + + + Serialization\MillisecondsDateTimeOffsetComparer.cs + + + Serialization\NilImplicationTestTarget.cs + + + Serialization\PerformanceTest.cs + + + Serialization\ReflectionBasedNilImplicationTest.cs + + + Serialization\RegressionTests.cs + + + Serialization\SerializationContextTest.cs + + + Serialization\SerializationTargets.cs + + + Serialization\SerializationTargetTest.cs + + + Serialization\SimpleCollection`1.cs + + + Serialization\StringKeyedCollection.cs + + + Serialization\StructWithDataContractTest.cs + + + Serialization\TestValueType.cs + + + Serialization\TimestampSerializationTest.cs + + + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs + + + Serialization\TypeWithInvalidMessagePackMemberAttributeMember.cs + + + Serialization\TypeWithMissingMessagePackMemberAttributeMember.cs + + + Serialization\VersioningTest.Cases.cs + + + Serialization\VersioningTest.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs + + + TestRandom.cs + + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + + + UnpackerTest.cs + + + UnpackerTest.Ext.cs + + + UnpackerTest.Object.cs + + + UnpackerTest.Raw.cs + + + UnpackerTest.Scalar.cs + + + UnpackerTest.Skip.cs + + + UnpackerTest.Skip.Variations.cs + + + UnpackerTest.Subtree.cs + + + UnpackingTest.Combinations.Array.cs + + + UnpackingTest.Combinations.Boolean.cs + + + UnpackingTest.Combinations.Byte.cs + + + UnpackingTest.Combinations.Double.cs + + + UnpackingTest.Combinations.Int16.cs + + + UnpackingTest.Combinations.Int32.cs + + + UnpackingTest.Combinations.Int64.cs + + + UnpackingTest.Combinations.Map.cs + + + UnpackingTest.Combinations.Nil.cs + + + UnpackingTest.Combinations.Raw.cs + + + UnpackingTest.Combinations.SByte.cs + + + UnpackingTest.Combinations.Single.cs + + + UnpackingTest.Combinations.UInt16.cs + + + UnpackingTest.Combinations.UInt32.cs + + + UnpackingTest.Combinations.UInt64.cs + + + UnpackingTest.cs + + + UnpackingTest.Ext.cs + + + UnpackingTest.Raw.cs + + + UnpackingTest.Scalar.cs + + + App.xaml + + + + + + Designer + MSBuild:Compile + + + + + MsgPack.snk + + + + + + + + {f9477829-6a6d-4540-9f0d-68f8c6d8e18b} + MsgPack.Silverlight.5 + + + {3deb15f9-e7da-403f-b6d3-a8499310397f} + nunit.framework-sl-5.0 + + + {0a5f920a-1bf5-4dac-b799-0c618b203797} + nunitlite-sl-5.0 + + + + + + + + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/AppManifest.xml b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/AppManifest.xml new file mode 100644 index 000000000..6712a1178 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/AppManifest.xml @@ -0,0 +1,6 @@ + + + + diff --git a/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/AssemblyInfo.cs b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..7dff50b6b --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Resources; + +[assembly: AssemblyTitle( "Unit test of MessagePack for CLI(Silverlight, FullTrust)" )] +[assembly: AssemblyDescription( "Unit test of MessagePack CLI(Silverlight) binding on FullTrust" )] +[assembly: AssemblyConfiguration( "Develop" )] +[assembly: AssemblyProduct( "MessagePack" )] +[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2017" )] + +[assembly: ComVisible( false )] +[assembly: NeutralResourcesLanguage( "en-US" )] +[assembly: AssemblyVersion( "1.0.0.0" )] +[assembly: AssemblyFileVersion( "0.1.0.0" )] +[assembly: AssemblyInformationalVersion( "0.1" )] diff --git a/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/InBrowserSettings.xml b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/InBrowserSettings.xml new file mode 100644 index 000000000..56716508b --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/InBrowserSettings.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/OutOfBrowserSettings.xml b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/OutOfBrowserSettings.xml new file mode 100644 index 000000000..8fad43d81 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5.FullTrust/Properties/OutOfBrowserSettings.xml @@ -0,0 +1,10 @@ + + デスクトップの MsgPack.UnitTest.Silverlight.5.FullTrust アプリケーションを、自宅でも、職場でも、外出先でも利用できます。 + + + + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/App.xaml b/test/MsgPack.UnitTest.Silverlight.5/App.xaml new file mode 100644 index 000000000..6142a28e6 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/App.xaml @@ -0,0 +1,8 @@ + + + + + diff --git a/test/MsgPack.UnitTest.Silverlight.5/App.xaml.cs b/test/MsgPack.UnitTest.Silverlight.5/App.xaml.cs new file mode 100644 index 000000000..91f1c536c --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/App.xaml.cs @@ -0,0 +1,74 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Windows; + +using NUnitLite.Runner.Silverlight; + +namespace MsgPack +{ + public partial class App : Application + { + + public App() + { + this.Startup += this.Application_Startup; + this.Exit += this.Application_Exit; + this.UnhandledException += this.Application_UnhandledException; + + this.InitializeComponent(); + } + + private void Application_Startup( object sender, StartupEventArgs e ) + { + this.RootVisual = new TestPage(); + } + + private void Application_Exit( object sender, EventArgs e ) + { + + } + + private void Application_UnhandledException( object sender, ApplicationUnhandledExceptionEventArgs e ) + { + if ( !System.Diagnostics.Debugger.IsAttached ) + { + + e.Handled = true; + Deployment.Current.Dispatcher.BeginInvoke( delegate { ReportErrorToDOM( e ); } ); + } + } + + private void ReportErrorToDOM( ApplicationUnhandledExceptionEventArgs e ) + { + try + { + string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; + errorMsg = errorMsg.Replace( '"', '\'' ).Replace( "\r\n", @"\n" ); + + System.Windows.Browser.HtmlPage.Window.Eval( "throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");" ); + } + catch ( Exception ) + { + } + } + } +} diff --git a/test/MsgPack.UnitTest.Silverlight.5/MsgPack.UnitTest.Silverlight.5.csproj b/test/MsgPack.UnitTest.Silverlight.5/MsgPack.UnitTest.Silverlight.5.csproj new file mode 100644 index 000000000..68a03a547 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/MsgPack.UnitTest.Silverlight.5.csproj @@ -0,0 +1,534 @@ + + + + 8.0.50727 + 2.0 + {17D0F223-E156-42CF-ACA8-815733FE094F} + {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + MsgPack.Silverlight.UnitTest + Silverlight + v5.0 + $(TargetFrameworkVersion) + true + ja + true + true + MsgPack.Silverlight.UnitTest.xap + Properties\AppManifest.xml + MsgPack.App + MsgPack.UnitTest.Silverlight._5TestPage.html + true + true + true + Properties\OutOfBrowserSettings.xml + false + true + + Properties\InBrowserSettings.xml + false + + + + v3.5 + + + + + $(DefineConstants);SILVERLIGHT + true + true + + + + + + + + + $(TargetFrameworkDirectory)System.Core.dll + + + + + + + + Augments.cs + + + BigEndianBinaryTest.cs + + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + + + CollectionAssertEx.cs + + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + + + DirectConversionTest.cs + + + DirectConversionTest.Scalar.cs + + + EqualsTest.cs + + + ExceptionTest.cs + + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + + + GenericExceptionTester.cs + + + Image.cs + + + LegacyJapaneseCultureInfo.cs + + + MessagePackConvertTest.cs + + + MessagePackExtendedTypeObjectTest.cs + + + MessagePackMemberSkipTest.cs + + + MessagePackObjectDictionaryTest.cs + + + MessagePackObjectTest.Conversion.cs + + + MessagePackObjectTest.Equals.cs + + + MessagePackObjectTest.Equals.Integer.cs + + + MessagePackObjectTest.Equals.Real.cs + + + MessagePackObjectTest.Exceptionals.Conversion.cs + + + MessagePackObjectTest.Exceptionals.cs + + + MessagePackObjectTest.IPackable.cs + + + MessagePackObjectTest.IsTypeOf.Array.cs + + + MessagePackObjectTest.IsTypeOf.cs + + + MessagePackObjectTest.IsTypeOf.Integer.cs + + + MessagePackObjectTest.IsTypeOf.Map.cs + + + MessagePackObjectTest.IsTypeOf.Raw.cs + + + MessagePackObjectTest.Miscs.cs + + + MessagePackObjectTest.Objects.cs + + + MessagePackObjectTest.RuntimeSerialization.cs + + + MessagePackObjectTest.Strings.cs + + + MessagePackStringTest.cs + + + MessageUnpackableTest.cs + + + PackerFactoryTest.cs + + + PackerTest.cs + + + PackerTest.Pack.cs + + + PackerTest.PackBinary.cs + + + PackerTest.PackExtendedType.cs + + + PackerTest.PackObject.cs + + + PackerTest.PackT.cs + + + PackUnpackTest.cs + + + PackUnpackTest.Scalar.cs + + + Serialization\AddOnlyCollection`1.cs + + + Serialization\ArrayReflectionBasedAutoMessagePackSerializerTest.cs + + + Serialization\ArrayReflectionBasedEnumSerializationTest.cs + + + Serialization\ArraySegmentEqualityComparer`1.cs + + + Serialization\AutoMessagePackSerializerTest.Types.cs + + + Serialization\BaseCollections.cs + + + Serialization\ComplexType.cs + + + Serialization\ComplexTypeWithDataContract.cs + + + Serialization\ComplexTypeWithDataContractWithOrder.cs + + + Serialization\ComplexTypeWithNonSerialized.cs + + + Serialization\ComplexTypeWithOneBaseOrder.cs + + + Serialization\ComplexTypeWithoutAnyAttribute.cs + + + Serialization\ComplexTypeWithTwoMember.cs + + + Serialization\DataContractAndNonSerializedMixedTarget.cs + + + Serialization\DataMemberAttributeNamedPropertyTestTarget.cs + + + Serialization\EchoKeyedCollection_2MessagePackSerializer`2.cs + + + Serialization\EnumSerializationTest.EnumDefinitions.cs + + + Serialization\InheritanceTest.cs + + + Serialization\IVerifiable.cs + + + Serialization\IVerifiable`1.cs + + + Serialization\KeyNameTransformersTest.cs + + + Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs + + + Serialization\MapReflectionBasedEnumSerializationTest.cs + + + Serialization\MessagePackMemberAndDataMemberMixedTarget.cs + + + Serialization\MessagePackMemberAttributeTest.cs + + + Serialization\MessagePackSerializerTest.cs + + + Serialization\MessagePackSerializerTTest.cs + + + Serialization\MillisecondsDateTimeComparer.cs + + + Serialization\MillisecondsDateTimeOffsetComparer.cs + + + Serialization\NilImplicationTestTarget.cs + + + Serialization\PerformanceTest.cs + + + Serialization\ReflectionBasedNilImplicationTest.cs + + + Serialization\RegressionTests.cs + + + Serialization\SerializationContextTest.cs + + + Serialization\SerializationTargets.cs + + + Serialization\SerializationTargetTest.cs + + + Serialization\SimpleCollection`1.cs + + + Serialization\StringKeyedCollection.cs + + + Serialization\StructWithDataContractTest.cs + + + Serialization\TestValueType.cs + + + Serialization\TimestampSerializationTest.cs + + + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs + + + Serialization\TypeWithInvalidMessagePackMemberAttributeMember.cs + + + Serialization\TypeWithMissingMessagePackMemberAttributeMember.cs + + + Serialization\VersioningTest.Cases.cs + + + Serialization\VersioningTest.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs + + + TestRandom.cs + + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + + + UnpackerTest.cs + + + UnpackerTest.Ext.cs + + + UnpackerTest.Object.cs + + + UnpackerTest.Raw.cs + + + UnpackerTest.Scalar.cs + + + UnpackerTest.Skip.cs + + + UnpackerTest.Skip.Variations.cs + + + UnpackerTest.Subtree.cs + + + UnpackingTest.Combinations.Array.cs + + + UnpackingTest.Combinations.Boolean.cs + + + UnpackingTest.Combinations.Byte.cs + + + UnpackingTest.Combinations.Double.cs + + + UnpackingTest.Combinations.Int16.cs + + + UnpackingTest.Combinations.Int32.cs + + + UnpackingTest.Combinations.Int64.cs + + + UnpackingTest.Combinations.Map.cs + + + UnpackingTest.Combinations.Nil.cs + + + UnpackingTest.Combinations.Raw.cs + + + UnpackingTest.Combinations.SByte.cs + + + UnpackingTest.Combinations.Single.cs + + + UnpackingTest.Combinations.UInt16.cs + + + UnpackingTest.Combinations.UInt32.cs + + + UnpackingTest.Combinations.UInt64.cs + + + UnpackingTest.cs + + + UnpackingTest.Ext.cs + + + UnpackingTest.Raw.cs + + + UnpackingTest.Scalar.cs + + + App.xaml + + + + + + + + + + + Designer + MSBuild:Compile + + + + + MsgPack.snk + + + + + + + + {f9477829-6a6d-4540-9f0d-68f8c6d8e18b} + MsgPack.Silverlight.5 + + + {3deb15f9-e7da-403f-b6d3-a8499310397f} + nunit.framework-sl-5.0 + + + {0a5f920a-1bf5-4dac-b799-0c618b203797} + nunitlite-sl-5.0 + + + + + + + + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/Properties/AppManifest.xml b/test/MsgPack.UnitTest.Silverlight.5/Properties/AppManifest.xml new file mode 100644 index 000000000..6712a1178 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/Properties/AppManifest.xml @@ -0,0 +1,6 @@ + + + + diff --git a/test/MsgPack.UnitTest.Silverlight.5/Properties/AssemblyInfo.cs b/test/MsgPack.UnitTest.Silverlight.5/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..e1c91e127 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Resources; + +[assembly: AssemblyTitle( "Unit test of MessagePack for CLI(Silverlight)" )] +[assembly: AssemblyDescription( "Unit test of MessagePack CLI(Silverlight) binding" )] +[assembly: AssemblyConfiguration( "Develop" )] +[assembly: AssemblyProduct( "MessagePack" )] +[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2017" )] + +[assembly: ComVisible( false )] +[assembly: NeutralResourcesLanguage( "en-US" )] +[assembly: AssemblyVersion( "1.0.0.0" )] +[assembly: AssemblyFileVersion( "0.1.0.0" )] +[assembly: AssemblyInformationalVersion( "0.1" )] diff --git a/test/MsgPack.UnitTest.Silverlight.5/Properties/InBrowserSettings.xml b/test/MsgPack.UnitTest.Silverlight.5/Properties/InBrowserSettings.xml new file mode 100644 index 000000000..0c41b0763 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/Properties/InBrowserSettings.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/Properties/OutOfBrowserSettings.xml b/test/MsgPack.UnitTest.Silverlight.5/Properties/OutOfBrowserSettings.xml new file mode 100644 index 000000000..de9ff71b4 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/Properties/OutOfBrowserSettings.xml @@ -0,0 +1,7 @@ + + デスクトップの MsgPack.UnitTest.Silverlight.5 アプリケーションを、自宅でも、職場でも、外出先でも利用できます。 + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/BigHelper.cs b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/BigHelper.cs new file mode 100644 index 000000000..280ff4272 --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/BigHelper.cs @@ -0,0 +1,109 @@ +// 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. + +// Based on corefx's BitHelper + +namespace System.Collections.Generic +{ + /// + /// ABOUT: + /// Helps with operations that rely on bit marking to indicate whether an item in the + /// collection should be added, removed, visited already, etc. + /// + /// BitHelper doesn't allocate the array; you must pass in an array or ints allocated on the + /// stack or heap. ToIntArrayLength() tells you the int array size you must allocate. + /// + /// USAGE: + /// Suppose you need to represent a bit array of length (i.e. logical bit array length) + /// BIT_ARRAY_LENGTH. Then this is the suggested way to instantiate BitHelper: + /// *************************************************************************** + /// int intArrayLength = BitHelper.ToIntArrayLength(BIT_ARRAY_LENGTH); + /// BitHelper bitHelper; + /// if (intArrayLength less than stack alloc threshold) + /// int* m_arrayPtr = stackalloc int[intArrayLength]; + /// bitHelper = new BitHelper(m_arrayPtr, intArrayLength); + /// else + /// int[] m_arrayPtr = new int[intArrayLength]; + /// bitHelper = new BitHelper(m_arrayPtr, intArrayLength); + /// *************************************************************************** + /// + /// IMPORTANT: + /// The second ctor args, length, should be specified as the length of the int array, not + /// the logical bit array. Because length is used for bounds checking into the int array, + /// it's especially important to get this correct for the stackalloc version. See the code + /// samples above; this is the value gotten from ToIntArrayLength(). + /// + /// The length ctor argument is the only exception; for other methods -- MarkBit and + /// IsMarked -- pass in values as indices into the logical bit array, and it will be mapped + /// to the position within the array of ints. + /// + /// FUTURE OPTIMIZATIONS: + /// A method such as FindFirstMarked/Unmarked Bit would be useful for callers that operate + /// on a bit array and then need to loop over it. In particular, if it avoided visiting + /// every bit, it would allow good perf improvements when the bit array is sparse. + /// + internal sealed class BitHelper + { // should not be serialized + private const byte MarkedBitFlag = 1; + private const byte IntSize = 32; + + // m_length of underlying int array (not logical bit array) + private readonly int _length; + + // array of ints + private readonly int[] _array; + + /// + /// Instantiates a BitHelper with a heap alloc'd array of ints + /// + /// int array to hold bits + /// length of int array + internal BitHelper( int[] bitArray, int length ) + { + _array = bitArray; + _length = length; + } + + /// + /// Mark bit at specified position + /// + /// + internal void MarkBit( int bitPosition ) + { + int bitArrayIndex = bitPosition / IntSize; + if ( bitArrayIndex < _length && bitArrayIndex >= 0 ) + { + int flag = (MarkedBitFlag << (bitPosition % IntSize)); + _array[ bitArrayIndex ] |= flag; + } + } + + /// + /// Is bit at specified position marked? + /// + /// + /// + internal bool IsMarked( int bitPosition ) + { + int bitArrayIndex = bitPosition / IntSize; + if ( bitArrayIndex < _length && bitArrayIndex >= 0 ) + { + int flag = (MarkedBitFlag << (bitPosition % IntSize)); + return ( ( _array[ bitArrayIndex ] & flag ) != 0 ); + } + return false; + } + + /// + /// How many ints must be allocated to represent n bits. Returns (n+31)/32, but + /// avoids overflow + /// + /// + /// + internal static int ToIntArrayLength( int n ) + { + return n > 0 ? ( ( n - 1 ) / IntSize + 1 ) : 0; + } + } +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/EnumerableHelpers.cs b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/EnumerableHelpers.cs new file mode 100644 index 000000000..4052cb6cd --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/EnumerableHelpers.cs @@ -0,0 +1,121 @@ +// 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. + +// Based on corefx's EnumerableHelpers + +using System.Diagnostics; + +namespace System.Collections.Generic +{ + /// Internal helper functions for working with enumerables. + internal static class EnumerableHelpers + { + /// Converts an enumerable to an array. + /// The enumerable to convert. + /// The resulting array. + internal static T[] ToArray( IEnumerable source ) + { + Debug.Assert( source != null ); + + var collection = source as ICollection; + if ( collection != null ) + { + int count = collection.Count; + if ( count == 0 ) + { + return new T[ 0 ]; + } + + var result = new T[count]; + collection.CopyTo( result, arrayIndex: 0 ); + return result; + } + + var builder = new List(); + builder.AddRange( source ); + return builder.ToArray(); + } + + /// Converts an enumerable to an array using the same logic as List{T}. + /// The enumerable to convert. + /// The number of items stored in the resulting array, 0-indexed. + /// + /// The resulting array. The length of the array may be greater than , + /// which is the actual number of elements in the array. + /// + internal static T[] ToArray( IEnumerable source, out int length ) + { + ICollection ic = source as ICollection; + if ( ic != null ) + { + int count = ic.Count; + if ( count != 0 ) + { + // Allocate an array of the desired size, then copy the elements into it. Note that this has the same + // issue regarding concurrency as other existing collections like List. If the collection size + // concurrently changes between the array allocation and the CopyTo, we could end up either getting an + // exception from overrunning the array (if the size went up) or we could end up not filling as many + // items as 'count' suggests (if the size went down). This is only an issue for concurrent collections + // that implement ICollection, which as of .NET 4.6 is just ConcurrentDictionary. + T[] arr = new T[count]; + ic.CopyTo( arr, 0 ); + length = count; + return arr; + } + } + else + { + using ( var en = source.GetEnumerator() ) + { + if ( en.MoveNext() ) + { + const int DefaultCapacity = 4; + T[] arr = new T[DefaultCapacity]; + arr[ 0 ] = en.Current; + int count = 1; + + while ( en.MoveNext() ) + { + if ( count == arr.Length ) + { + // MaxArrayLength is defined in Array.MaxArrayLength and in gchelpers in CoreCLR. + // It represents the maximum number of elements that can be in an array where + // the size of the element is greater than one byte; a separate, slightly larger constant, + // is used when the size of the element is one. + const int MaxArrayLength = 0x7FEFFFFF; + + // This is the same growth logic as in List: + // If the array is currently empty, we make it a default size. Otherwise, we attempt to + // double the size of the array. Doubling will overflow once the size of the array reaches + // 2^30, since doubling to 2^31 is 1 larger than Int32.MaxValue. In that case, we instead + // constrain the length to be MaxArrayLength (this overflow check works because of the + // cast to uint). Because a slightly larger constant is used when T is one byte in size, we + // could then end up in a situation where arr.Length is MaxArrayLength or slightly larger, such + // that we constrain newLength to be MaxArrayLength but the needed number of elements is actually + // larger than that. For that case, we then ensure that the newLength is large enough to hold + // the desired capacity. This does mean that in the very rare case where we've grown to such a + // large size, each new element added after MaxArrayLength will end up doing a resize. + int newLength = count << 1; + if ( ( uint )newLength > MaxArrayLength ) + { + newLength = MaxArrayLength <= count ? count + 1 : MaxArrayLength; + } + + Array.Resize( ref arr, newLength ); + } + + arr[ count++ ] = en.Current; + } + + length = count; + return arr; + } + } + } + + length = 0; + return new T[ 0 ]; + } + } +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/SortedDictionary`2.cs b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/SortedDictionary`2.cs new file mode 100644 index 000000000..1c1c2200f --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/SortedDictionary`2.cs @@ -0,0 +1,957 @@ +// 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. + +// Based on corefx's SortedDictionary + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Collections.Generic +{ + [DebuggerDisplay( "Count = {Count}" )] + public class SortedDictionary : IDictionary, IDictionary + { + private KeyCollection _keys; + private ValueCollection _values; + + private TreeSet> _set; + + public SortedDictionary() : this( ( IComparer )null ) + { + } + + public SortedDictionary( IDictionary dictionary ) : this( dictionary, null ) + { + } + + public SortedDictionary( IDictionary dictionary, IComparer comparer ) + { + if ( dictionary == null ) + { + throw new ArgumentNullException( nameof( dictionary ) ); + } + + _set = new TreeSet>( new KeyValuePairComparer( comparer ) ); + + foreach ( KeyValuePair pair in dictionary ) + { + _set.Add( pair ); + } + } + + public SortedDictionary( IComparer comparer ) + { + _set = new TreeSet>( new KeyValuePairComparer( comparer ) ); + } + + void ICollection>.Add( KeyValuePair keyValuePair ) + { + _set.Add( keyValuePair ); + } + + bool ICollection>.Contains( KeyValuePair keyValuePair ) + { + TreeSet>.Node node = _set.FindNode(keyValuePair); + if ( node == null ) + { + return false; + } + + if ( keyValuePair.Value == null ) + { + return node.Item.Value == null; + } + else + { + return EqualityComparer.Default.Equals( node.Item.Value, keyValuePair.Value ); + } + } + + bool ICollection>.Remove( KeyValuePair keyValuePair ) + { + TreeSet>.Node node = _set.FindNode(keyValuePair); + if ( node == null ) + { + return false; + } + + if ( EqualityComparer.Default.Equals( node.Item.Value, keyValuePair.Value ) ) + { + _set.Remove( keyValuePair ); + return true; + } + return false; + } + + bool ICollection>.IsReadOnly + { + get + { + return false; + } + } + + public TValue this[ TKey key ] + { + get + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + TreeSet>.Node node = _set.FindNode(new KeyValuePair(key, default(TValue))); + if ( node == null ) + { + throw new KeyNotFoundException(); + } + + return node.Item.Value; + } + set + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + TreeSet>.Node node = _set.FindNode(new KeyValuePair(key, default(TValue))); + if ( node == null ) + { + _set.Add( new KeyValuePair( key, value ) ); + } + else + { + node.Item = new KeyValuePair( node.Item.Key, value ); + _set.UpdateVersion(); + } + } + } + + public int Count + { + get + { + return _set.Count; + } + } + + public IComparer Comparer + { + get + { + return ( ( KeyValuePairComparer )_set.Comparer ).keyComparer; + } + } + + public KeyCollection Keys + { + get + { + if ( _keys == null ) _keys = new KeyCollection( this ); + return _keys; + } + } + + ICollection IDictionary.Keys + { + get + { + return Keys; + } + } + + public ValueCollection Values + { + get + { + if ( _values == null ) _values = new ValueCollection( this ); + return _values; + } + } + + ICollection IDictionary.Values + { + get + { + return Values; + } + } + + public void Add( TKey key, TValue value ) + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + _set.Add( new KeyValuePair( key, value ) ); + } + + public void Clear() + { + _set.Clear(); + } + + public bool ContainsKey( TKey key ) + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + return _set.Contains( new KeyValuePair( key, default( TValue ) ) ); + } + + public bool ContainsValue( TValue value ) + { + bool found = false; + if ( value == null ) + { + _set.InOrderTreeWalk( delegate ( TreeSet>.Node node ) + { + if ( node.Item.Value == null ) + { + found = true; + return false; // stop the walk + } + return true; + } ); + } + else + { + EqualityComparer valueComparer = EqualityComparer.Default; + _set.InOrderTreeWalk( delegate ( TreeSet>.Node node ) + { + if ( valueComparer.Equals( node.Item.Value, value ) ) + { + found = true; + return false; // stop the walk + } + return true; + } ); + } + return found; + } + + public void CopyTo( KeyValuePair[] array, int index ) + { + _set.CopyTo( array, index ); + } + + public Enumerator GetEnumerator() + { + return new Enumerator( this, Enumerator.KeyValuePair ); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return new Enumerator( this, Enumerator.KeyValuePair ); + } + + public bool Remove( TKey key ) + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + return _set.Remove( new KeyValuePair( key, default( TValue ) ) ); + } + + public bool TryGetValue( TKey key, out TValue value ) + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + TreeSet>.Node node = _set.FindNode(new KeyValuePair(key, default(TValue))); + if ( node == null ) + { + value = default( TValue ); + return false; + } + value = node.Item.Value; + return true; + } + + void ICollection.CopyTo( Array array, int index ) + { + ( ( ICollection )_set ).CopyTo( array, index ); + } + + bool IDictionary.IsFixedSize + { + get { return false; } + } + + bool IDictionary.IsReadOnly + { + get { return false; } + } + + ICollection IDictionary.Keys + { + get { return ( ICollection )Keys; } + } + + ICollection IDictionary.Values + { + get { return ( ICollection )Values; } + } + + object IDictionary.this[ object key ] + { + get + { + if ( IsCompatibleKey( key ) ) + { + TValue value; + if ( TryGetValue( ( TKey )key, out value ) ) + { + return value; + } + } + + return null; + } + set + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + if ( value == null && !( default( TValue ) == null ) ) + throw new ArgumentNullException( nameof( value ) ); + + try + { + TKey tempKey = (TKey)key; + try + { + this[ tempKey ] = ( TValue )value; + } + catch ( InvalidCastException ) + { + throw new ArgumentException( String.Format( "Wrong type {0}.", value, typeof( TValue ) ), nameof( value ) ); + } + } + catch ( InvalidCastException ) + { + throw new ArgumentException( String.Format( "Wrong type {0}.", key, typeof( TKey ) ), nameof( key ) ); + } + } + } + + void IDictionary.Add( object key, object value ) + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + if ( value == null && !( default( TValue ) == null ) ) + throw new ArgumentNullException( nameof( value ) ); + + try + { + TKey tempKey = (TKey)key; + + try + { + Add( tempKey, ( TValue )value ); + } + catch ( InvalidCastException ) + { + throw new ArgumentException( String.Format( "Wrong type {0}.", value, typeof( TValue ) ), nameof( value ) ); + } + } + catch ( InvalidCastException ) + { + throw new ArgumentException( String.Format( "Wrong type {0}.", key, typeof( TKey ) ), nameof( key ) ); + } + } + + bool IDictionary.Contains( object key ) + { + if ( IsCompatibleKey( key ) ) + { + return ContainsKey( ( TKey )key ); + } + return false; + } + + private static bool IsCompatibleKey( object key ) + { + if ( key == null ) + { + throw new ArgumentNullException( nameof( key ) ); + } + + return ( key is TKey ); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new Enumerator( this, Enumerator.DictEntry ); + } + + void IDictionary.Remove( object key ) + { + if ( IsCompatibleKey( key ) ) + { + Remove( ( TKey )key ); + } + } + + bool ICollection.IsSynchronized + { + get { return false; } + } + + object ICollection.SyncRoot + { + get { return ( ( ICollection )_set ).SyncRoot; } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( this, Enumerator.KeyValuePair ); + } + + [SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario" )] + public struct Enumerator : IEnumerator>, IDictionaryEnumerator + { + private TreeSet>.Enumerator _treeEnum; + private int _getEnumeratorRetType; // What should Enumerator.Current return? + + internal const int KeyValuePair = 1; + internal const int DictEntry = 2; + + internal Enumerator( SortedDictionary dictionary, int getEnumeratorRetType ) + { + _treeEnum = dictionary._set.GetEnumerator(); + _getEnumeratorRetType = getEnumeratorRetType; + } + + public bool MoveNext() + { + return _treeEnum.MoveNext(); + } + + public void Dispose() + { + _treeEnum.Dispose(); + } + + public KeyValuePair Current + { + get + { + return _treeEnum.Current; + } + } + + internal bool NotStartedOrEnded + { + get + { + return _treeEnum.NotStartedOrEnded; + } + } + + internal void Reset() + { + _treeEnum.Reset(); + } + + + void IEnumerator.Reset() + { + _treeEnum.Reset(); + } + + object IEnumerator.Current + { + get + { + if ( NotStartedOrEnded ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + if ( _getEnumeratorRetType == DictEntry ) + { + return new DictionaryEntry( Current.Key, Current.Value ); + } + else + { + return new KeyValuePair( Current.Key, Current.Value ); + } + } + } + + object IDictionaryEnumerator.Key + { + get + { + if ( NotStartedOrEnded ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + return Current.Key; + } + } + + object IDictionaryEnumerator.Value + { + get + { + if ( NotStartedOrEnded ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + return Current.Value; + } + } + + DictionaryEntry IDictionaryEnumerator.Entry + { + get + { + if ( NotStartedOrEnded ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + return new DictionaryEntry( Current.Key, Current.Value ); + } + } + } + + [DebuggerDisplay( "Count = {Count}" )] + public sealed class KeyCollection : ICollection, ICollection + { + private SortedDictionary _dictionary; + + public KeyCollection( SortedDictionary dictionary ) + { + if ( dictionary == null ) + { + throw new ArgumentNullException( nameof( dictionary ) ); + } + _dictionary = dictionary; + } + + public Enumerator GetEnumerator() + { + return new Enumerator( _dictionary ); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( _dictionary ); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( _dictionary ); + } + + public void CopyTo( TKey[] array, int index ) + { + if ( array == null ) + { + throw new ArgumentNullException( nameof( array ) ); + } + + if ( index < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( index ) ); + } + + if ( array.Length - index < Count ) + { + throw new ArgumentException( "Array plus offset too small." ); + } + + _dictionary._set.InOrderTreeWalk( delegate ( TreeSet>.Node node ) { array[ index++ ] = node.Item.Key; return true; } ); + } + + void ICollection.CopyTo( Array array, int index ) + { + if ( array == null ) + { + throw new ArgumentNullException( nameof( array ) ); + } + + if ( array.Rank != 1 ) + { + throw new ArgumentException( "Multi dimensional array.", nameof( array ) ); + } + + if ( array.GetLowerBound( 0 ) != 0 ) + { + throw new ArgumentException( "Non zero lower bound array.", nameof( array ) ); + } + + if ( index < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( index ) ); + } + + if ( array.Length - index < _dictionary.Count ) + { + throw new ArgumentException( "Array plus offset too small." ); + } + + TKey[] keys = array as TKey[]; + if ( keys != null ) + { + CopyTo( keys, index ); + } + else + { + try + { + object[] objects = (object[])array; + _dictionary._set.InOrderTreeWalk( delegate ( TreeSet>.Node node ) { objects[ index++ ] = node.Item.Key; return true; } ); + } + catch ( ArrayTypeMismatchException ) + { + throw new ArgumentException( "Invalid array type.", nameof( array ) ); + } + } + } + + public int Count + { + get { return _dictionary.Count; } + } + + bool ICollection.IsReadOnly + { + get { return true; } + } + + void ICollection.Add( TKey item ) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Contains( TKey item ) + { + return _dictionary.ContainsKey( item ); + } + + bool ICollection.Remove( TKey item ) + { + throw new NotSupportedException(); + } + + bool ICollection.IsSynchronized + { + get { return false; } + } + + object ICollection.SyncRoot + { + get { return ( ( ICollection )_dictionary ).SyncRoot; } + } + + [SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario" )] + public struct Enumerator : IEnumerator, IEnumerator + { + private SortedDictionary.Enumerator _dictEnum; + + internal Enumerator( SortedDictionary dictionary ) + { + _dictEnum = dictionary.GetEnumerator(); + } + + public void Dispose() + { + _dictEnum.Dispose(); + } + + public bool MoveNext() + { + return _dictEnum.MoveNext(); + } + + public TKey Current + { + get + { + return _dictEnum.Current.Key; + } + } + + object IEnumerator.Current + { + get + { + if ( _dictEnum.NotStartedOrEnded ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + return Current; + } + } + + void IEnumerator.Reset() + { + _dictEnum.Reset(); + } + } + } + + [DebuggerDisplay( "Count = {Count}" )] + public sealed class ValueCollection : ICollection, ICollection + { + private SortedDictionary _dictionary; + + public ValueCollection( SortedDictionary dictionary ) + { + if ( dictionary == null ) + { + throw new ArgumentNullException( nameof( dictionary ) ); + } + _dictionary = dictionary; + } + + public Enumerator GetEnumerator() + { + return new Enumerator( _dictionary ); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( _dictionary ); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( _dictionary ); + } + + public void CopyTo( TValue[] array, int index ) + { + if ( array == null ) + { + throw new ArgumentNullException( nameof( array ) ); + } + + if ( index < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( index ) ); + } + + if ( array.Length - index < Count ) + { + throw new ArgumentException( "Array plus offset too small." ); + } + + _dictionary._set.InOrderTreeWalk( delegate ( TreeSet>.Node node ) { array[ index++ ] = node.Item.Value; return true; } ); + } + + void ICollection.CopyTo( Array array, int index ) + { + if ( array == null ) + { + throw new ArgumentNullException( nameof( array ) ); + } + + if ( array.Rank != 1 ) + { + throw new ArgumentException( "Multi dimensional array.", nameof( array ) ); + } + + if ( array.GetLowerBound( 0 ) != 0 ) + { + throw new ArgumentException( "Non zero lower bound array.", nameof( array ) ); + } + + if ( index < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( index ) ); + } + + if ( array.Length - index < _dictionary.Count ) + { + throw new ArgumentException( "Array plus offset too small." ); + } + + TValue[] values = array as TValue[]; + if ( values != null ) + { + CopyTo( values, index ); + } + else + { + try + { + object[] objects = (object[])array; + _dictionary._set.InOrderTreeWalk( delegate ( TreeSet>.Node node ) { objects[ index++ ] = node.Item.Value; return true; } ); + } + catch ( ArrayTypeMismatchException ) + { + throw new ArgumentException( "Invalid array type.", nameof( array ) ); + } + } + } + + public int Count + { + get { return _dictionary.Count; } + } + + bool ICollection.IsReadOnly + { + get { return true; } + } + + void ICollection.Add( TValue item ) + { + throw new NotSupportedException(); + } + + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + bool ICollection.Contains( TValue item ) + { + return _dictionary.ContainsValue( item ); + } + + bool ICollection.Remove( TValue item ) + { + throw new NotSupportedException(); + } + + bool ICollection.IsSynchronized + { + get { return false; } + } + + object ICollection.SyncRoot + { + get { return ( ( ICollection )_dictionary ).SyncRoot; } + } + + [SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario" )] + public struct Enumerator : IEnumerator, IEnumerator + { + private SortedDictionary.Enumerator _dictEnum; + + internal Enumerator( SortedDictionary dictionary ) + { + _dictEnum = dictionary.GetEnumerator(); + } + + public void Dispose() + { + _dictEnum.Dispose(); + } + + public bool MoveNext() + { + return _dictEnum.MoveNext(); + } + + public TValue Current + { + get + { + return _dictEnum.Current.Value; + } + } + + object IEnumerator.Current + { + get + { + if ( _dictEnum.NotStartedOrEnded ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + return Current; + } + } + + void IEnumerator.Reset() + { + _dictEnum.Reset(); + } + } + } + + internal sealed class KeyValuePairComparer : Comparer> + { + internal IComparer keyComparer; + + public KeyValuePairComparer( IComparer keyComparer ) + { + if ( keyComparer == null ) + { + this.keyComparer = Comparer.Default; + } + else + { + this.keyComparer = keyComparer; + } + } + + public override int Compare( KeyValuePair x, KeyValuePair y ) + { + return keyComparer.Compare( x.Key, y.Key ); + } + } + } + + /// + /// This class is intended as a helper for backwards compatibility with existing SortedDictionaries. + /// TreeSet has been converted into SortedSet, which will be exposed publicly. SortedDictionaries + /// have the problem where they have already been serialized to disk as having a backing class named + /// TreeSet. To ensure that we can read back anything that has already been written to disk, we need to + /// make sure that we have a class named TreeSet that does everything the way it used to. + /// + /// The only thing that makes it different from SortedSet is that it throws on duplicates + /// + /// + internal sealed class TreeSet : SortedSet + { + public TreeSet() + : base() + { } + + public TreeSet( IComparer comparer ) : base( comparer ) { } + + public TreeSet( ICollection collection ) : base( collection ) { } + + public TreeSet( ICollection collection, IComparer comparer ) : base( collection, comparer ) { } + + internal override bool AddIfNotPresent( T item ) + { + bool ret = base.AddIfNotPresent(item); + if ( !ret ) + { + throw new ArgumentException( String.Format( "{0} is already added.", item ) ); + } + return ret; + } + } +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/SortedSet`1.cs b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/SortedSet`1.cs new file mode 100644 index 000000000..9fb704b8d --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/System/Collections/Generic/SortedSet`1.cs @@ -0,0 +1,2455 @@ +// 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. + +// Based on corefx's SortedSet + +/*============================================================ +** +** +** Purpose: A generic sorted set. +** +** +===========================================================*/ + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Collections.Generic +{ + // + // A binary search tree is a red-black tree if it satisfies the following red-black properties: + // 1. Every node is either red or black + // 2. Every leaf (nil node) is black + // 3. If a node is red, the both its children are black + // 4. Every simple path from a node to a descendant leaf contains the same number of black nodes + // + // The basic idea of red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information + // per node to encode 3-nodes and 4-nodes. + // 4-nodes will be represented as: B + // R R + // 3 -node will be represented as: B or B + // R B B R + // + // For a detailed description of the algorithm, take a look at "Algorithm" by Rebert Sedgewick. + // + + internal delegate bool TreeWalkPredicate( SortedSet.Node node ); + + internal enum TreeRotation + { + LeftRotation = 1, + RightRotation = 2, + RightLeftRotation = 3, + LeftRightRotation = 4, + } + + [SuppressMessage( "Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "by design name choice" )] + [DebuggerDisplay( "Count = {Count}" )] + public class SortedSet : ISet, ICollection, ICollection + { + #region local variables/constants + private Node _root; + private IComparer _comparer; + private int _count; + private int _version; + private object _syncRoot; + + private const string ComparerName = "Comparer"; + private const string CountName = "Count"; + private const string ItemsName = "Items"; + private const string VersionName = "Version"; + //needed for enumerator + private const string TreeName = "Tree"; + private const string NodeValueName = "Item"; + private const string EnumStartName = "EnumStarted"; + private const string ReverseName = "Reverse"; + private const string EnumVersionName = "EnumVersion"; + //needed for TreeSubset + private const string minName = "Min"; + private const string maxName = "Max"; + private const string lBoundActiveName = "lBoundActive"; + private const string uBoundActiveName = "uBoundActive"; + + internal const int StackAllocThreshold = 100; + + #endregion + + #region Constructors + public SortedSet() + { + _comparer = Comparer.Default; + } + + public SortedSet( IComparer comparer ) + { + if ( comparer == null ) + { + _comparer = Comparer.Default; + } + else + { + _comparer = comparer; + } + } + + + public SortedSet( IEnumerable collection ) : this( collection, Comparer.Default ) { } + + public SortedSet( IEnumerable collection, IComparer comparer ) + : this( comparer ) + { + if ( collection == null ) + { + throw new ArgumentNullException( nameof( collection ) ); + } + + // these are explicit type checks in the mould of HashSet. It would have worked better + // with something like an ISorted (we could make this work for SortedList.Keys etc) + SortedSet baseSortedSet = collection as SortedSet; + SortedSet baseTreeSubSet = collection as TreeSubSet; + if ( baseSortedSet != null && baseTreeSubSet == null && AreComparersEqual( this, baseSortedSet ) ) + { + //breadth first traversal to recreate nodes + if ( baseSortedSet.Count == 0 ) + { + return; + } + + //pre order way to replicate nodes + Stack theirStack = new Stack.Node>(2 * log2(baseSortedSet.Count) + 2); + Stack myStack = new Stack.Node>(2 * log2(baseSortedSet.Count) + 2); + Node theirCurrent = baseSortedSet._root; + Node myCurrent = (theirCurrent != null ? new SortedSet.Node(theirCurrent.Item, theirCurrent.IsRed) : null); + _root = myCurrent; + while ( theirCurrent != null ) + { + theirStack.Push( theirCurrent ); + myStack.Push( myCurrent ); + myCurrent.Left = ( theirCurrent.Left != null ? new SortedSet.Node( theirCurrent.Left.Item, theirCurrent.Left.IsRed ) : null ); + theirCurrent = theirCurrent.Left; + myCurrent = myCurrent.Left; + } + while ( theirStack.Count != 0 ) + { + theirCurrent = theirStack.Pop(); + myCurrent = myStack.Pop(); + Node theirRight = theirCurrent.Right; + Node myRight = null; + if ( theirRight != null ) + { + myRight = new SortedSet.Node( theirRight.Item, theirRight.IsRed ); + } + myCurrent.Right = myRight; + + while ( theirRight != null ) + { + theirStack.Push( theirRight ); + myStack.Push( myRight ); + myRight.Left = ( theirRight.Left != null ? new SortedSet.Node( theirRight.Left.Item, theirRight.Left.IsRed ) : null ); + theirRight = theirRight.Left; + myRight = myRight.Left; + } + } + _count = baseSortedSet._count; + } + else + { + int count; + T[] els = EnumerableHelpers.ToArray(collection, out count); + if ( count > 0 ) + { + comparer = _comparer; // If comparer is null, sets it to Comparer.Default + Array.Sort( els, 0, count, comparer ); + int index = 1; + for ( int i = 1; i < count; i++ ) + { + if ( comparer.Compare( els[ i ], els[ i - 1 ] ) != 0 ) + { + els[ index++ ] = els[ i ]; + } + } + count = index; + + _root = ConstructRootFromSortedArray( els, 0, count - 1, null ); + _count = count; + } + } + } + + #endregion + + #region Bulk Operation Helpers + private void AddAllElements( IEnumerable collection ) + { + foreach ( T item in collection ) + { + if ( !Contains( item ) ) + Add( item ); + } + } + + private void RemoveAllElements( IEnumerable collection ) + { + T min = Min; + T max = Max; + foreach ( T item in collection ) + { + if ( !( _comparer.Compare( item, min ) < 0 || _comparer.Compare( item, max ) > 0 ) && Contains( item ) ) + Remove( item ); + } + } + + private bool ContainsAllElements( IEnumerable collection ) + { + foreach ( T item in collection ) + { + if ( !Contains( item ) ) + { + return false; + } + } + return true; + } + + // Do a in order walk on tree and calls the delegate for each node. + // If the action delegate returns false, stop the walk. + // + // Return true if the entire tree has been walked. + // Otherwise returns false. + internal bool InOrderTreeWalk( TreeWalkPredicate action ) + { + return InOrderTreeWalk( action, false ); + } + + // Allows for the change in traversal direction. Reverse visits nodes in descending order + internal virtual bool InOrderTreeWalk( TreeWalkPredicate action, bool reverse ) + { + if ( _root == null ) + { + return true; + } + + // The maximum height of a red-black tree is 2*lg(n+1). + // See page 264 of "Introduction to algorithms" by Thomas H. Cormen + // note: this should be logbase2, but since the stack grows itself, we + // don't want the extra cost + Stack stack = new Stack(2 * (int)(SortedSet.log2(Count + 1))); + Node current = _root; + while ( current != null ) + { + stack.Push( current ); + current = ( reverse ? current.Right : current.Left ); + } + while ( stack.Count != 0 ) + { + current = stack.Pop(); + if ( !action( current ) ) + { + return false; + } + + Node node = (reverse ? current.Left : current.Right); + while ( node != null ) + { + stack.Push( node ); + node = ( reverse ? node.Right : node.Left ); + } + } + return true; + } + + // Do a left to right breadth first walk on tree and + // calls the delegate for each node. + // If the action delegate returns false, stop the walk. + // + // Return true if the entire tree has been walked. + // Otherwise returns false. + internal virtual bool BreadthFirstTreeWalk( TreeWalkPredicate action ) + { + if ( _root == null ) + { + return true; + } + + Queue processQueue = new Queue(); + processQueue.Enqueue( _root ); + Node current; + + while ( processQueue.Count != 0 ) + { + current = processQueue.Dequeue(); + if ( !action( current ) ) + { + return false; + } + if ( current.Left != null ) + { + processQueue.Enqueue( current.Left ); + } + if ( current.Right != null ) + { + processQueue.Enqueue( current.Right ); + } + } + return true; + } + #endregion + + #region Properties + public int Count + { + get + { + VersionCheck(); + return _count; + } + } + + public IComparer Comparer + { + get + { + return _comparer; + } + } + + bool ICollection.IsReadOnly + { + get + { + return false; + } + } + + bool ICollection.IsSynchronized + { + get + { + return false; + } + } + + object ICollection.SyncRoot + { + get + { + if ( _syncRoot == null ) + { + Threading.Interlocked.CompareExchange( ref _syncRoot, new object(), null ); + } + return _syncRoot; + } + } + #endregion + + #region Subclass helpers + + //virtual function for subclass that needs to update count + internal virtual void VersionCheck() { } + + + //virtual function for subclass that needs to do range checks + internal virtual bool IsWithinRange( T item ) + { + return true; + } + #endregion + + #region ICollection Members + /// + /// Add the value ITEM to the tree, returns true if added, false if duplicate + /// + /// item to be added + public bool Add( T item ) + { + return AddIfNotPresent( item ); + } + + void ICollection.Add( T item ) + { + AddIfNotPresent( item ); + } + + /// + /// Adds ITEM to the tree if not already present. Returns TRUE if value was successfully added + /// or FALSE if it is a duplicate + /// + internal virtual bool AddIfNotPresent( T item ) + { + if ( _root == null ) + { // empty tree + _root = new Node( item, false ); + _count = 1; + _version++; + return true; + } + + // Search for a node at bottom to insert the new node. + // If we can guarantee the node we found is not a 4-node, it would be easy to do insertion. + // We split 4-nodes along the search path. + Node current = _root; + Node parent = null; + Node grandParent = null; + Node greatGrandParent = null; + + //even if we don't actually add to the set, we may be altering its structure (by doing rotations + //and such). so update version to disable any enumerators/subsets working on it + _version++; + + int order = 0; + while ( current != null ) + { + order = _comparer.Compare( item, current.Item ); + if ( order == 0 ) + { + // We could have changed root node to red during the search process. + // We need to set it to black before we return. + _root.IsRed = false; + return false; + } + + // split a 4-node into two 2-nodes + if ( Is4Node( current ) ) + { + Split4Node( current ); + // We could have introduced two consecutive red nodes after split. Fix that by rotation. + if ( IsRed( parent ) ) + { + InsertionBalance( current, ref parent, grandParent, greatGrandParent ); + } + } + greatGrandParent = grandParent; + grandParent = parent; + parent = current; + current = ( order < 0 ) ? current.Left : current.Right; + } + + Debug.Assert( parent != null, "Parent node cannot be null here!" ); + // ready to insert the new node + Node node = new Node(item); + if ( order > 0 ) + { + parent.Right = node; + } + else + { + parent.Left = node; + } + + // the new node will be red, so we will need to adjust the colors if parent node is also red + if ( parent.IsRed ) + { + InsertionBalance( node, ref parent, grandParent, greatGrandParent ); + } + + // Root node is always black + _root.IsRed = false; + ++_count; + return true; + } + + /// + /// Remove the T ITEM from this SortedSet. Returns true if successfully removed. + /// + /// + /// + public bool Remove( T item ) + { + return DoRemove( item ); // hack so it can be made non-virtual + } + + internal virtual bool DoRemove( T item ) + { + if ( _root == null ) + { + return false; + } + + // Search for a node and then find its successor. + // Then copy the item from the successor to the matching node and delete the successor. + // If a node doesn't have a successor, we can replace it with its left child (if not empty.) + // or delete the matching node. + // + // In top-down implementation, it is important to make sure the node to be deleted is not a 2-node. + // Following code will make sure the node on the path is not a 2 Node. + + //even if we don't actually remove from the set, we may be altering its structure (by doing rotations + //and such). so update version to disable any enumerators/subsets working on it + _version++; + + Node current = _root; + Node parent = null; + Node grandParent = null; + Node match = null; + Node parentOfMatch = null; + bool foundMatch = false; + while ( current != null ) + { + if ( Is2Node( current ) ) + { // fix up 2-Node + if ( parent == null ) + { // current is root. Mark it as red + current.IsRed = true; + } + else + { + Node sibling = GetSibling(current, parent); + if ( sibling.IsRed ) + { + // If parent is a 3-node, flip the orientation of the red link. + // We can achieve this by a single rotation + // This case is converted to one of other cased below. + Debug.Assert( !parent.IsRed, "parent must be a black node!" ); + if ( parent.Right == sibling ) + { + RotateLeft( parent ); + } + else + { + RotateRight( parent ); + } + + parent.IsRed = true; + sibling.IsRed = false; // parent's color + // sibling becomes child of grandParent or root after rotation. Update link from grandParent or root + ReplaceChildOfNodeOrRoot( grandParent, parent, sibling ); + // sibling will become grandParent of current node + grandParent = sibling; + if ( parent == match ) + { + parentOfMatch = sibling; + } + + // update sibling, this is necessary for following processing + sibling = ( parent.Left == current ) ? parent.Right : parent.Left; + } + Debug.Assert( sibling != null && sibling.IsRed == false, "sibling must not be null and it must be black!" ); + + if ( Is2Node( sibling ) ) + { + Merge2Nodes( parent, current, sibling ); + } + else + { + // current is a 2-node and sibling is either a 3-node or a 4-node. + // We can change the color of current to red by some rotation. + TreeRotation rotation = RotationNeeded(parent, current, sibling); + Node newGrandParent = null; + switch ( rotation ) + { + case TreeRotation.RightRotation: + Debug.Assert( parent.Left == sibling, "sibling must be left child of parent!" ); + Debug.Assert( sibling.Left.IsRed, "Left child of sibling must be red!" ); + sibling.Left.IsRed = false; + newGrandParent = RotateRight( parent ); + break; + case TreeRotation.LeftRotation: + Debug.Assert( parent.Right == sibling, "sibling must be left child of parent!" ); + Debug.Assert( sibling.Right.IsRed, "Right child of sibling must be red!" ); + sibling.Right.IsRed = false; + newGrandParent = RotateLeft( parent ); + break; + + case TreeRotation.RightLeftRotation: + Debug.Assert( parent.Right == sibling, "sibling must be left child of parent!" ); + Debug.Assert( sibling.Left.IsRed, "Left child of sibling must be red!" ); + newGrandParent = RotateRightLeft( parent ); + break; + + case TreeRotation.LeftRightRotation: + Debug.Assert( parent.Left == sibling, "sibling must be left child of parent!" ); + Debug.Assert( sibling.Right.IsRed, "Right child of sibling must be red!" ); + newGrandParent = RotateLeftRight( parent ); + break; + } + + newGrandParent.IsRed = parent.IsRed; + parent.IsRed = false; + current.IsRed = true; + ReplaceChildOfNodeOrRoot( grandParent, parent, newGrandParent ); + if ( parent == match ) + { + parentOfMatch = newGrandParent; + } + grandParent = newGrandParent; + } + } + } + + // we don't need to compare any more once we found the match + int order = foundMatch ? -1 : _comparer.Compare(item, current.Item); + if ( order == 0 ) + { + // save the matching node + foundMatch = true; + match = current; + parentOfMatch = parent; + } + + grandParent = parent; + parent = current; + + if ( order < 0 ) + { + current = current.Left; + } + else + { + current = current.Right; // continue the search in right sub tree after we find a match + } + } + + // move successor to the matching node position and replace links + if ( match != null ) + { + ReplaceNode( match, parentOfMatch, parent, grandParent ); + --_count; + } + + if ( _root != null ) + { + _root.IsRed = false; + } + return foundMatch; + } + + public virtual void Clear() + { + _root = null; + _count = 0; + ++_version; + } + + + public virtual bool Contains( T item ) + { + return FindNode( item ) != null; + } + + public void CopyTo( T[] array ) + { + CopyTo( array, 0, Count ); + } + + public void CopyTo( T[] array, int index ) + { + CopyTo( array, index, Count ); + } + + public void CopyTo( T[] array, int index, int count ) + { + if ( array == null ) + { + throw new ArgumentNullException( nameof( array ) ); + } + + if ( index < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( index ) ); + } + + if ( count < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( count ) ); + } + + // will array, starting at arrayIndex, be able to hold elements? Note: not + // checking arrayIndex >= array.Length (consistency with list of allowing + // count of 0; subsequent check takes care of the rest) + if ( index > array.Length || count > array.Length - index ) + { + throw new ArgumentException( "Array length plus offset is too small." ); + } + //upper bound + count += index; + + InOrderTreeWalk( delegate ( Node node ) + { + if ( index >= count ) + { + return false; + } + else + { + array[ index++ ] = node.Item; + return true; + } + } ); + } + + void ICollection.CopyTo( Array array, int index ) + { + if ( array == null ) + { + throw new ArgumentNullException( nameof( array ) ); + } + + if ( array.Rank != 1 ) + { + throw new ArgumentException( nameof( array ) ); + } + + if ( array.GetLowerBound( 0 ) != 0 ) + { + throw new ArgumentException( nameof( array ) ); + } + + if ( index < 0 ) + { + throw new ArgumentOutOfRangeException( nameof( index ) ); + } + + if ( array.Length - index < Count ) + { + throw new ArgumentException( "Array length plus offset is too small." ); + } + + T[] tarray = array as T[]; + if ( tarray != null ) + { + CopyTo( tarray, index ); + } + else + { + object[] objects = array as object[]; + if ( objects == null ) + { + throw new ArgumentException( "Invalid array type.", nameof( array ) ); + } + + try + { + InOrderTreeWalk( delegate ( Node node ) { objects[ index++ ] = node.Item; return true; } ); + } + catch ( ArrayTypeMismatchException ) + { + throw new ArgumentException( "Invalid array type.", nameof( array ) ); + } + } + } + + #endregion + + #region IEnumerable members + public Enumerator GetEnumerator() + { + return new Enumerator( this ); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( this ); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return new Enumerator( this ); + } + #endregion + + #region Tree Specific Operations + + private static Node GetSibling( Node node, Node parent ) + { + if ( parent.Left == node ) + { + return parent.Right; + } + return parent.Left; + } + + // After calling InsertionBalance, we need to make sure current and parent up-to-date. + // It doesn't matter if we keep grandParent and greatGrantParent up-to-date + // because we won't need to split again in the next node. + // By the time we need to split again, everything will be correctly set. + private void InsertionBalance( Node current, ref Node parent, Node grandParent, Node greatGrandParent ) + { + Debug.Assert( grandParent != null, "Grand parent cannot be null here!" ); + bool parentIsOnRight = (grandParent.Right == parent); + bool currentIsOnRight = (parent.Right == current); + + Node newChildOfGreatGrandParent; + if ( parentIsOnRight == currentIsOnRight ) + { // same orientation, single rotation + newChildOfGreatGrandParent = currentIsOnRight ? RotateLeft( grandParent ) : RotateRight( grandParent ); + } + else + { // different orientation, double rotation + newChildOfGreatGrandParent = currentIsOnRight ? RotateLeftRight( grandParent ) : RotateRightLeft( grandParent ); + // current node now becomes the child of greatgrandparent + parent = greatGrandParent; + } + // grand parent will become a child of either parent of current. + grandParent.IsRed = true; + newChildOfGreatGrandParent.IsRed = false; + + ReplaceChildOfNodeOrRoot( greatGrandParent, grandParent, newChildOfGreatGrandParent ); + } + + private static bool Is2Node( Node node ) + { + Debug.Assert( node != null, "node cannot be null!" ); + return IsBlack( node ) && IsNullOrBlack( node.Left ) && IsNullOrBlack( node.Right ); + } + + private static bool Is4Node( Node node ) + { + return IsRed( node.Left ) && IsRed( node.Right ); + } + + private static bool IsBlack( Node node ) + { + return ( node != null && !node.IsRed ); + } + + private static bool IsNullOrBlack( Node node ) + { + return ( node == null || !node.IsRed ); + } + + private static bool IsRed( Node node ) + { + return ( node != null && node.IsRed ); + } + + private static void Merge2Nodes( Node parent, Node child1, Node child2 ) + { + Debug.Assert( IsRed( parent ), "parent must be red" ); + // combing two 2-nodes into a 4-node + parent.IsRed = false; + child1.IsRed = true; + child2.IsRed = true; + } + + // Replace the child of a parent node. + // If the parent node is null, replace the root. + private void ReplaceChildOfNodeOrRoot( Node parent, Node child, Node newChild ) + { + if ( parent != null ) + { + if ( parent.Left == child ) + { + parent.Left = newChild; + } + else + { + parent.Right = newChild; + } + } + else + { + _root = newChild; + } + } + + // Replace the matching node with its successor. + private void ReplaceNode( Node match, Node parentOfMatch, Node successor, Node parentOfsuccessor ) + { + if ( successor == match ) + { // this node has no successor, should only happen if right child of matching node is null. + Debug.Assert( match.Right == null, "Right child must be null!" ); + successor = match.Left; + } + else + { + Debug.Assert( parentOfsuccessor != null, "parent of successor cannot be null!" ); + Debug.Assert( successor.Left == null, "Left child of successor must be null!" ); + Debug.Assert( ( successor.Right == null && successor.IsRed ) || ( successor.Right.IsRed && !successor.IsRed ), "Successor must be in valid state" ); + if ( successor.Right != null ) + { + successor.Right.IsRed = false; + } + + if ( parentOfsuccessor != match ) + { // detach successor from its parent and set its right child + parentOfsuccessor.Left = successor.Right; + successor.Right = match.Right; + } + + successor.Left = match.Left; + } + + if ( successor != null ) + { + successor.IsRed = match.IsRed; + } + + ReplaceChildOfNodeOrRoot( parentOfMatch, match, successor ); + } + + internal virtual Node FindNode( T item ) + { + Node current = _root; + while ( current != null ) + { + int order = _comparer.Compare(item, current.Item); + if ( order == 0 ) + { + return current; + } + else + { + current = ( order < 0 ) ? current.Left : current.Right; + } + } + + return null; + } + + //used for bithelpers. Note that this implementation is completely different + //from the Subset's. The two should not be mixed. This indexes as if the tree were an array. + //http://en.wikipedia.org/wiki/Binary_Tree#Methods_for_storing_binary_trees + internal virtual int InternalIndexOf( T item ) + { + Node current = _root; + int count = 0; + while ( current != null ) + { + int order = _comparer.Compare(item, current.Item); + if ( order == 0 ) + { + return count; + } + else + { + current = ( order < 0 ) ? current.Left : current.Right; + count = ( order < 0 ) ? ( 2 * count + 1 ) : ( 2 * count + 2 ); + } + } + return -1; + } + + internal Node FindRange( T from, T to ) + { + return FindRange( from, to, true, true ); + } + + internal Node FindRange( T from, T to, bool lowerBoundActive, bool upperBoundActive ) + { + Node current = _root; + while ( current != null ) + { + if ( lowerBoundActive && _comparer.Compare( from, current.Item ) > 0 ) + { + current = current.Right; + } + else + { + if ( upperBoundActive && _comparer.Compare( to, current.Item ) < 0 ) + { + current = current.Left; + } + else + { + return current; + } + } + } + + return null; + } + + internal void UpdateVersion() + { + ++_version; + } + + private static Node RotateLeft( Node node ) + { + Node x = node.Right; + node.Right = x.Left; + x.Left = node; + return x; + } + + private static Node RotateLeftRight( Node node ) + { + Node child = node.Left; + Node grandChild = child.Right; + + node.Left = grandChild.Right; + grandChild.Right = node; + child.Right = grandChild.Left; + grandChild.Left = child; + return grandChild; + } + + private static Node RotateRight( Node node ) + { + Node x = node.Left; + node.Left = x.Right; + x.Right = node; + return x; + } + + private static Node RotateRightLeft( Node node ) + { + Node child = node.Right; + Node grandChild = child.Left; + + node.Right = grandChild.Left; + grandChild.Left = node; + child.Left = grandChild.Right; + grandChild.Right = child; + return grandChild; + } + + /// + /// Testing counter that can track rotations + /// + private static TreeRotation RotationNeeded( Node parent, Node current, Node sibling ) + { + Debug.Assert( IsRed( sibling.Left ) || IsRed( sibling.Right ), "sibling must have at least one red child" ); + if ( IsRed( sibling.Left ) ) + { + if ( parent.Left == current ) + { + return TreeRotation.RightLeftRotation; + } + return TreeRotation.RightRotation; + } + else + { + if ( parent.Left == current ) + { + return TreeRotation.LeftRotation; + } + return TreeRotation.LeftRightRotation; + } + } + + /// + /// Used for deep equality of SortedSet testing + /// + /// + public static IEqualityComparer> CreateSetComparer() + { + return new SortedSetEqualityComparer(); + } + + /// + /// Create a new set comparer for this set, where this set's members' equality is defined by the + /// memberEqualityComparer. Note that this equality comparer's definition of equality must be the + /// same as this set's Comparer's definition of equality + /// + public static IEqualityComparer> CreateSetComparer( IEqualityComparer memberEqualityComparer ) + { + return new SortedSetEqualityComparer( memberEqualityComparer ); + } + + /// + /// Decides whether these sets are the same, given the comparer. If the EC's are the same, we can + /// just use SetEquals, but if they aren't then we have to manually check with the given comparer + /// + internal static bool SortedSetEquals( SortedSet set1, SortedSet set2, IComparer comparer ) + { + // handle null cases first + if ( set1 == null ) + { + return ( set2 == null ); + } + else if ( set2 == null ) + { + // set1 != null + return false; + } + + if ( AreComparersEqual( set1, set2 ) ) + { + if ( set1.Count != set2.Count ) + return false; + + return set1.SetEquals( set2 ); + } + else + { + bool found = false; + foreach ( T item1 in set1 ) + { + found = false; + foreach ( T item2 in set2 ) + { + if ( comparer.Compare( item1, item2 ) == 0 ) + { + found = true; + break; + } + } + if ( !found ) + return false; + } + return true; + } + + } + + //This is a little frustrating because we can't support more sorted structures + private static bool AreComparersEqual( SortedSet set1, SortedSet set2 ) + { + return set1.Comparer.Equals( set2.Comparer ); + } + + private static void Split4Node( Node node ) + { + node.IsRed = true; + node.Left.IsRed = false; + node.Right.IsRed = false; + } + + #endregion + + #region ISet Members + + /// + /// Transform this set into its union with the IEnumerable OTHER + ///Attempts to insert each element and rejects it if it exists. + /// NOTE: The caller object is important as UnionWith uses the Comparator + ///associated with THIS to check equality + /// Throws ArgumentNullException if OTHER is null + /// + /// + public void UnionWith( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + SortedSet s = other as SortedSet; + TreeSubSet t = this as TreeSubSet; + + if ( t != null ) + VersionCheck(); + + if ( s != null && t == null && _count == 0 ) + { + SortedSet dummy = new SortedSet(s, _comparer); + _root = dummy._root; + _count = dummy._count; + _version++; + return; + } + + if ( s != null && t == null && AreComparersEqual( this, s ) && ( s.Count > this.Count / 2 ) ) + { //this actually hurts if N is much greater than M the /2 is arbitrary + //first do a merge sort to an array. + T[] merged = new T[s.Count + this.Count]; + int c = 0; + Enumerator mine = this.GetEnumerator(); + Enumerator theirs = s.GetEnumerator(); + bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext(); + while ( !mineEnded && !theirsEnded ) + { + int comp = Comparer.Compare(mine.Current, theirs.Current); + if ( comp < 0 ) + { + merged[ c++ ] = mine.Current; + mineEnded = !mine.MoveNext(); + } + else if ( comp == 0 ) + { + merged[ c++ ] = theirs.Current; + mineEnded = !mine.MoveNext(); + theirsEnded = !theirs.MoveNext(); + } + else + { + merged[ c++ ] = theirs.Current; + theirsEnded = !theirs.MoveNext(); + } + } + + if ( !mineEnded || !theirsEnded ) + { + Enumerator remaining = (mineEnded ? theirs : mine); + do + { + merged[ c++ ] = remaining.Current; + } while ( remaining.MoveNext() ); + } + + //now merged has all c elements + + //safe to gc the root, we have all the elements + _root = null; + + _root = SortedSet.ConstructRootFromSortedArray( merged, 0, c - 1, null ); + _count = c; + _version++; + } + else + { + AddAllElements( other ); + } + } + + private static Node ConstructRootFromSortedArray( T[] arr, int startIndex, int endIndex, Node redNode ) + { + //what does this do? + //you're given a sorted array... say 1 2 3 4 5 6 + //2 cases: + // If there are odd # of elements, pick the middle element (in this case 4), and compute + // its left and right branches + // If there are even # of elements, pick the left middle element, save the right middle element + // and call the function on the rest + // 1 2 3 4 5 6 -> pick 3, save 4 and call the fn on 1,2 and 5,6 + // now add 4 as a red node to the lowest element on the right branch + // 3 3 + // 1 5 -> 1 5 + // 2 6 2 4 6 + // As we're adding to the leftmost of the right branch, nesting will not hurt the red-black properties + // Leaf nodes are red if they have no sibling (if there are 2 nodes or if a node trickles + // down to the bottom + + //the iterative way to do this ends up wasting more space than it saves in stack frames (at + //least in what i tried) + //so we're doing this recursively + //base cases are described below + int size = endIndex - startIndex + 1; + if ( size == 0 ) + { + return null; + } + Node root = null; + if ( size == 1 ) + { + root = new Node( arr[ startIndex ], false ); + if ( redNode != null ) + { + root.Left = redNode; + } + } + else if ( size == 2 ) + { + root = new Node( arr[ startIndex ], false ); + root.Right = new Node( arr[ endIndex ], false ); + root.Right.IsRed = true; + if ( redNode != null ) + { + root.Left = redNode; + } + } + else if ( size == 3 ) + { + root = new Node( arr[ startIndex + 1 ], false ); + root.Left = new Node( arr[ startIndex ], false ); + root.Right = new Node( arr[ endIndex ], false ); + if ( redNode != null ) + { + root.Left.Left = redNode; + } + } + else + { + int midpt = ((startIndex + endIndex) / 2); + root = new Node( arr[ midpt ], false ); + root.Left = ConstructRootFromSortedArray( arr, startIndex, midpt - 1, redNode ); + if ( size % 2 == 0 ) + { + root.Right = ConstructRootFromSortedArray( arr, midpt + 2, endIndex, new Node( arr[ midpt + 1 ], true ) ); + } + else + { + root.Right = ConstructRootFromSortedArray( arr, midpt + 1, endIndex, null ); + } + } + return root; + } + + /// + /// Transform this set into its intersection with the IEnumerable OTHER + /// NOTE: The caller object is important as IntersectionWith uses the + /// comparator associated with THIS to check equality + /// Throws ArgumentNullException if OTHER is null + /// + /// + public virtual void IntersectWith( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( Count == 0 ) + return; + + //HashSet optimizations can't be done until equality comparers and comparers are related + + //Technically, this would work as well with an ISorted + SortedSet s = other as SortedSet; + TreeSubSet t = this as TreeSubSet; + if ( t != null ) + VersionCheck(); + //only let this happen if i am also a SortedSet, not a SubSet + if ( s != null && t == null && AreComparersEqual( this, s ) ) + { + //first do a merge sort to an array. + T[] merged = new T[this.Count]; + int c = 0; + Enumerator mine = this.GetEnumerator(); + Enumerator theirs = s.GetEnumerator(); + bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext(); + T max = Max; + T min = Min; + + while ( !mineEnded && !theirsEnded && Comparer.Compare( theirs.Current, max ) <= 0 ) + { + int comp = Comparer.Compare(mine.Current, theirs.Current); + if ( comp < 0 ) + { + mineEnded = !mine.MoveNext(); + } + else if ( comp == 0 ) + { + merged[ c++ ] = theirs.Current; + mineEnded = !mine.MoveNext(); + theirsEnded = !theirs.MoveNext(); + } + else + { + theirsEnded = !theirs.MoveNext(); + } + } + + //now merged has all c elements + + //safe to gc the root, we have all the elements + _root = null; + + _root = SortedSet.ConstructRootFromSortedArray( merged, 0, c - 1, null ); + _count = c; + _version++; + } + else + { + IntersectWithEnumerable( other ); + } + } + + internal virtual void IntersectWithEnumerable( IEnumerable other ) + { + //TODO: Perhaps a more space-conservative way to do this + List toSave = new List(Count); + foreach ( T item in other ) + { + if ( Contains( item ) ) + { + toSave.Add( item ); + } + } + + if ( toSave.Count < Count ) + { + Clear(); + AddAllElements( toSave ); + } + } + + /// + /// Transform this set into its complement with the IEnumerable OTHER + /// NOTE: The caller object is important as ExceptWith uses the + /// comparator associated with THIS to check equality + /// Throws ArgumentNullException if OTHER is null + /// + /// + public void ExceptWith( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( _count == 0 ) + return; + + if ( other == this ) + { + Clear(); + return; + } + + SortedSet asSorted = other as SortedSet; + + if ( asSorted != null && AreComparersEqual( this, asSorted ) ) + { + //outside range, no point doing anything + if ( !( _comparer.Compare( asSorted.Max, Min ) < 0 || _comparer.Compare( asSorted.Min, Max ) > 0 ) ) + { + T min = Min; + T max = Max; + foreach ( T item in other ) + { + if ( _comparer.Compare( item, min ) < 0 ) + continue; + if ( _comparer.Compare( item, max ) > 0 ) + break; + Remove( item ); + } + } + } + else + { + RemoveAllElements( other ); + } + } + + /// + /// Transform this set so it contains elements in THIS or OTHER but not both + /// NOTE: The caller object is important as SymmetricExceptWith uses the + /// comparator associated with THIS to check equality + /// Throws ArgumentNullException if OTHER is null + /// + /// + public void SymmetricExceptWith( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( Count == 0 ) + { + UnionWith( other ); + return; + } + + if ( other == this ) + { + Clear(); + return; + } + + SortedSet asSorted = other as SortedSet; + + if ( asSorted != null && AreComparersEqual( this, asSorted ) ) + { + SymmetricExceptWithSameEC( asSorted ); + } + else + { + int length; + T[] elements = EnumerableHelpers.ToArray(other, out length); + Array.Sort( elements, 0, length, Comparer ); + SymmetricExceptWithSameEC( elements, length ); + } + } + + private void SymmetricExceptWithSameEC( SortedSet other ) + { + Debug.Assert( other != null ); + Debug.Assert( AreComparersEqual( this, other ) ); + + foreach ( T item in other ) + { + //yes, it is classier to say + //if (!this.Remove(item))this.Add(item); + //but this ends up saving on rotations + if ( Contains( item ) ) + { + Remove( item ); + } + else + { + Add( item ); + } + } + } + + //OTHER must be a sorted array + private void SymmetricExceptWithSameEC( T[] other, int count ) + { + Debug.Assert( other != null ); + Debug.Assert( count >= 0 && count <= other.Length ); + + if ( count == 0 ) + { + return; + } + T last = other[0]; + for ( int i = 0; i < count; i++ ) + { + while ( i < count && i != 0 && _comparer.Compare( other[ i ], last ) == 0 ) + i++; + if ( i >= count ) + break; + if ( Contains( other[ i ] ) ) + { + Remove( other[ i ] ); + } + else + { + Add( other[ i ] ); + } + last = other[ i ]; + } + } + + /// + /// Checks whether this Tree is a subset of the IEnumerable other + /// + /// + /// + public bool IsSubsetOf( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( Count == 0 ) + return true; + + + SortedSet asSorted = other as SortedSet; + if ( asSorted != null && AreComparersEqual( this, asSorted ) ) + { + if ( Count > asSorted.Count ) + return false; + return IsSubsetOfSortedSetWithSameEC( asSorted ); + } + else + { + //worst case: mark every element in my set and see if I've counted all + //O(MlogN) + + ElementCount result = CheckUniqueAndUnfoundElements(other, false); + return ( result.uniqueCount == Count && result.unfoundCount >= 0 ); + } + } + + private bool IsSubsetOfSortedSetWithSameEC( SortedSet asSorted ) + { + SortedSet prunedOther = asSorted.GetViewBetween(Min, Max); + foreach ( T item in this ) + { + if ( !prunedOther.Contains( item ) ) + return false; + } + return true; + } + + /// + /// Checks whether this Tree is a proper subset of the IEnumerable other + /// + /// + /// + public bool IsProperSubsetOf( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( ( other as ICollection ) != null ) + { + if ( Count == 0 ) + return ( other as ICollection ).Count > 0; + } + + //another for sorted sets with the same comparer + SortedSet asSorted = other as SortedSet; + if ( asSorted != null && AreComparersEqual( this, asSorted ) ) + { + if ( Count >= asSorted.Count ) + return false; + return IsSubsetOfSortedSetWithSameEC( asSorted ); + } + + //worst case: mark every element in my set and see if I've counted all + //O(MlogN). + ElementCount result = CheckUniqueAndUnfoundElements(other, false); + return ( result.uniqueCount == Count && result.unfoundCount > 0 ); + } + + /// + /// Checks whether this Tree is a super set of the IEnumerable other + /// + /// + /// + public bool IsSupersetOf( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( ( other as ICollection ) != null && ( other as ICollection ).Count == 0 ) + return true; + + //do it one way for HashSets + //another for sorted sets with the same comparer + SortedSet asSorted = other as SortedSet; + if ( asSorted != null && AreComparersEqual( this, asSorted ) ) + { + if ( Count < asSorted.Count ) + return false; + SortedSet pruned = GetViewBetween(asSorted.Min, asSorted.Max); + foreach ( T item in asSorted ) + { + if ( !pruned.Contains( item ) ) + return false; + } + return true; + } + //and a third for everything else + return ContainsAllElements( other ); + } + + /// + /// Checks whether this Tree is a proper super set of the IEnumerable other + /// + /// + /// + public bool IsProperSupersetOf( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( Count == 0 ) + return false; + + if ( ( other as ICollection ) != null && ( other as ICollection ).Count == 0 ) + return true; + + //another way for sorted sets + SortedSet asSorted = other as SortedSet; + if ( asSorted != null && AreComparersEqual( asSorted, this ) ) + { + if ( asSorted.Count >= Count ) + return false; + SortedSet pruned = GetViewBetween(asSorted.Min, asSorted.Max); + foreach ( T item in asSorted ) + { + if ( !pruned.Contains( item ) ) + return false; + } + return true; + } + + //worst case: mark every element in my set and see if I've counted all + //O(MlogN) + //slight optimization, put it into a HashSet and then check can do it in O(N+M) + //but slower in better cases + wastes space + ElementCount result = CheckUniqueAndUnfoundElements(other, true); + return ( result.uniqueCount < Count && result.unfoundCount == 0 ); + } + + /// + /// Checks whether this Tree has all elements in common with IEnumerable other + /// + /// + /// + public bool SetEquals( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + SortedSet asSorted = other as SortedSet; + if ( asSorted != null && AreComparersEqual( this, asSorted ) ) + { + Enumerator mine = GetEnumerator(); + Enumerator theirs = asSorted.GetEnumerator(); + bool mineEnded = !mine.MoveNext(); + bool theirsEnded = !theirs.MoveNext(); + while ( !mineEnded && !theirsEnded ) + { + if ( Comparer.Compare( mine.Current, theirs.Current ) != 0 ) + { + return false; + } + mineEnded = !mine.MoveNext(); + theirsEnded = !theirs.MoveNext(); + } + return mineEnded && theirsEnded; + } + + //worst case: mark every element in my set and see if I've counted all + //O(N) by size of other + ElementCount result = CheckUniqueAndUnfoundElements(other, true); + return ( result.uniqueCount == Count && result.unfoundCount == 0 ); + } + + /// + /// Checks whether this Tree has any elements in common with IEnumerable other + /// + /// + /// + public bool Overlaps( IEnumerable other ) + { + if ( other == null ) + { + throw new ArgumentNullException( nameof( other ) ); + } + + if ( Count == 0 ) + return false; + + if ( ( other as ICollection != null ) && ( other as ICollection ).Count == 0 ) + return false; + + SortedSet asSorted = other as SortedSet; + if ( asSorted != null && AreComparersEqual( this, asSorted ) && ( _comparer.Compare( Min, asSorted.Max ) > 0 || _comparer.Compare( Max, asSorted.Min ) < 0 ) ) + { + return false; + } + foreach ( T item in other ) + { + if ( Contains( item ) ) + { + return true; + } + } + return false; + } + + /// + /// This works similar to HashSet's CheckUniqueAndUnfound (description below), except that the bit + /// array maps differently than in the HashSet. We can only use this for the bulk boolean checks. + /// + /// Determines counts that can be used to determine equality, subset, and superset. This + /// is only used when other is an IEnumerable and not a HashSet. If other is a HashSet + /// these properties can be checked faster without use of marking because we can assume + /// other has no duplicates. + /// + /// The following count checks are performed by callers: + /// 1. Equals: checks if unfoundCount = 0 and uniqueFoundCount = Count; i.e. everything + /// in other is in this and everything in this is in other + /// 2. Subset: checks if unfoundCount >= 0 and uniqueFoundCount = Count; i.e. other may + /// have elements not in this and everything in this is in other + /// 3. Proper subset: checks if unfoundCount > 0 and uniqueFoundCount = Count; i.e + /// other must have at least one element not in this and everything in this is in other + /// 4. Proper superset: checks if unfound count = 0 and uniqueFoundCount strictly less + /// than Count; i.e. everything in other was in this and this had at least one element + /// not contained in other. + /// + /// An earlier implementation used delegates to perform these checks rather than returning + /// an ElementCount struct; however this was changed due to the perf overhead of delegates. + /// + /// + /// Allows us to finish faster for equals and proper superset + /// because unfoundCount must be 0. + /// + // + // + // + // + // + // + private ElementCount CheckUniqueAndUnfoundElements( IEnumerable other, bool returnIfUnfound ) + { + ElementCount result; + + // need special case in case this has no elements. + if ( Count == 0 ) + { + int numElementsInOther = 0; + foreach ( T item in other ) + { + numElementsInOther++; + // break right away, all we want to know is whether other has 0 or 1 elements + break; + } + result.uniqueCount = 0; + result.unfoundCount = numElementsInOther; + return result; + } + + int originalLastIndex = Count; + int intArrayLength = BitHelper.ToIntArrayLength(originalLastIndex); + + BitHelper bitHelper; + int[] bitArray = new int[intArrayLength]; + bitHelper = new BitHelper( bitArray, intArrayLength ); + + // count of items in other not found in this + int unfoundCount = 0; + // count of unique items in other found in this + int uniqueFoundCount = 0; + + foreach ( T item in other ) + { + int index = InternalIndexOf(item); + if ( index >= 0 ) + { + if ( !bitHelper.IsMarked( index ) ) + { + // item hasn't been seen yet + bitHelper.MarkBit( index ); + uniqueFoundCount++; + } + } + else + { + unfoundCount++; + if ( returnIfUnfound ) + { + break; + } + } + } + + result.uniqueCount = uniqueFoundCount; + result.unfoundCount = unfoundCount; + return result; + } + public int RemoveWhere( Predicate match ) + { + if ( match == null ) + { + throw new ArgumentNullException( nameof( match ) ); + } + List matches = new List(this.Count); + + BreadthFirstTreeWalk( delegate ( Node n ) + { + if ( match( n.Item ) ) + { + matches.Add( n.Item ); + } + return true; + } ); + // reverse breadth first to (try to) incur low cost + int actuallyRemoved = 0; + for ( int i = matches.Count - 1; i >= 0; i-- ) + { + if ( Remove( matches[ i ] ) ) + { + actuallyRemoved++; + } + } + + return actuallyRemoved; + } + #endregion + + #region ISorted Members + public T Min + { + get + { + if ( _root == null ) + { + return default( T ); + } + + Node current = _root; + while ( current.Left != null ) + { + current = current.Left; + } + + return current.Item; + } + } + + public T Max + { + get + { + if ( _root == null ) + { + return default( T ); + } + + Node current = _root; + while ( current.Right != null ) + { + current = current.Right; + } + + return current.Item; + } + } + + public IEnumerable Reverse() + { + Enumerator e = new Enumerator(this, true); + while ( e.MoveNext() ) + { + yield return e.Current; + } + } + + /// + /// Returns a subset of this tree ranging from values lBound to uBound + /// Any changes made to the subset reflect in the actual tree + /// + /// Lowest Value allowed in the subset + /// Highest Value allowed in the subset + public virtual SortedSet GetViewBetween( T lowerValue, T upperValue ) + { + if ( Comparer.Compare( lowerValue, upperValue ) > 0 ) + { + throw new ArgumentException( "The lower value is greater than upper value.", nameof( lowerValue ) ); + } + return new TreeSubSet( this, lowerValue, upperValue, true, true ); + } + +#if DEBUG + + /// + /// debug status to be checked whenever any operation is called + /// + /// + internal virtual bool versionUpToDate() + { + return true; + } +#endif + + /// + /// This class represents a subset view into the tree. Any changes to this view + /// are reflected in the actual tree. Uses the Comparator of the underlying tree. + /// + /// + internal sealed class TreeSubSet : SortedSet + { + private SortedSet _underlying; + private T _min, _max; + //these exist for unbounded collections + //for instance, you could allow this subset to be defined for i>10. The set will throw if + //anything <=10 is added, but there is no upperbound. These features Head(), Tail(), were punted + //in the spec, and are not available, but the framework is there to make them available at some point. + private bool _lBoundActive, _uBoundActive; + //used to see if the count is out of date + +#if DEBUG + internal override bool versionUpToDate() + { + return ( _version == _underlying._version ); + } +#endif + + public TreeSubSet( SortedSet Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive ) + : base( Underlying.Comparer ) + { + _underlying = Underlying; + _min = Min; + _max = Max; + _lBoundActive = lowerBoundActive; + _uBoundActive = upperBoundActive; + _root = _underlying.FindRange( _min, _max, _lBoundActive, _uBoundActive ); // root is first element within range + _count = 0; + _version = -1; + VersionCheckImpl(); + } + + /// + /// Additions to this tree need to be added to the underlying tree as well + /// + internal override bool AddIfNotPresent( T item ) + { + if ( !IsWithinRange( item ) ) + { + throw new ArgumentOutOfRangeException( nameof( item ) ); + } + + bool ret = _underlying.AddIfNotPresent(item); + VersionCheck(); +#if DEBUG + Debug.Assert( this.versionUpToDate() && _root == _underlying.FindRange( _min, _max ) ); +#endif + + return ret; + } + + public override bool Contains( T item ) + { + VersionCheck(); +#if DEBUG + Debug.Assert( versionUpToDate() && _root == _underlying.FindRange( _min, _max ) ); +#endif + return base.Contains( item ); + } + + internal override bool DoRemove( T item ) + { // todo: uppercase this and others + if ( !IsWithinRange( item ) ) + { + return false; + } + + bool ret = _underlying.Remove(item); + VersionCheck(); +#if DEBUG + Debug.Assert( versionUpToDate() && _root == _underlying.FindRange( _min, _max ) ); +#endif + return ret; + } + + public override void Clear() + { + if ( _count == 0 ) + { + return; + } + + List toRemove = new List(); + BreadthFirstTreeWalk( delegate ( Node n ) { toRemove.Add( n.Item ); return true; } ); + while ( toRemove.Count != 0 ) + { + _underlying.Remove( toRemove[ toRemove.Count - 1 ] ); + toRemove.RemoveAt( toRemove.Count - 1 ); + } + _root = null; + _count = 0; + _version = _underlying._version; + } + + internal override bool IsWithinRange( T item ) + { + int comp = (_lBoundActive ? Comparer.Compare(_min, item) : -1); + if ( comp > 0 ) + { + return false; + } + comp = ( _uBoundActive ? Comparer.Compare( _max, item ) : 1 ); + if ( comp < 0 ) + { + return false; + } + return true; + } + + internal override bool InOrderTreeWalk( TreeWalkPredicate action, bool reverse ) + { + VersionCheck(); + + if ( _root == null ) + { + return true; + } + + // The maximum height of a red-black tree is 2*lg(n+1). + // See page 264 of "Introduction to algorithms" by Thomas H. Cormen + Stack stack = new Stack(2 * (int)SortedSet.log2(_count + 1)); //this is not exactly right if count is out of date, but the stack can grow + Node current = _root; + while ( current != null ) + { + if ( IsWithinRange( current.Item ) ) + { + stack.Push( current ); + current = ( reverse ? current.Right : current.Left ); + } + else if ( _lBoundActive && Comparer.Compare( _min, current.Item ) > 0 ) + { + current = current.Right; + } + else + { + current = current.Left; + } + } + + while ( stack.Count != 0 ) + { + current = stack.Pop(); + if ( !action( current ) ) + { + return false; + } + + Node node = (reverse ? current.Left : current.Right); + while ( node != null ) + { + if ( IsWithinRange( node.Item ) ) + { + stack.Push( node ); + node = ( reverse ? node.Right : node.Left ); + } + else if ( _lBoundActive && Comparer.Compare( _min, node.Item ) > 0 ) + { + node = node.Right; + } + else + { + node = node.Left; + } + } + } + return true; + } + + internal override bool BreadthFirstTreeWalk( TreeWalkPredicate action ) + { + VersionCheck(); + + if ( _root == null ) + { + return true; + } + + Queue processQueue = new Queue(); + processQueue.Enqueue( _root ); + Node current; + + while ( processQueue.Count != 0 ) + { + current = processQueue.Dequeue(); + if ( IsWithinRange( current.Item ) && !action( current ) ) + { + return false; + } + if ( current.Left != null && ( !_lBoundActive || Comparer.Compare( _min, current.Item ) < 0 ) ) + { + processQueue.Enqueue( current.Left ); + } + if ( current.Right != null && ( !_uBoundActive || Comparer.Compare( _max, current.Item ) > 0 ) ) + { + processQueue.Enqueue( current.Right ); + } + } + return true; + } + + internal override SortedSet.Node FindNode( T item ) + { + if ( !IsWithinRange( item ) ) + { + return null; + } + VersionCheck(); +#if DEBUG + Debug.Assert( this.versionUpToDate() && _root == _underlying.FindRange( _min, _max ) ); +#endif + return base.FindNode( item ); + } + + //this does indexing in an inefficient way compared to the actual sortedset, but it saves a + //lot of space + internal override int InternalIndexOf( T item ) + { + int count = -1; + foreach ( T i in this ) + { + count++; + if ( Comparer.Compare( item, i ) == 0 ) + return count; + } +#if DEBUG + Debug.Assert( this.versionUpToDate() && _root == _underlying.FindRange( _min, _max ) ); +#endif + return -1; + } + + /// + /// checks whether this subset is out of date. updates if necessary. + /// + internal override void VersionCheck() + { + VersionCheckImpl(); + } + + private void VersionCheckImpl() + { + Debug.Assert( _underlying != null, "Underlying set no longer exists" ); + if ( _version != _underlying._version ) + { + _root = _underlying.FindRange( _min, _max, _lBoundActive, _uBoundActive ); + _version = _underlying._version; + _count = 0; + InOrderTreeWalk( delegate ( Node n ) { _count++; return true; } ); + } + } + + //This passes functionality down to the underlying tree, clipping edges if necessary + //There's nothing gained by having a nested subset. May as well draw it from the base + //Cannot increase the bounds of the subset, can only decrease it + public override SortedSet GetViewBetween( T lowerValue, T upperValue ) + { + if ( _lBoundActive && Comparer.Compare( _min, lowerValue ) > 0 ) + { + //lBound = min; + throw new ArgumentOutOfRangeException( nameof( lowerValue ) ); + } + if ( _uBoundActive && Comparer.Compare( _max, upperValue ) < 0 ) + { + //uBound = max; + throw new ArgumentOutOfRangeException( nameof( upperValue ) ); + } + TreeSubSet ret = (TreeSubSet)_underlying.GetViewBetween(lowerValue, upperValue); + return ret; + } + +#if DEBUG + internal override void IntersectWithEnumerable( IEnumerable other ) + { + base.IntersectWithEnumerable( other ); + Debug.Assert( versionUpToDate() && _root == _underlying.FindRange( _min, _max ) ); + } +#endif + } + #endregion + + #region Helper Classes + internal sealed class Node + { + public bool IsRed; + public T Item; + public Node Left; + public Node Right; + + public Node( T item ) + { + // The default color will be red, we never need to create a black node directly. + Item = item; + IsRed = true; + } + + public Node( T item, bool isRed ) + { + // The default color will be red, we never need to create a black node directly. + Item = item; + IsRed = isRed; + } + } + + [SuppressMessage( "Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario" )] + public struct Enumerator : IEnumerator, IEnumerator + { + private SortedSet _tree; + private int _version; + + private Stack.Node> _stack; + private SortedSet.Node _current; + + private bool _reverse; + private static SortedSet.Node s_dummyNode = new SortedSet.Node(default(T)); + + internal Enumerator( SortedSet set ) + { + _tree = set; + _tree.VersionCheck(); // make sure that the underlying subset has not been changed since + + _version = _tree._version; + + // 2lg(n + 1) is the maximum height + _stack = new Stack.Node>( 2 * ( int )SortedSet.log2( set.Count + 1 ) ); + _current = null; + _reverse = false; + + Intialize(); + } + + internal Enumerator( SortedSet set, bool reverse ) + { + _tree = set; + _tree.VersionCheck(); // make sure that the underlying subset has not been changed since + _version = _tree._version; + + // 2lg(n + 1) is the maximum height + _stack = new Stack.Node>( 2 * ( int )SortedSet.log2( set.Count + 1 ) ); + _current = null; + _reverse = reverse; + + Intialize(); + } + + private void Intialize() + { + _current = null; + SortedSet.Node node = _tree._root; + Node next = null, other = null; + while ( node != null ) + { + next = ( _reverse ? node.Right : node.Left ); + other = ( _reverse ? node.Left : node.Right ); + if ( _tree.IsWithinRange( node.Item ) ) + { + _stack.Push( node ); + node = next; + } + else if ( next == null || !_tree.IsWithinRange( next.Item ) ) + { + node = other; + } + else + { + node = next; + } + } + } + + public bool MoveNext() + { + // Make sure that the underlying subset has not been changed since + _tree.VersionCheck(); + + if ( _version != _tree._version ) + { + throw new InvalidOperationException( "Enum failed version." ); + } + + if ( _stack.Count == 0 ) + { + _current = null; + return false; + } + + _current = _stack.Pop(); + SortedSet.Node node = (_reverse ? _current.Left : _current.Right); + Node next = null, other = null; + while ( node != null ) + { + next = ( _reverse ? node.Right : node.Left ); + other = ( _reverse ? node.Left : node.Right ); + if ( _tree.IsWithinRange( node.Item ) ) + { + _stack.Push( node ); + node = next; + } + else if ( other == null || !_tree.IsWithinRange( other.Item ) ) + { + node = next; + } + else + { + node = other; + } + } + return true; + } + + public void Dispose() + { + } + + public T Current + { + get + { + if ( _current != null ) + { + return _current.Item; + } + return default( T ); + } + } + + object IEnumerator.Current + { + get + { + if ( _current == null ) + { + throw new InvalidOperationException( "Enum op cannot happen." ); + } + + return _current.Item; + } + } + + internal bool NotStartedOrEnded + { + get + { + return _current == null; + } + } + + internal void Reset() + { + if ( _version != _tree._version ) + { + throw new InvalidOperationException( "Enum failed version." ); + } + + _stack.Clear(); + Intialize(); + } + + void IEnumerator.Reset() + { + Reset(); + } + } + + internal struct ElementCount + { + internal int uniqueCount; + internal int unfoundCount; + } + #endregion + + #region misc + // used for set checking operations (using enumerables) that rely on counting + private static int log2( int value ) + { + int c = 0; + while ( value > 0 ) + { + c++; + value >>= 1; + } + return c; + } + #endregion + } + + /// + /// A class that generates an IEqualityComparer for this SortedSet. Requires that the definition of + /// equality defined by the IComparer for this SortedSet be consistent with the default IEqualityComparer + /// for the type T. If not, such an IEqualityComparer should be provided through the constructor. + /// + internal sealed class SortedSetEqualityComparer : IEqualityComparer> + { + private readonly IComparer _comparer; + private readonly IEqualityComparer _memberEqualityComparer; + + public SortedSetEqualityComparer() : this( null, null ) { } + + public SortedSetEqualityComparer( IEqualityComparer memberEqualityComparer ) : this( null, memberEqualityComparer ) { } + + /// + /// Create a new SetEqualityComparer, given a comparer for member order and another for member equality (these + /// must be consistent in their definition of equality) + /// + private SortedSetEqualityComparer( IComparer comparer, IEqualityComparer memberEqualityComparer ) + { + _comparer = comparer ?? Comparer.Default; + _memberEqualityComparer = memberEqualityComparer ?? EqualityComparer.Default; + } + + // using comparer to keep equals properties in tact; don't want to choose one of the comparers + public bool Equals( SortedSet x, SortedSet y ) + { + return SortedSet.SortedSetEquals( x, y, _comparer ); + } + + //IMPORTANT: this part uses the fact that GetHashCode() is consistent with the notion of equality in + //the set + public int GetHashCode( SortedSet obj ) + { + int hashCode = 0; + if ( obj != null ) + { + foreach ( T t in obj ) + { + hashCode = hashCode ^ ( _memberEqualityComparer.GetHashCode( t ) & 0x7FFFFFFF ); + } + } // else returns hashcode of 0 for null HashSets + return hashCode; + } + + // Equals method for the comparer itself. + public override bool Equals( object obj ) + { + SortedSetEqualityComparer comparer = obj as SortedSetEqualityComparer; + if ( comparer == null ) + { + return false; + } + return ( _comparer == comparer._comparer ); + } + + public override int GetHashCode() + { + return _comparer.GetHashCode() ^ _memberEqualityComparer.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.5/System/MidpointRouding.cs b/test/MsgPack.UnitTest.Silverlight.5/System/MidpointRouding.cs new file mode 100644 index 000000000..984fb79ee --- /dev/null +++ b/test/MsgPack.UnitTest.Silverlight.5/System/MidpointRouding.cs @@ -0,0 +1,16 @@ +// 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. + +// From coreclr MidpointRounding + +namespace System +{ + + [System.Runtime.InteropServices.ComVisible( true )] + public enum MidpointRounding + { + ToEven = 0, + AwayFromZero = 1, + } +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Silverlight.WindowsPhone/MsgPack.UnitTest.Silverlight.WindowsPhone.csproj b/test/MsgPack.UnitTest.Silverlight.WindowsPhone/MsgPack.UnitTest.Silverlight.WindowsPhone.csproj index e0b14a5c2..a9c359ebe 100644 --- a/test/MsgPack.UnitTest.Silverlight.WindowsPhone/MsgPack.UnitTest.Silverlight.WindowsPhone.csproj +++ b/test/MsgPack.UnitTest.Silverlight.WindowsPhone/MsgPack.UnitTest.Silverlight.WindowsPhone.csproj @@ -1,15 +1,11 @@  - Debug - x86 10.0.20506 2.0 {288171D8-50E5-4DA2-9802-55D23D5A2307} {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} Library - Properties - MsgPack MsgPack.UnitTest.Silverlight.WindowsPhone WindowsPhone v8.0 @@ -26,55 +22,50 @@ 11.0 true - - true - full - false - Bin\x86\Debug - TRACE;DEBUG;SILVERLIGHT;WINDOWS_PHONE;MSTEST - true - true - prompt - 4 - - - pdbonly - true - Bin\x86\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - true - full - false - Bin\ARM\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - pdbonly - true - Bin\ARM\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE + + + + $(DefineConstants);SILVERLIGHT;WINDOWS_PHONE;MSTEST true true - prompt - 4 + + _SetUpFixture.cs + + + AssertEx.cs + BigEndianBinaryTest.cs + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + CollectionAssertEx.cs + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + DirectConversionTest.cs @@ -87,18 +78,30 @@ ExceptionTest.cs + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + GenericExceptionTester.cs Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -156,18 +159,15 @@ MessageUnpackableTest.cs + + PackerFactoryTest.cs + PackerTest.cs - - PackerTest.Miscs.cs - PackerTest.Pack.cs - - PackerTest.Pack.Miscs.cs - PackerTest.PackBinary.cs @@ -186,6 +186,15 @@ PackUnpackTest.Scalar.cs + + Serialization\_SetUpFixture.cs + + + Serialization\MessagePackMemberAndDataMemberMixedTarget.cs + + + Serialization\MessagePackMemberAttributeTest.cs + Serialization\AddOnlyCollection`1.cs @@ -249,18 +258,15 @@ Serialization\IVerifiable`1.cs + + Serialization\KeyNameTransformersTest.cs + Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs Serialization\MapReflectionBasedEnumSerializationTest.cs - - Serialization\MessagePackMemberAndDataMemberMixedTarget.cs - - - Serialization\MessagePackMemberAttributeTest.cs - Serialization\MessagePackSerializerTest.cs @@ -300,9 +306,15 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs + + Serialization\TimestampSerializationTest.cs + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs @@ -318,14 +330,26 @@ Serialization\VersioningTest.cs - - Serialization\_SetUpFixture.cs - SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs TestRandom.cs @@ -333,6 +357,33 @@ TestSuite.cs + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + UnpackerTest.cs @@ -354,6 +405,9 @@ UnpackerTest.Skip.Variations.cs + + UnpackerTest.Subtree.cs + UnpackingTest.Combinations.Array.cs @@ -411,9 +465,6 @@ UnpackingTest.Scalar.cs - - _SetUpFixture.cs - App.xaml diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/MsgPack.UnitTest.Timestamp.Xamarin.Android.csproj b/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/MsgPack.UnitTest.Timestamp.Xamarin.Android.csproj new file mode 100644 index 000000000..d44e9ffe8 --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/MsgPack.UnitTest.Timestamp.Xamarin.Android.csproj @@ -0,0 +1,67 @@ + + + + {64868f91-8537-4cc7-9900-a29d5e51fb52} + {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + MsgPack.UnitTest.Timestamp.Xamarin.Android + + + + + AssertEx.cs + + + CollectionAssertEx.cs + + + LegacyJapaneseCultureInfo.cs + + + Serialization\TimestampSerializationTest.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + TestRandom.cs + + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + + + + Resources\drawable\Icon.png + + + Resources\values\Strings.xml + Designer + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/Properties/AndroidManifest.xml b/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/Properties/AndroidManifest.xml new file mode 100644 index 000000000..534a35030 --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/Properties/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/Resources/Resource.Designer.cs b/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/Resources/Resource.Designer.cs new file mode 100644 index 000000000..a8f80078b --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.Android/Resources/Resource.Designer.cs @@ -0,0 +1,191 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// このコードはツールによって生成されました。 +// ランタイム バージョン:4.0.30319.42000 +// +// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 +// コードが再生成されるときに損失したりします。 +// +//------------------------------------------------------------------------------ + +[assembly: global::Android.Runtime.ResourceDesignerAttribute("MsgPack.Resource", IsApplication=true)] + +namespace MsgPack +{ + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] + public partial class Resource + { + + static Resource() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + public static void UpdateIdValues() + { + global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::MsgPack.Resource.Id.OptionHostName; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::MsgPack.Resource.Id.OptionPort; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::MsgPack.Resource.Id.OptionRemoteServer; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::MsgPack.Resource.Id.OptionsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::MsgPack.Resource.Id.ResultFullName; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::MsgPack.Resource.Id.ResultMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::MsgPack.Resource.Id.ResultResultState; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::MsgPack.Resource.Id.ResultRunSingleMethodTest; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::MsgPack.Resource.Id.ResultStackTrace; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::MsgPack.Resource.Id.ResultsFailed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::MsgPack.Resource.Id.ResultsId; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::MsgPack.Resource.Id.ResultsIgnored; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::MsgPack.Resource.Id.ResultsInconclusive; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::MsgPack.Resource.Id.ResultsMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::MsgPack.Resource.Id.ResultsPassed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::MsgPack.Resource.Id.ResultsResult; + global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::MsgPack.Resource.Id.RunTestsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::MsgPack.Resource.Id.TestSuiteListView; + global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::MsgPack.Resource.Layout.options; + global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::MsgPack.Resource.Layout.results; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::MsgPack.Resource.Layout.test_result; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::MsgPack.Resource.Layout.test_suite; + } + + public partial class Attribute + { + + static Attribute() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Attribute() + { + } + } + + public partial class Drawable + { + + // aapt resource value: 0x7f020000 + public const int Icon = 2130837504; + + static Drawable() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Drawable() + { + } + } + + public partial class Id + { + + // aapt resource value: 0x7f050001 + public const int OptionHostName = 2131034113; + + // aapt resource value: 0x7f050002 + public const int OptionPort = 2131034114; + + // aapt resource value: 0x7f050000 + public const int OptionRemoteServer = 2131034112; + + // aapt resource value: 0x7f050010 + public const int OptionsButton = 2131034128; + + // aapt resource value: 0x7f05000b + public const int ResultFullName = 2131034123; + + // aapt resource value: 0x7f05000d + public const int ResultMessage = 2131034125; + + // aapt resource value: 0x7f05000c + public const int ResultResultState = 2131034124; + + // aapt resource value: 0x7f05000a + public const int ResultRunSingleMethodTest = 2131034122; + + // aapt resource value: 0x7f05000e + public const int ResultStackTrace = 2131034126; + + // aapt resource value: 0x7f050006 + public const int ResultsFailed = 2131034118; + + // aapt resource value: 0x7f050003 + public const int ResultsId = 2131034115; + + // aapt resource value: 0x7f050007 + public const int ResultsIgnored = 2131034119; + + // aapt resource value: 0x7f050008 + public const int ResultsInconclusive = 2131034120; + + // aapt resource value: 0x7f050009 + public const int ResultsMessage = 2131034121; + + // aapt resource value: 0x7f050005 + public const int ResultsPassed = 2131034117; + + // aapt resource value: 0x7f050004 + public const int ResultsResult = 2131034116; + + // aapt resource value: 0x7f05000f + public const int RunTestsButton = 2131034127; + + // aapt resource value: 0x7f050011 + public const int TestSuiteListView = 2131034129; + + static Id() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Id() + { + } + } + + public partial class Layout + { + + // aapt resource value: 0x7f030000 + public const int options = 2130903040; + + // aapt resource value: 0x7f030001 + public const int results = 2130903041; + + // aapt resource value: 0x7f030002 + public const int test_result = 2130903042; + + // aapt resource value: 0x7f030003 + public const int test_suite = 2130903043; + + static Layout() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Layout() + { + } + } + + public partial class String + { + + // aapt resource value: 0x7f040000 + public const int ApplicationName = 2130968576; + + static String() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private String() + { + } + } + } +} +#pragma warning restore 1591 diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/Entitlements.plist b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/Entitlements.plist new file mode 100644 index 000000000..0c67376eb --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/Entitlements.plist @@ -0,0 +1,5 @@ + + + + + diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/Info.plist b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/Info.plist new file mode 100644 index 000000000..b9e7d0e62 --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/Info.plist @@ -0,0 +1,45 @@ + + + + + CFBundleDisplayName + MsgPack.UnitTest.Timestamp.Xamios + CFBundleIdentifier + org.msgpack.msgpack-cli-xamarin-ios-test-timestamp + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIDeviceFamily + + 1 + 2 + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + MinimumOSVersion + 7.0 + + diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/MsgPack.UnitTest.Timestamp.Xamarin.iOS.csproj b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/MsgPack.UnitTest.Timestamp.Xamarin.iOS.csproj new file mode 100644 index 000000000..3a58b2282 --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/MsgPack.UnitTest.Timestamp.Xamarin.iOS.csproj @@ -0,0 +1,60 @@ + + + + + {afd483ba-392d-437b-8d0c-d053bd15e2ea} + {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + MsgPackUnitTestTimestampXamariniOS + + + + + + + AssertEx.cs + + + CollectionAssertEx.cs + + + LegacyJapaneseCultureInfo.cs + + + Serialization\TimestampSerializationTest.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + TestRandom.cs + + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/linker.xml b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/linker.xml new file mode 100644 index 000000000..2cdc8b7d3 --- /dev/null +++ b/test/MsgPack.UnitTest.Timestamp.Xamarin.iOS/linker.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/.gitignore b/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/.gitignore new file mode 100644 index 000000000..5a32ef924 --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/.gitignore @@ -0,0 +1 @@ +/[Aa]ssets/ diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MakeAssets.ps1 b/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MakeAssets.ps1 new file mode 100644 index 000000000..5e91542ff --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MakeAssets.ps1 @@ -0,0 +1,71 @@ +Remove-Item ./Assets -Force -Recurse + +if (!(Test-Path ./bin/Debug/MsgPack.dll)) +{ + Write-Error "Build MsgPack.UnitTest.Unity.Full.Desktop project with Debug configuration first." + exit 1 +} + +[string[]]$additionalDefines = ("#define AOT", "#define NET35", "#define UNITY_WORKAROUND") +[xml]$csproj = Get-Content ./MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj +foreach($c in $csproj.Project.ItemGroup.Compile) +{ + if ($c.Include -eq $null) + { + continue + } + + if ($c.Link -ne $null) + { + $destination = "Assets/UnitTests/$($c.Link)".Replace("\", "/") + } + else + { + $destination = "Assets/UnitTests/$($c.Include)".Replace("\", "/") + } + + $destinationDirectory = [IO.Path]::GetDirectoryName($destination); + if (!(Test-Path $destinationDirectory)) + { + New-Item $destinationDirectory -ItemType Directory | Out-Null + } + + Copy-Item $c.Include $destination -Force + + if ($destination.EndsWith(".cs")) + { + $code = [IO.File]::ReadAllLines($destination) + [IO.File]::WriteAllLines($destination, "#define UNITY") + [IO.File]::AppendAllLines($destination, $additionalDefines) + + # Change "protected internal" to "protected" because Unity build drop is not "InternalsVisibleTo" target. + if ($destination.Contains("gen35") -or $destination.Contains("AutoMessagePackSerializerTest.Types.cs") -or $destination.Contains("RegressionTests.cs") -or $destination.Contains("SerializationContextTest.cs")) + { + $appender = [IO.File]::AppendText($destination) + + foreach ($line in $code) + { + if ($destination.Contains("gen35")) + { + # Change FILETIME to DateTime because FILETIME in Unity is not supported. + $appender.WriteLine($line.Replace("protected internal", "protected").Replace("System.Runtime.InteropServices.ComTypes.FILETIME", "System.DateTime")) + } + else + { + $appender.WriteLine($line.Replace("protected internal", "protected")) + } + } + + $appender.Flush() + $appender.Dispose() + } + else + { + [IO.File]::AppendAllLines($destination, $code) + } + } +} + +New-Item ./Assets/Dll -ItemType Directory | Out-Null +Copy-Item ./bin/Debug/MsgPack.dll ./Assets/Dll/MsgPack.dll -Force +Copy-Item ./link.xml ./Assets/link.xml -Force diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj b/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj index f98e3d6d1..253381245 100644 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj @@ -17,7 +17,7 @@ full false bin\Debug\ - TRACE;DEBUG;AOT;NETFX_35;UNITY_WORKAROUND;UNITY + TRACE;DEBUG;AOT;NET35;UNITY_WORKAROUND;UNITY;MP_UNITY_DESKTOP prompt 4 @@ -25,7 +25,7 @@ pdbonly true bin\Release\ - TRACE;AOT;NETFX_35;UNITY_WORKAROUND;UNITY2 + TRACE;AOT;NET35;UNITY_WORKAROUND;UNITY;MP_UNITY_DESKTOP prompt 4 @@ -39,377 +39,393 @@ {30581b4a-bca5-4446-b5e7-4f890a3e9514} MsgPack.Unity.Full - - {43b24dc5-16d6-45ef-93f1-b021b785a892} + + {7fa125b4-e377-4d4c-aecb-17b934e3a4b3} + nunit.framework-3.5 + + + {82f93f6e-5c10-4cc7-bc65-ac0b9ca6d39a} nunitlite-3.5 - - Delegates.cs + + src\MsgPack\Tuple`n.cs - - NetFxCompatibilities.cs + + Serialization\AotTest.cs - - Tuple`n.cs + + Augments.cs - - Dummies\System.Threading.Tasks\Task.cs + + BigEndianBinaryTest.cs - - Dummies\System.Threading.Tasks\TaskFactory.cs + + ByteArrayPackerTest.Allocation.cs - - gen\MsgPack_ImageSerializer.cs + + ByteArrayPackerTest.cs - - gen\MsgPack_Serialization_AbstractClassCollectionKnownTypeSerializer.cs + + ByteArrayUnpackerTest.cs - - gen\MsgPack_Serialization_AbstractClassCollectionNoAttributeSerializer.cs + + ByteArrayUnpackerTest.Ext.cs - - gen\MsgPack_Serialization_AbstractClassCollectionRuntimeTypeSerializer.cs + + ByteArrayUnpackerTest.Raw.cs - - gen\MsgPack_Serialization_AbstractClassDictKeyKnownTypeSerializer.cs + + ByteArrayUnpackerTest.Scalar.cs - - gen\MsgPack_Serialization_AbstractClassDictKeyRuntimeTypeSerializer.cs + + CollectionAssertEx.cs - - gen\MsgPack_Serialization_AbstractClassListItemKnownTypeSerializer.cs + + CollectionValidatingByteArrayUnpackerTest.cs - - gen\MsgPack_Serialization_AbstractClassListItemRuntimeTypeSerializer.cs + + CollectionValidatingStreamUnpackerTest.cs - - gen\MsgPack_Serialization_AbstractClassMemberKnownTypeSerializer.cs + + DirectConversionTest.cs - - gen\MsgPack_Serialization_AbstractClassMemberRuntimeTypeSerializer.cs + + DirectConversionTest.Scalar.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + Dummies\System.Threading.Tasks\Task.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObject_Serializer.cs + + Dummies\System.Threading.Tasks\TaskFactory.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs + + EqualsTest.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTime_Serializer.cs + + FastByteArrayUnpackerTest.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs + + FastStreamUnpackerTest.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32_Serializer.cs + + gen35\MsgPack_ImageSerializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_AbstractClassCollectionKnownTypeSerializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Object_Serializer.cs + + gen35\MsgPack_Serialization_AbstractClassCollectionNoAttributeSerializer.cs - - gen\MsgPack_Serialization_AnnotatedClassSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassCollectionRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeGeneratedEnclosureSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassDictKeyKnownTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeGeneratedSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassDictKeyRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassListItemKnownTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeWithDataContractSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassListItemRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeWithDataContractWithOrderSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassMemberKnownTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeWithNonSerializedSerializer.cs + + gen35\MsgPack_Serialization_AbstractClassMemberRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_ComplexTypeWithOneBaseOrderSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_ComplexTypeWithoutAnyAttributeSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - gen\MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_DataMamberClassSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs - - gen\MsgPack_Serialization_DataMemberAttributeNamedPropertyTestTargetSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_DictionaryValueType_2_System_Int32_System_Int32_Serializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs - - gen\MsgPack_Serialization_EnumByNameSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_System_Object_Serializer.cs - - gen\MsgPack_Serialization_EnumByteFlagsSerializer.cs + + gen35\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs - - gen\MsgPack_Serialization_EnumByteSerializer.cs + + gen35\MsgPack_Serialization_AnnotatedClassSerializer.cs - - gen\MsgPack_Serialization_EnumByUnderlyingValueSerializer.cs + + gen35\MsgPack_Serialization_ComplexTypeGeneratedEnclosureSerializer.cs - - gen\MsgPack_Serialization_EnumDefaultSerializer.cs + + gen35\MsgPack_Serialization_ComplexTypeGeneratedSerializer.cs - - gen\MsgPack_Serialization_EnumInt16FlagsSerializer.cs + + gen35\MsgPack_Serialization_ComplexTypeSerializer.cs - - gen\MsgPack_Serialization_EnumInt16Serializer.cs + + gen35\MsgPack_Serialization_ComplexTypeWithDataContractSerializer.cs - - gen\MsgPack_Serialization_EnumInt32FlagsSerializer.cs + + gen35\MsgPack_Serialization_ComplexTypeWithDataContractWithOrderSerializer.cs - - gen\MsgPack_Serialization_EnumInt32Serializer.cs + + gen35\MsgPack_Serialization_ComplexTypeWithNonSerializedSerializer.cs - - gen\MsgPack_Serialization_EnumInt64FlagsSerializer.cs + + gen35\MsgPack_Serialization_ComplexTypeWithOneBaseOrderSerializer.cs - - gen\MsgPack_Serialization_EnumInt64Serializer.cs + + gen35\MsgPack_Serialization_ComplexTypeWithoutAnyAttributeSerializer.cs - - gen\MsgPack_Serialization_EnumMemberObjectSerializer.cs + + gen35\MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs - - gen\MsgPack_Serialization_EnumSByteFlagsSerializer.cs + + gen35\MsgPack_Serialization_DataMamberClassSerializer.cs - - gen\MsgPack_Serialization_EnumSByteSerializer.cs + + gen35\MsgPack_Serialization_DataMemberAttributeNamedPropertyTestTargetSerializer.cs - - gen\MsgPack_Serialization_EnumUInt16FlagsSerializer.cs + + gen35\MsgPack_Serialization_DictionaryValueType_2_System_Int32_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_EnumUInt16Serializer.cs + + gen35\MsgPack_Serialization_EnumByNameSerializer.cs - - gen\MsgPack_Serialization_EnumUInt32FlagsSerializer.cs + + gen35\MsgPack_Serialization_EnumByteFlagsSerializer.cs - - gen\MsgPack_Serialization_EnumUInt32Serializer.cs + + gen35\MsgPack_Serialization_EnumByteSerializer.cs - - gen\MsgPack_Serialization_EnumUInt64FlagsSerializer.cs + + gen35\MsgPack_Serialization_EnumByUnderlyingValueSerializer.cs - - gen\MsgPack_Serialization_EnumUInt64Serializer.cs + + gen35\MsgPack_Serialization_EnumDefaultSerializer.cs - - gen\MsgPack_Serialization_HasEnumerableSerializer.cs + + gen35\MsgPack_Serialization_EnumInt16FlagsSerializer.cs - - gen\MsgPack_Serialization_InnerSerializer.cs + + gen35\MsgPack_Serialization_EnumInt16Serializer.cs - - gen\MsgPack_Serialization_InterfaceCollectionKnownTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumInt32FlagsSerializer.cs - - gen\MsgPack_Serialization_InterfaceCollectionNoAttributeSerializer.cs + + gen35\MsgPack_Serialization_EnumInt32Serializer.cs - - gen\MsgPack_Serialization_InterfaceCollectionRuntimeTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumInt64FlagsSerializer.cs - - gen\MsgPack_Serialization_InterfaceDictKeyKnownTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumInt64Serializer.cs - - gen\MsgPack_Serialization_InterfaceDictKeyRuntimeTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumMemberObjectSerializer.cs - - gen\MsgPack_Serialization_InterfaceListItemKnownTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumSByteFlagsSerializer.cs - - gen\MsgPack_Serialization_InterfaceListItemRuntimeTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumSByteSerializer.cs - - gen\MsgPack_Serialization_InterfaceMemberKnownTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumUInt16FlagsSerializer.cs - - gen\MsgPack_Serialization_InterfaceMemberRuntimeTypeSerializer.cs + + gen35\MsgPack_Serialization_EnumUInt16Serializer.cs - - gen\MsgPack_Serialization_ListValueType_1_System_Int32_Serializer.cs + + gen35\MsgPack_Serialization_EnumUInt32FlagsSerializer.cs - - gen\MsgPack_Serialization_OuterSerializer.cs + + gen35\MsgPack_Serialization_EnumUInt32Serializer.cs - - gen\MsgPack_Serialization_PlainClassSerializer.cs + + gen35\MsgPack_Serialization_EnumUInt64FlagsSerializer.cs - - gen\MsgPack_Serialization_PolymorphicMemberTypeMixedSerializer.cs + + gen35\MsgPack_Serialization_EnumUInt64Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_GenericNonCollectionTypeSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObject_Serializer.cs + + gen35\MsgPack_Serialization_HasEnumerableSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs + + gen35\MsgPack_Serialization_InnerSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTime_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceCollectionKnownTypeSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceCollectionNoAttributeSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceCollectionRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceDictKeyKnownTypeSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Object_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceDictKeyRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceListItemKnownTypeSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObject_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceListItemRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceMemberKnownTypeSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTime_Serializer.cs + + gen35\MsgPack_Serialization_InterfaceMemberRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs + + gen35\MsgPack_Serialization_ListValueType_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32_Serializer.cs + + gen35\MsgPack_Serialization_NonGenericNonCollectionTypeSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_OuterSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Object_Serializer.cs + + gen35\MsgPack_Serialization_PlainClassSerializer.cs - - gen\MsgPack_Serialization_TestValueTypeSerializer.cs + + gen35\MsgPack_Serialization_PolymorphicMemberTypeMixedSerializer.cs - - gen\MsgPack_Serialization_VersioningTestTargetSerializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_WithAbstractInt32CollectionSerializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - gen\MsgPack_Serialization_WithAbstractNonCollectionSerializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_WithAbstractStringCollectionSerializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_System_Int32_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObject_Serializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_System_Object_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_DateTime_Serializer.cs + + gen35\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_Int32_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_System_DateTime_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_Object_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_System_Int32_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObject_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_System_Object_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_DateTime_Serializer.cs + + gen35\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs + + gen35\MsgPack_Serialization_TestValueTypeSerializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_Int32_Serializer.cs + + gen35\MsgPack_Serialization_VersioningTestTargetSerializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs + + gen35\MsgPack_Serialization_WithAbstractInt32CollectionSerializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_Object_Serializer.cs + + gen35\MsgPack_Serialization_WithAbstractNonCollectionSerializer.cs - - gen\System_DayOfWeekSerializer.cs + + gen35\MsgPack_Serialization_WithAbstractStringCollectionSerializer.cs - - Mono\System\AggregateException.cs + + gen35\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObject_Serializer.cs - - Mono\System\Threading\AtomicBoolean.cs + + gen35\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs - - Mono\System\Threading\Barrier.cs + + gen35\System_Collections_Generic_HashSet_1_System_DateTime_Serializer.cs - - Mono\System\Threading\BarrierPostPhaseException.cs + + gen35\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs - - Mono\System\Threading\CountdownEvent.cs + + gen35\System_Collections_Generic_HashSet_1_System_Int32_Serializer.cs - - Mono\System\Threading\ManualResetEventSlim.cs + + gen35\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs - - Mono\System\Threading\SpinWait.cs + + gen35\System_Collections_Generic_HashSet_1_System_Object_Serializer.cs - - Serialization\AotTest.cs + + gen35\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs - - BigEndianBinaryTest.cs + + gen35\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObject_Serializer.cs - - CollectionAssertEx.cs + + gen35\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - DirectConversionTest.cs + + gen35\System_Collections_ObjectModel_Collection_1_System_DateTime_Serializer.cs - - DirectConversionTest.Scalar.cs + + gen35\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs - - EqualsTest.cs + + gen35\System_Collections_ObjectModel_Collection_1_System_Int32_Serializer.cs + + + gen35\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs + + + gen35\System_Collections_ObjectModel_Collection_1_System_Object_Serializer.cs + + + gen35\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs + + + gen35\System_DayOfWeekSerializer.cs GenericExceptionTester.cs @@ -417,12 +433,18 @@ Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -477,18 +499,36 @@ MessageUnpackableTest.cs + + Mono\System\AggregateException.cs + + + Mono\System\Threading\AtomicBoolean.cs + + + Mono\System\Threading\Barrier.cs + + + Mono\System\Threading\BarrierPostPhaseException.cs + + + Mono\System\Threading\CountdownEvent.cs + + + Mono\System\Threading\ManualResetEventSlim.cs + + + Mono\System\Threading\SpinWait.cs + + + PackerFactoryTest.cs + PackerTest.cs - - PackerTest.Miscs.cs - PackerTest.Pack.cs - - PackerTest.Pack.Miscs.cs - PackerTest.PackBinary.cs @@ -576,6 +616,9 @@ Serialization\IVerifiable`1.cs + + Serialization\KeyNameTransformersTest.cs + Serialization\MapGenerationBasedAutoMessagePackSerializerTest.cs @@ -624,15 +667,24 @@ Serialization\SerializationTargets.cs + + Serialization\SerializationTargetTest.cs + Serialization\SimpleCollection`1.cs Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs + + Serialization\TimestampSerializationTest.cs + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs @@ -651,12 +703,54 @@ SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs TestRandom.cs + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + UnpackerTest.cs @@ -678,6 +772,9 @@ UnpackerTest.Skip.Variations.cs + + UnpackerTest.Subtree.cs + UnpackingTest.cs @@ -691,16 +788,12 @@ UnpackingTest.Scalar.cs + - - RoboCopy $(ProjectDir)$(OutDir) $(ProjectDir)\..\MsgPack.UnitTest.Unity.Il2cpp.Full\Assets\Plugins\Dlls\ *.dll /MIR -if %25ERRORLEVEL%25 geq 8 exit 1 -exit 0 - " + Environment.NewLine + baseException.Message; - } - - r.Color.Value = UnityEngine.Color.red; - - if ( isFailure ) - { - summaryReporter.RecordFailure(); - } - else - { - summaryReporter.RecordError(); - } - } - } - - remains--; - - yield return null; - - try - { - instance.TestCleanup(); - } - catch ( Exception ex ) - { - summaryReporter.HandleFatalException( "TestCleanup", ex, resultPrefab, resultVertical ); - summaryReporter.RecordError( remains ); - isCrashed = true; - } - - if ( isCrashed ) - { - yield break; - } - - yield return null; - } // foreach method - - try - { - testClass.FixtureCleanup(); - } - catch ( Exception ex ) - { - summaryReporter.HandleFatalException( "FixtureCleanup", ex, resultPrefab, resultVertical ); - isCrashed = true; - } - - if ( isCrashed ) - { - yield break; - } - - yield return null; - - try - { - CleanUpTestEngine(); - } - catch ( Exception ex ) - { - summaryReporter.HandleFatalException( "CleanupTestEngine", ex, resultPrefab, resultVertical ); - } - - yield return null; - } - } -} - -#endif // !UNITY_METRO && !UNITY_4_5 \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Assets/UnitTests/TestDrivers/UnitTestDriver.cs.meta b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Assets/UnitTests/TestDrivers/UnitTestDriver.cs.meta deleted file mode 100644 index 0fdb61a1d..000000000 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Assets/UnitTests/TestDrivers/UnitTestDriver.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 4158b25c956189046a69a2c25c1f6804 -timeCreated: 1462427285 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Assets/link.xml.meta b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Assets/link.xml.meta deleted file mode 100644 index bbe4947d6..000000000 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Assets/link.xml.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: bc88f8a769be9e14280e8193ea92f041 -timeCreated: 1462546752 -licenseType: Free -TextScriptImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.Plugins.csproj b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.Plugins.csproj index b4a9dc041..660e28921 100644 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.Plugins.csproj +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.Plugins.csproj @@ -16,7 +16,7 @@ GamePlugins:3 iOS:9 - 5.3.5f1 + 5.4.1p1 4 @@ -27,7 +27,7 @@ Temp\UnityVS_obj\Debug\ prompt 4 - DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;WWW_USE_CURL;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING + DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_1;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING false @@ -37,7 +37,7 @@ Temp\UnityVS_obj\Release\ prompt 4 - TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;WWW_USE_CURL;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING + TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_1;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING false @@ -52,17 +52,20 @@ Library\UnityAssemblies\UnityEngine.dll + + Library\UnityAssemblies\UnityEngine.Advertisements.dll + Library\UnityAssemblies\UnityEngine.UI.dll Library\UnityAssemblies\UnityEngine.Networking.dll - - Library\UnityAssemblies\UnityEngine.Networking.dll + + Library\UnityAssemblies\UnityEngine.Analytics.dll - - Library\UnityAssemblies\UnityEngine.UI.dll + + Library\UnityAssemblies\UnityEngine.Purchasing.dll Library\UnityAssemblies\UnityEditor.dll diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.csproj b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.csproj index b6841908b..69a6a8d93 100644 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.csproj +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.csproj @@ -16,7 +16,7 @@ Game:1 iOS:9 - 5.3.5f1 + 5.4.1p1 4 @@ -27,7 +27,7 @@ Temp\UnityVS_obj\Debug\ prompt 4 - DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;WWW_USE_CURL;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING + DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_1;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING false @@ -37,7 +37,7 @@ Temp\UnityVS_obj\Release\ prompt 4 - TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;WWW_USE_CURL;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING + TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_1;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_UNITYWEBREQUEST;ENABLE_TEXTUREID_MAP;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;HAS_NEON_SKINNIG;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;UNITY_IOS;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING false @@ -52,17 +52,20 @@ Library\UnityAssemblies\UnityEngine.dll + + Library\UnityAssemblies\UnityEngine.Advertisements.dll + Library\UnityAssemblies\UnityEngine.UI.dll Library\UnityAssemblies\UnityEngine.Networking.dll - - Library\UnityAssemblies\UnityEngine.Networking.dll + + Library\UnityAssemblies\UnityEngine.Analytics.dll - - Library\UnityAssemblies\UnityEngine.UI.dll + + Library\UnityAssemblies\UnityEngine.Purchasing.dll Library\UnityAssemblies\UnityEditor.dll diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.Editor.csproj b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.Editor.csproj new file mode 100644 index 000000000..0d6d09eb0 --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.Editor.csproj @@ -0,0 +1,391 @@ + + + + Debug + AnyCPU + 10.0.20506 + 2.0 + {DF272883-3409-C2D7-4112-108B9FCC372B} + Library + Assembly-CSharp-Editor + 512 + {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + .NETFramework + v3.5 + Unity Full v3.5 + + Editor:5 + StandaloneWindows64:19 + 2017.1.0f3 + + 4 + + + pdbonly + false + Temp\UnityVS_bin\Debug\ + Temp\UnityVS_obj\Debug\ + prompt + 4 + DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_1_0;UNITY_2017_1;UNITY_2017;PLATFORM_ARCH_64;UNITY_64;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_RUNTIME_NAVMESH_BUILDING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_2_0;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU + false + + + pdbonly + false + Temp\UnityVS_bin\Release\ + Temp\UnityVS_obj\Release\ + prompt + 4 + TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_1_0;UNITY_2017_1;UNITY_2017;PLATFORM_ARCH_64;UNITY_64;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_RUNTIME_NAVMESH_BUILDING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_2_0;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU + false + + + + + + + + + + + + Library\UnityAssemblies\UnityEditor.dll + + + Library\UnityAssemblies\UnityEngine.dll + + + Library\UnityAssemblies\UnityEditor.Advertisements.dll + + + Library\UnityAssemblies\UnityEngine.UI.dll + + + Library\UnityAssemblies\UnityEditor.UI.dll + + + Library\UnityAssemblies\UnityEngine.Networking.dll + + + Library\UnityAssemblies\UnityEditor.Networking.dll + + + Library\UnityAssemblies\UnityEditor.TestRunner.dll + + + Library\UnityAssemblies\UnityEngine.TestRunner.dll + + + Library\UnityAssemblies\nunit.framework.dll + + + Library\UnityAssemblies\UnityEngine.Timeline.dll + + + Library\UnityAssemblies\UnityEditor.Timeline.dll + + + Library\UnityAssemblies\UnityEditor.TreeEditor.dll + + + Library\UnityAssemblies\UnityEngine.Analytics.dll + + + Library\UnityAssemblies\UnityEditor.Analytics.dll + + + Library\UnityAssemblies\UnityEditor.HoloLens.dll + + + Library\UnityAssemblies\UnityEngine.HoloLens.dll + + + Library\UnityAssemblies\UnityEditor.Purchasing.dll + + + Library\UnityAssemblies\UnityEditor.VR.dll + + + Library\UnityAssemblies\UnityEditor.Graphs.dll + + + Library\UnityAssemblies\UnityEditor.Android.Extensions.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.dll + + + Library\UnityAssemblies\UnityEditor.WSA.Extensions.dll + + + Library\UnityAssemblies\UnityEditor.WindowsStandalone.Extensions.dll + + + Library\UnityAssemblies\SyntaxTree.VisualStudio.Unity.Bridge.dll + + + Library\UnityAssemblies\Mono.Cecil.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.Xcode.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.Common.dll + + + Assets\Dll\MsgPack.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.Plugins.csproj b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.Plugins.csproj new file mode 100644 index 000000000..39afe0448 --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.Plugins.csproj @@ -0,0 +1,274 @@ + + + + Debug + AnyCPU + 10.0.20506 + 2.0 + {B0562D43-30A2-5269-EB47-9E358016836E} + Library + Assembly-CSharp-firstpass + 512 + {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + .NETFramework + v3.5 + Unity Subset v3.5 + + GamePlugins:3 + iOS:9 + 2017.1.0f3 + + 4 + + + pdbonly + false + Temp\UnityVS_bin\Debug\ + Temp\UnityVS_obj\Debug\ + prompt + 4 + DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_1_0;UNITY_2017_1;UNITY_2017;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_RUNTIME_NAVMESH_BUILDING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_IOS_NATIVE_CRASH_REPORTING;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;HAS_NEON_SKINNIG;UNITY_GFX_USE_PLATFORM_VSYNC;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_VR;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;PLATFORM_IOS;UNITY_IOS;PLATFORM_IPHONE;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;NET_2_0_SUBSET;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING;UNITY_HAS_GOOGLEVR + false + + + pdbonly + false + Temp\UnityVS_bin\Release\ + Temp\UnityVS_obj\Release\ + prompt + 4 + TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_1_0;UNITY_2017_1;UNITY_2017;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_RUNTIME_NAVMESH_BUILDING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;ENABLE_RUNTIME_GI;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_NETWORK;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_IOS_NATIVE_CRASH_REPORTING;PLAYERCONNECTION_LISTENS_FIXED_PORT;DEBUGGER_LISTENS_FIXED_PORT;PLATFORM_SUPPORTS_ADS_ID;SUPPORT_ENVIRONMENT_VARIABLES;PLATFORM_SUPPORTS_PROFILER;PLATFORM_HAS_NO_SUPPORT_FOR_BUCKET_ALLOCATOR;STRICTCPP_NEW_DELETE_SIGNATURES;HAS_NEON_SKINNIG;UNITY_GFX_USE_PLATFORM_VSYNC;UNITY_INPUT_SIMULATE_EVENTS;PLATFORM_ALWAYS_USES_STDOUT_FOR_LOG;ENABLE_VR;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;PLATFORM_IOS;UNITY_IOS;PLATFORM_IPHONE;UNITY_IPHONE;UNITY_IPHONE_API;SUPPORT_MULTIPLE_DISPLAYS;ENABLE_IL2CPP;NET_2_0_SUBSET;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU;ENABLE_IOS_ON_DEMAND_RESOURCES;ENABLE_IOS_APP_SLICING;UNITY_HAS_GOOGLEVR + false + + + + + + + + + + + + Library\UnityAssemblies\UnityEditor.dll + + + Library\UnityAssemblies\UnityEngine.dll + + + Library\UnityAssemblies\UnityEngine.UI.dll + + + Library\UnityAssemblies\UnityEngine.Networking.dll + + + Library\UnityAssemblies\UnityEngine.TestRunner.dll + + + Library\UnityAssemblies\nunit.framework.dll + + + Library\UnityAssemblies\UnityEngine.Timeline.dll + + + Library\UnityAssemblies\UnityEngine.Analytics.dll + + + Library\UnityAssemblies\UnityEngine.HoloLens.dll + + + Library\UnityAssemblies\Mono.Cecil.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.Xcode.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.Common.dll + + + Assets\Plugins\Dlls\MsgPack.dll + + + Assets\Plugins\Dlls\MsgPack.UnitTest.dll + + + Assets\Plugins\Dlls\nunitlite.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.csproj b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.csproj new file mode 100644 index 000000000..06f83308c --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.csproj @@ -0,0 +1,343 @@ + + + + Debug + AnyCPU + 10.0.20506 + 2.0 + {E33D164C-F307-1A33-5E34-8F3F54F34025} + Library + Assembly-CSharp + 512 + {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + .NETFramework + v3.5 + Unity Full v3.5 + + Game:1 + StandaloneWindows64:19 + 2017.1.0f3 + + 4 + + + pdbonly + false + Temp\UnityVS_bin\Debug\ + Temp\UnityVS_obj\Debug\ + prompt + 4 + DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_1_0;UNITY_2017_1;UNITY_2017;PLATFORM_ARCH_64;UNITY_64;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_RUNTIME_NAVMESH_BUILDING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_2_0;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU + false + + + pdbonly + false + Temp\UnityVS_bin\Release\ + Temp\UnityVS_obj\Release\ + prompt + 4 + TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_1_0;UNITY_2017_1;UNITY_2017;PLATFORM_ARCH_64;UNITY_64;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_RUNTIME_NAVMESH_BUILDING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_2_0;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU + false + + + + + + + + + + + + Library\UnityAssemblies\UnityEditor.dll + + + Library\UnityAssemblies\UnityEngine.dll + + + Library\UnityAssemblies\UnityEngine.UI.dll + + + Library\UnityAssemblies\UnityEngine.Networking.dll + + + Library\UnityAssemblies\UnityEngine.TestRunner.dll + + + Library\UnityAssemblies\nunit.framework.dll + + + Library\UnityAssemblies\UnityEngine.Timeline.dll + + + Library\UnityAssemblies\UnityEngine.Analytics.dll + + + Library\UnityAssemblies\UnityEngine.HoloLens.dll + + + Library\UnityAssemblies\Mono.Cecil.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.Xcode.dll + + + Library\UnityAssemblies\UnityEditor.iOS.Extensions.Common.dll + + + Assets\Dll\MsgPack.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.sln b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.sln index d90d251ed..fcb0d3f9a 100644 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.sln +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/MsgPack.UnitTest.Unity.Il2cpp.Full.sln @@ -1,40 +1,32 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2015 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.Plugins", "MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.Plugins.csproj", "{A4BA5C02-42E9-9B1C-7BDC-CC58474660F4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp", "MsgPack.UnitTest.Unity.Il2cpp.Full.CSharp.csproj", "{0FA766F5-A760-8511-410A-522C3E51B847}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unity.Il2cpp.Full", "MsgPack.UnitTest.Unity.Il2cpp.Full.csproj", "{E33D164C-F307-1A33-5E34-8F3F54F34025}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop", "..\MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop\MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop.csproj", "{46C5B3D9-45E8-46B6-89F7-837D52C6187A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-3.5", "..\NUnitLite\src\framework\nunitlite-3.5.csproj", "{43B24DC5-16D6-45EF-93F1-B021B785A892}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NUnitLiteRunner", "..\NUnitLiteRunner\NUnitLiteRunner.csproj", "{12047296-B817-4C1A-B01B-5E619F72E407}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsgPack.Unity.Full", "..\..\src\MsgPack.Unity.Full\MsgPack.Unity.Full.csproj", "{30581B4A-BCA5-4446-B5E7-4F890A3E9514}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunit.framework-3.5", "..\NUnitLite\NUnitFramework\framework\nunit.framework-3.5.csproj", "{7FA125B4-E377-4D4C-AECB-17B934E3A4B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-3.5", "..\NUnitLite\NUnitFramework\nunitlite\nunitlite-3.5.csproj", "{82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A4BA5C02-42E9-9B1C-7BDC-CC58474660F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A4BA5C02-42E9-9B1C-7BDC-CC58474660F4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A4BA5C02-42E9-9B1C-7BDC-CC58474660F4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A4BA5C02-42E9-9B1C-7BDC-CC58474660F4}.Release|Any CPU.Build.0 = Release|Any CPU - {0FA766F5-A760-8511-410A-522C3E51B847}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0FA766F5-A760-8511-410A-522C3E51B847}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0FA766F5-A760-8511-410A-522C3E51B847}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0FA766F5-A760-8511-410A-522C3E51B847}.Release|Any CPU.Build.0 = Release|Any CPU + {E33D164C-F307-1A33-5E34-8F3F54F34025}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E33D164C-F307-1A33-5E34-8F3F54F34025}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E33D164C-F307-1A33-5E34-8F3F54F34025}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E33D164C-F307-1A33-5E34-8F3F54F34025}.Release|Any CPU.Build.0 = Release|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.Debug|Any CPU.Build.0 = Debug|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.Release|Any CPU.ActiveCfg = Release|Any CPU {46C5B3D9-45E8-46B6-89F7-837D52C6187A}.Release|Any CPU.Build.0 = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Any CPU.Build.0 = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Any CPU.Build.0 = Release|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.Debug|Any CPU.Build.0 = Debug|Any CPU {12047296-B817-4C1A-B01B-5E619F72E407}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -43,6 +35,14 @@ Global {30581B4A-BCA5-4446-B5E7-4F890A3E9514}.Debug|Any CPU.Build.0 = Debug|Any CPU {30581B4A-BCA5-4446-B5E7-4F890A3E9514}.Release|Any CPU.ActiveCfg = Release|Any CPU {30581B4A-BCA5-4446-B5E7-4F890A3E9514}.Release|Any CPU.Build.0 = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3}.Release|Any CPU.Build.0 = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/EditorBuildSettings.asset b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/EditorBuildSettings.asset index 4ddc1e609..bf2ad270c 100644 Binary files a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/EditorBuildSettings.asset and b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/EditorBuildSettings.asset differ diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/GraphicsSettings.asset b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/GraphicsSettings.asset index 4e0de5d9f..83e98c30f 100644 Binary files a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/GraphicsSettings.asset and b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/GraphicsSettings.asset differ diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectSettings.asset b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectSettings.asset index 18064bd0f..8ab2464fa 100644 Binary files a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectSettings.asset and b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectSettings.asset differ diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectVersion.txt b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectVersion.txt index 558807b2a..ca1aa057c 100644 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectVersion.txt +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/ProjectVersion.txt @@ -1,2 +1 @@ -m_EditorVersion: 5.3.5f1 -m_StandardAssetsVersion: 0 +m_EditorVersion: 2017.1.0f3 diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/UnityAdsSettings.asset b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/UnityAdsSettings.asset deleted file mode 100644 index 39abcdf80..000000000 Binary files a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/ProjectSettings/UnityAdsSettings.asset and /dev/null differ diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Readme.md b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Readme.md index e1cbdedf5..43cd38ab2 100644 --- a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Readme.md +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/Readme.md @@ -3,12 +3,48 @@ MessagePack for CLI Unit Test for Unity IL2CPP Overview --- + This directory contains unit test framework for Unity IL2CPP backend. -The idea of the framework borrowed from UniRx, and many codes are based on UniRx unit testing. How to build --- - 1. Open MsgPack.UnitTest.Unity.Il2cpp.Full.sln first (specifically, you need to build MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop project). - 2. Build all. Three dlls (MsgPack.dll, MsgPack.UnitTest.dll, nunitlite.dll) will be copied to Assets/Plugins/Dlls - 3. Open this directory in Unity Editor. \ No newline at end of file +1. Go to `../MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop` directory. +2. Run `msbuild` to build the project. + * Note that Mono must be installed for your *nix environment. + * Note that you must have path to .NET SDKs for your Windows environment (using Visual Studio Developer Command Prompt is easy way if you have it). +3. Run `MakeAssets.ps1` PowerShell script. + +```bat +@rem In Windows +powershell -ExecutionPolicy Unrestricted ./MakeAssets.ps1 +``` + +```shell +# In *nix +pwsh ./MakeAssets.ps1 +``` + +4. Ensure `../MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/Assets` directory and its subtree have been generated. +5. Open this folder with Unity. +6. Import `../MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/Assets/Dll` directory into `Assets` of Unity project with Unity Editor. +7. Import `../MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/Assets/UnitTests` directory into `Assets` of Unity project with Unity Editor. +8. Import `../MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop/Assets/link.xml` file into `Assets` of Unity project with Unity Editor. + +How to run +--- + +See [Unity official document](https://docs.unity3d.com/Manual/testing-editortestsrunner.html) for details. + +1. Select [[Window]] > [[Unit Test Runner]] +2. Click [[PlayMode]] tab. + * If you see [[Enable playmode tests]] button, click it and then restart the Unity editor. +3. Ensure one more unit tests are shown in the dialog. +4. Click [[Run all]] to run in the Editor. +5. Open [[Build Settings]] dialog, and select a platform you want to run tests. + * Note that author only tests in iOS (AOT). +6. Click [[Run all in player ({YourSelectedPlatform})]] button to run tests in play-mode. + * If you face an error that the editor cannot find scene file, do following: + 1. Ensure that auto generated scene (its name should be "InitTestScene{RandomNumber}"). + 2. In [[Build Settings]] dialog, click [[Add Open Scenes]] and check *only* above auto generated scene. + 3. Click [[Build and Run]] (or [[Build]] and then run the player built). diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/run-ios-macos.sh b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/run-ios-macos.sh new file mode 100644 index 000000000..4765da8dc --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/run-ios-macos.sh @@ -0,0 +1 @@ +/Applications/Unity/Unity.app/Contents/MacOS/Unity -runTests -batchmode -testPlatform ios -projectPath `pwd` -nographics -testResults `pwd`/result.xml diff --git a/test/MsgPack.UnitTest.Unity.Il2cpp.Full/run-win.cmd b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/run-win.cmd new file mode 100644 index 000000000..8c6dd9869 --- /dev/null +++ b/test/MsgPack.UnitTest.Unity.Il2cpp.Full/run-win.cmd @@ -0,0 +1 @@ +Unity.exe -runTests -batchmode -testPlatform StandaloneWindows64 -projectPath "%CD%" -nographics -testResults "%CD%/result.xml" diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/MsgPack.UnitTest.Unpacker.Xamarin.Android.csproj b/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/MsgPack.UnitTest.Unpacker.Xamarin.Android.csproj new file mode 100644 index 000000000..25094c19b --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/MsgPack.UnitTest.Unpacker.Xamarin.Android.csproj @@ -0,0 +1,100 @@ + + + + {f08ffedd-1158-40d8-acc2-02dd6a5c84a8} + {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + MsgPack.UnitTest.Unpacker.Xamarin.Android + + + + + AssertEx.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + + + CollectionAssertEx.cs + + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs + + + TestRandom.cs + + + UnpackerFactoryTest.cs + + + UnpackerTest.cs + + + UnpackerTest.Ext.cs + + + UnpackerTest.Object.cs + + + UnpackerTest.Raw.cs + + + UnpackerTest.Scalar.cs + + + UnpackerTest.Skip.cs + + + UnpackerTest.Skip.Variations.cs + + + UnpackerTest.Subtree.cs + + + + + + Resources\drawable\Icon.png + + + Resources\values\Strings.xml + Designer + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/Properties/AndroidManifest.xml b/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/Properties/AndroidManifest.xml new file mode 100644 index 000000000..98206364a --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/Properties/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/Resources/Resource.Designer.cs b/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/Resources/Resource.Designer.cs new file mode 100644 index 000000000..a8f80078b --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.Android/Resources/Resource.Designer.cs @@ -0,0 +1,191 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// このコードはツールによって生成されました。 +// ランタイム バージョン:4.0.30319.42000 +// +// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 +// コードが再生成されるときに損失したりします。 +// +//------------------------------------------------------------------------------ + +[assembly: global::Android.Runtime.ResourceDesignerAttribute("MsgPack.Resource", IsApplication=true)] + +namespace MsgPack +{ + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] + public partial class Resource + { + + static Resource() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + public static void UpdateIdValues() + { + global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::MsgPack.Resource.Id.OptionHostName; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::MsgPack.Resource.Id.OptionPort; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::MsgPack.Resource.Id.OptionRemoteServer; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::MsgPack.Resource.Id.OptionsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::MsgPack.Resource.Id.ResultFullName; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::MsgPack.Resource.Id.ResultMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::MsgPack.Resource.Id.ResultResultState; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::MsgPack.Resource.Id.ResultRunSingleMethodTest; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::MsgPack.Resource.Id.ResultStackTrace; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::MsgPack.Resource.Id.ResultsFailed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::MsgPack.Resource.Id.ResultsId; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::MsgPack.Resource.Id.ResultsIgnored; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::MsgPack.Resource.Id.ResultsInconclusive; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::MsgPack.Resource.Id.ResultsMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::MsgPack.Resource.Id.ResultsPassed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::MsgPack.Resource.Id.ResultsResult; + global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::MsgPack.Resource.Id.RunTestsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::MsgPack.Resource.Id.TestSuiteListView; + global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::MsgPack.Resource.Layout.options; + global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::MsgPack.Resource.Layout.results; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::MsgPack.Resource.Layout.test_result; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::MsgPack.Resource.Layout.test_suite; + } + + public partial class Attribute + { + + static Attribute() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Attribute() + { + } + } + + public partial class Drawable + { + + // aapt resource value: 0x7f020000 + public const int Icon = 2130837504; + + static Drawable() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Drawable() + { + } + } + + public partial class Id + { + + // aapt resource value: 0x7f050001 + public const int OptionHostName = 2131034113; + + // aapt resource value: 0x7f050002 + public const int OptionPort = 2131034114; + + // aapt resource value: 0x7f050000 + public const int OptionRemoteServer = 2131034112; + + // aapt resource value: 0x7f050010 + public const int OptionsButton = 2131034128; + + // aapt resource value: 0x7f05000b + public const int ResultFullName = 2131034123; + + // aapt resource value: 0x7f05000d + public const int ResultMessage = 2131034125; + + // aapt resource value: 0x7f05000c + public const int ResultResultState = 2131034124; + + // aapt resource value: 0x7f05000a + public const int ResultRunSingleMethodTest = 2131034122; + + // aapt resource value: 0x7f05000e + public const int ResultStackTrace = 2131034126; + + // aapt resource value: 0x7f050006 + public const int ResultsFailed = 2131034118; + + // aapt resource value: 0x7f050003 + public const int ResultsId = 2131034115; + + // aapt resource value: 0x7f050007 + public const int ResultsIgnored = 2131034119; + + // aapt resource value: 0x7f050008 + public const int ResultsInconclusive = 2131034120; + + // aapt resource value: 0x7f050009 + public const int ResultsMessage = 2131034121; + + // aapt resource value: 0x7f050005 + public const int ResultsPassed = 2131034117; + + // aapt resource value: 0x7f050004 + public const int ResultsResult = 2131034116; + + // aapt resource value: 0x7f05000f + public const int RunTestsButton = 2131034127; + + // aapt resource value: 0x7f050011 + public const int TestSuiteListView = 2131034129; + + static Id() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Id() + { + } + } + + public partial class Layout + { + + // aapt resource value: 0x7f030000 + public const int options = 2130903040; + + // aapt resource value: 0x7f030001 + public const int results = 2130903041; + + // aapt resource value: 0x7f030002 + public const int test_result = 2130903042; + + // aapt resource value: 0x7f030003 + public const int test_suite = 2130903043; + + static Layout() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Layout() + { + } + } + + public partial class String + { + + // aapt resource value: 0x7f040000 + public const int ApplicationName = 2130968576; + + static String() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private String() + { + } + } + } +} +#pragma warning restore 1591 diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/Entitlements.plist b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/Entitlements.plist new file mode 100644 index 000000000..0c67376eb --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/Entitlements.plist @@ -0,0 +1,5 @@ + + + + + diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/Info.plist b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/Info.plist new file mode 100644 index 000000000..4c42b2781 --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/Info.plist @@ -0,0 +1,45 @@ + + + + + CFBundleDisplayName + MsgPack.UnitTest.Unpacker.Xamios + CFBundleIdentifier + org.msgpack.msgpack-cli-xamarin-ios-test-unpacker + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIDeviceFamily + + 1 + 2 + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + MinimumOSVersion + 7.0 + + diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/MsgPack.UnitTest.Unpacker.Xamarin.iOS.csproj b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/MsgPack.UnitTest.Unpacker.Xamarin.iOS.csproj new file mode 100644 index 000000000..98e3ccf15 --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/MsgPack.UnitTest.Unpacker.Xamarin.iOS.csproj @@ -0,0 +1,93 @@ + + + + + {7F63D9CD-28E2-4E24-BFAA-71DE14078023} + {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + MsgPackUnitTestUnpackerXamariniOS + + + + + + + AssertEx.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + + + CollectionAssertEx.cs + + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs + + + TestRandom.cs + + + UnpackerFactoryTest.cs + + + UnpackerTest.cs + + + UnpackerTest.Ext.cs + + + UnpackerTest.Object.cs + + + UnpackerTest.Raw.cs + + + UnpackerTest.Scalar.cs + + + UnpackerTest.Skip.cs + + + UnpackerTest.Skip.Variations.cs + + + UnpackerTest.Subtree.cs + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/linker.xml b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/linker.xml new file mode 100644 index 000000000..b41b40bfc --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacker.Xamarin.iOS/linker.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/MsgPack.UnitTest.Unpacking.Xamarin.Android.csproj b/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/MsgPack.UnitTest.Unpacking.Xamarin.Android.csproj new file mode 100644 index 000000000..c7b2650e4 --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/MsgPack.UnitTest.Unpacking.Xamarin.Android.csproj @@ -0,0 +1,94 @@ + + + + {436eda6d-0ff9-40e9-bb74-08d0dcdf94aa} + {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + MsgPack.UnitTest.Unpacking.Xamarin.Android + + + + + AssertEx.cs + + + CollectionAssertEx.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + TestRandom.cs + + + UnpackingTest.Combinations.Array.cs + + + UnpackingTest.Combinations.Boolean.cs + + + UnpackingTest.Combinations.Byte.cs + + + UnpackingTest.Combinations.Double.cs + + + UnpackingTest.Combinations.Int16.cs + + + UnpackingTest.Combinations.Int32.cs + + + UnpackingTest.Combinations.Int64.cs + + + UnpackingTest.Combinations.Map.cs + + + UnpackingTest.Combinations.Nil.cs + + + UnpackingTest.Combinations.Raw.cs + + + UnpackingTest.Combinations.SByte.cs + + + UnpackingTest.Combinations.Single.cs + + + UnpackingTest.Combinations.UInt16.cs + + + UnpackingTest.Combinations.UInt32.cs + + + UnpackingTest.Combinations.UInt64.cs + + + UnpackingTest.cs + + + UnpackingTest.Ext.cs + + + UnpackingTest.Raw.cs + + + UnpackingTest.Scalar.cs + + + + + + Resources\drawable\Icon.png + + + Resources\values\Strings.xml + Designer + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/Properties/AndroidManifest.xml b/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/Properties/AndroidManifest.xml new file mode 100644 index 000000000..ee047ca38 --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/Properties/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/Resources/Resource.Designer.cs b/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/Resources/Resource.Designer.cs new file mode 100644 index 000000000..a8f80078b --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.Android/Resources/Resource.Designer.cs @@ -0,0 +1,191 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// このコードはツールによって生成されました。 +// ランタイム バージョン:4.0.30319.42000 +// +// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 +// コードが再生成されるときに損失したりします。 +// +//------------------------------------------------------------------------------ + +[assembly: global::Android.Runtime.ResourceDesignerAttribute("MsgPack.Resource", IsApplication=true)] + +namespace MsgPack +{ + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] + public partial class Resource + { + + static Resource() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + public static void UpdateIdValues() + { + global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::MsgPack.Resource.Id.OptionHostName; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::MsgPack.Resource.Id.OptionPort; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::MsgPack.Resource.Id.OptionRemoteServer; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::MsgPack.Resource.Id.OptionsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::MsgPack.Resource.Id.ResultFullName; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::MsgPack.Resource.Id.ResultMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::MsgPack.Resource.Id.ResultResultState; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::MsgPack.Resource.Id.ResultRunSingleMethodTest; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::MsgPack.Resource.Id.ResultStackTrace; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::MsgPack.Resource.Id.ResultsFailed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::MsgPack.Resource.Id.ResultsId; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::MsgPack.Resource.Id.ResultsIgnored; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::MsgPack.Resource.Id.ResultsInconclusive; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::MsgPack.Resource.Id.ResultsMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::MsgPack.Resource.Id.ResultsPassed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::MsgPack.Resource.Id.ResultsResult; + global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::MsgPack.Resource.Id.RunTestsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::MsgPack.Resource.Id.TestSuiteListView; + global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::MsgPack.Resource.Layout.options; + global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::MsgPack.Resource.Layout.results; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::MsgPack.Resource.Layout.test_result; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::MsgPack.Resource.Layout.test_suite; + } + + public partial class Attribute + { + + static Attribute() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Attribute() + { + } + } + + public partial class Drawable + { + + // aapt resource value: 0x7f020000 + public const int Icon = 2130837504; + + static Drawable() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Drawable() + { + } + } + + public partial class Id + { + + // aapt resource value: 0x7f050001 + public const int OptionHostName = 2131034113; + + // aapt resource value: 0x7f050002 + public const int OptionPort = 2131034114; + + // aapt resource value: 0x7f050000 + public const int OptionRemoteServer = 2131034112; + + // aapt resource value: 0x7f050010 + public const int OptionsButton = 2131034128; + + // aapt resource value: 0x7f05000b + public const int ResultFullName = 2131034123; + + // aapt resource value: 0x7f05000d + public const int ResultMessage = 2131034125; + + // aapt resource value: 0x7f05000c + public const int ResultResultState = 2131034124; + + // aapt resource value: 0x7f05000a + public const int ResultRunSingleMethodTest = 2131034122; + + // aapt resource value: 0x7f05000e + public const int ResultStackTrace = 2131034126; + + // aapt resource value: 0x7f050006 + public const int ResultsFailed = 2131034118; + + // aapt resource value: 0x7f050003 + public const int ResultsId = 2131034115; + + // aapt resource value: 0x7f050007 + public const int ResultsIgnored = 2131034119; + + // aapt resource value: 0x7f050008 + public const int ResultsInconclusive = 2131034120; + + // aapt resource value: 0x7f050009 + public const int ResultsMessage = 2131034121; + + // aapt resource value: 0x7f050005 + public const int ResultsPassed = 2131034117; + + // aapt resource value: 0x7f050004 + public const int ResultsResult = 2131034116; + + // aapt resource value: 0x7f05000f + public const int RunTestsButton = 2131034127; + + // aapt resource value: 0x7f050011 + public const int TestSuiteListView = 2131034129; + + static Id() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Id() + { + } + } + + public partial class Layout + { + + // aapt resource value: 0x7f030000 + public const int options = 2130903040; + + // aapt resource value: 0x7f030001 + public const int results = 2130903041; + + // aapt resource value: 0x7f030002 + public const int test_result = 2130903042; + + // aapt resource value: 0x7f030003 + public const int test_suite = 2130903043; + + static Layout() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Layout() + { + } + } + + public partial class String + { + + // aapt resource value: 0x7f040000 + public const int ApplicationName = 2130968576; + + static String() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private String() + { + } + } + } +} +#pragma warning restore 1591 diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/Entitlements.plist b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/Entitlements.plist new file mode 100644 index 000000000..0c67376eb --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/Entitlements.plist @@ -0,0 +1,5 @@ + + + + + diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/Info.plist b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/Info.plist new file mode 100644 index 000000000..ba24ca1cc --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/Info.plist @@ -0,0 +1,45 @@ + + + + + CFBundleDisplayName + MsgPack.UnitTest.Unpacking.Xamios + CFBundleIdentifier + org.msgpack.msgpack-cli-xamarin-ios-test-unpacking + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIDeviceFamily + + 1 + 2 + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + MinimumOSVersion + 7.0 + + diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/MsgPack.UnitTest.Unpacking.Xamarin.iOS.csproj b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/MsgPack.UnitTest.Unpacking.Xamarin.iOS.csproj new file mode 100644 index 000000000..b0a041a53 --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/MsgPack.UnitTest.Unpacking.Xamarin.iOS.csproj @@ -0,0 +1,87 @@ + + + + + {01607987-6f33-4990-8e1a-eab89ed5c968} + {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + MsgPackUnitTestUnpackingXamariniOS + + + + + + + AssertEx.cs + + + CollectionAssertEx.cs + + + SplittingStream.cs + + + StreamExtensions.cs + + + TestRandom.cs + + + UnpackingTest.Combinations.Array.cs + + + UnpackingTest.Combinations.Boolean.cs + + + UnpackingTest.Combinations.Byte.cs + + + UnpackingTest.Combinations.Double.cs + + + UnpackingTest.Combinations.Int16.cs + + + UnpackingTest.Combinations.Int32.cs + + + UnpackingTest.Combinations.Int64.cs + + + UnpackingTest.Combinations.Map.cs + + + UnpackingTest.Combinations.Nil.cs + + + UnpackingTest.Combinations.Raw.cs + + + UnpackingTest.Combinations.SByte.cs + + + UnpackingTest.Combinations.Single.cs + + + UnpackingTest.Combinations.UInt16.cs + + + UnpackingTest.Combinations.UInt32.cs + + + UnpackingTest.Combinations.UInt64.cs + + + UnpackingTest.cs + + + UnpackingTest.Ext.cs + + + UnpackingTest.Raw.cs + + + UnpackingTest.Scalar.cs + + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/linker.xml b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/linker.xml new file mode 100644 index 000000000..be6ae9132 --- /dev/null +++ b/test/MsgPack.UnitTest.Unpacking.Xamarin.iOS/linker.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/test/MsgPack.UnitTest.Uwp.Aot/MainPage.xaml.cs b/test/MsgPack.UnitTest.Uwp.Aot/MainPage.xaml.cs index 14380df9f..4b051c781 100644 --- a/test/MsgPack.UnitTest.Uwp.Aot/MainPage.xaml.cs +++ b/test/MsgPack.UnitTest.Uwp.Aot/MainPage.xaml.cs @@ -38,9 +38,6 @@ public MainPage() // duplicate the following line with a type from the referenced assembly nunit.AddTestAssembly( typeof( MainPage ).GetTypeInfo().Assembly ); - // Do you want to automatically run tests when the app starts? - nunit.AutoRun = true; - LoadApplication( nunit ); } } diff --git a/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.csproj b/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.csproj index 05f5b698c..5619c491c 100644 --- a/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.csproj +++ b/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.csproj @@ -2,12 +2,8 @@ - Debug - x86 {E4CA9866-6234-49D4-8CDF-1F3A21EFD138} AppContainerExe - Properties - MsgPack MsgPack.UnitTest en-US UAP @@ -18,77 +14,31 @@ {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} MsgPack.UnitTest.Uwp.Aot_TemporaryKey.pfx 14.0 - FF0127D5ED0BF0BD54B400F1AE36CFC269007C27 + 880646284800F8F3356B8C7E3E734562D8BB304F - - true - bin\x86\Debug\ - TRACE;DEBUG;NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;AOT + + + + $(DefineConstants);NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;FEATURE_TAP;AOT ;2008 - full - x86 - false - prompt - true + false + full - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;AOT - true - ;2008 - pdbonly + x86 false - prompt true - true - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full + ARM false - prompt true - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - ARM - false - prompt - true - true - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly + x64 false - prompt true - true @@ -113,6 +63,9 @@ + + linker.xml + gen\_ReadMe.txt @@ -131,12 +84,39 @@ Serialization\AotTest.cs + + AssertEx.cs + BigEndianBinaryTest.cs + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + CollectionAssertEx.cs + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + DirectConversionTest.cs @@ -149,8 +129,11 @@ ExceptionTest.cs - - GenericExceptionTester.cs + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs gen\MsgPack_ImageSerializer.cs @@ -182,30 +165,30 @@ gen\MsgPack_Serialization_AbstractClassMemberRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs gen\MsgPack_Serialization_AddOnlyCollection_1_System_Object_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs + gen\MsgPack_Serialization_AnnotatedClassSerializer.cs @@ -305,6 +288,9 @@ gen\MsgPack_Serialization_EnumUInt64Serializer.cs + + gen\MsgPack_Serialization_GenericNonCollectionTypeSerializer.cs + gen\MsgPack_Serialization_HasEnumerableSerializer.cs @@ -341,6 +327,9 @@ gen\MsgPack_Serialization_ListValueType_1_System_Int32_Serializer.cs + + gen\MsgPack_Serialization_NonGenericNonCollectionTypeSerializer.cs + gen\MsgPack_Serialization_OuterSerializer.cs @@ -1406,54 +1395,54 @@ gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadWritePropertyAsObjectSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\MsgPack_Serialization_SimpleCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs gen\MsgPack_Serialization_SimpleCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs gen\MsgPack_Serialization_SimpleCollection_1_System_Object_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_System_Object_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + gen\MsgPack_Serialization_TestValueTypeSerializer.cs @@ -1472,90 +1461,99 @@ gen\MsgPack_Serialization_WithAbstractStringCollectionSerializer.cs - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\System_Collections_Generic_HashSet_1_System_DateTime_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs gen\System_Collections_Generic_HashSet_1_System_Int32_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs gen\System_Collections_Generic_HashSet_1_System_Object_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_System_DateTime_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_System_Int32_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_System_Object_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTimeArray_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTime_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32Array_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTimeArray_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_ObjectArray_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32Array_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_System_Object_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_System_ObjectArray_Serializer.cs + gen\System_DayOfWeekSerializer.cs + + GenericExceptionTester.cs + Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -1613,18 +1611,15 @@ MessageUnpackableTest.cs + + PackerFactoryTest.cs + PackerTest.cs - - PackerTest.Miscs.cs - PackerTest.Pack.cs - - PackerTest.Pack.Miscs.cs - PackerTest.PackBinary.cs @@ -1715,6 +1710,9 @@ Serialization\IVerifiable`1.cs + + Serialization\KeyNameTransformersTest.cs + Serialization\MapGenerationBasedAutoMessagePackSerializerTest.cs @@ -1772,9 +1770,15 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs + + Serialization\TimestampSerializationTest.cs + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs @@ -1793,12 +1797,54 @@ SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs TestRandom.cs + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + UnpackerTest.cs @@ -1820,6 +1866,9 @@ UnpackerTest.Skip.Variations.cs + + UnpackerTest.Subtree.cs + UnpackingTest.Combinations.Array.cs diff --git a/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.nuget.targets b/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.nuget.targets index fec9a75f8..8fb2a2db4 100644 --- a/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.nuget.targets +++ b/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot.nuget.targets @@ -1,9 +1,18 @@  - - $(UserProfile)\.nuget\packages\ + + True + NuGet + d:\Yusuke\git\msgpack-cli\test\MsgPack.UnitTest.Uwp.Aot\project.lock.json + $(UserProfile)\.nuget\packages\ + C:\Users\Yusuke\.nuget\packages\ + ProjectJson + 4.4.0 - - + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot_TemporaryKey.pfx b/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot_TemporaryKey.pfx index 8212b27cb..d2def697c 100644 Binary files a/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot_TemporaryKey.pfx and b/test/MsgPack.UnitTest.Uwp.Aot/MsgPack.UnitTest.Uwp.Aot_TemporaryKey.pfx differ diff --git a/test/MsgPack.UnitTest.Uwp.Aot/project.json b/test/MsgPack.UnitTest.Uwp.Aot/project.json index a2dcba192..358919ff8 100644 --- a/test/MsgPack.UnitTest.Uwp.Aot/project.json +++ b/test/MsgPack.UnitTest.Uwp.Aot/project.json @@ -1,13 +1,20 @@ { "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0", - "NUnit": "3.2.1", - "nunit.xamarin": "3.0.1", - "System.Collections.NonGeneric": "4.0.0", - "System.Collections.Specialized": "4.0.0", - "System.Data.Common": "4.0.1-rc2-24027", - "System.Numerics.Vectors": "4.1.1-rc2-24027", - "Xamarin.Forms": "2.2.0.31" + "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.3", + "NUnit": "3.6.1", + "nunit.xamarin": "3.6.1", + "System.Collections.NonGeneric": "4.3.0", + "System.Collections.Specialized": "4.3.0", + "System.Data.Common": "4.3.0", + "System.Diagnostics.Contracts": "4.3.0", + "System.Net.NameResolution": "4.3.0", + "System.Net.Primitives": "4.3.0", + "System.Numerics.Vectors": "4.3.0", + "System.Runtime.WindowsRuntime": "4.3.0", + "System.Threading.Overlapped": "4.3.0", + "System.ValueTuple": "4.3.1", + "Microsoft.Win32.Primitives" : "4.3.0", + "Xamarin.Forms": "2.3.3.180" }, "frameworks": { "uap10.0": {} diff --git a/test/MsgPack.UnitTest.Uwp/MainPage.xaml.cs b/test/MsgPack.UnitTest.Uwp/MainPage.xaml.cs index b91cbe7ae..c097cdf9f 100644 --- a/test/MsgPack.UnitTest.Uwp/MainPage.xaml.cs +++ b/test/MsgPack.UnitTest.Uwp/MainPage.xaml.cs @@ -39,9 +39,6 @@ public MainPage() // duplicate the following line with a type from the referenced assembly nunit.AddTestAssembly( typeof( MainPage ).GetTypeInfo().Assembly ); - // Do you want to automatically run tests when the app starts? - nunit.AutoRun = true; - LoadApplication( nunit ); } } diff --git a/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.csproj b/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.csproj index 973d7e28d..58e9423ca 100644 --- a/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.csproj +++ b/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.csproj @@ -2,12 +2,8 @@ - Debug - x86 {0F930636-458B-401F-9EAF-F4F05E93BCC9} AppContainerExe - Properties - MsgPack MsgPack.UnitTest en-US UAP @@ -18,77 +14,35 @@ {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} MsgPack.UnitTest.Uwp_TemporaryKey.pfx 14.0 - 32441F74F534431D36F20CDFE251197D129985A0 + 807856C98966D121CA69C33F7D6475CF03AA8633 - - true - bin\x86\Debug\ - TRACE;DEBUG;NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;CODE_ANALYSIS;CODE_ANALYSIS + + + + + $(DefineConstants);NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;FEATURE_TAP ;2008 + false full - x86 - false - prompt - true - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;NETSTANDARD1_3;CODE_ANALYSIS;CODE_ANALYSIS - true - ;2008 - pdbonly - x86 - false - prompt - true + true - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM + + x86 false - prompt true - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly + ARM false - prompt true - true - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full + x64 false - prompt true - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x64 - false - prompt - true - true - @@ -113,12 +67,39 @@ Serialization\AotTest.cs + + AssertEx.cs + BigEndianBinaryTest.cs + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + CollectionAssertEx.cs + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + DirectConversionTest.cs @@ -131,8 +112,11 @@ ExceptionTest.cs - - GenericExceptionTester.cs + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs gen\MsgPack_ImageSerializer.cs @@ -164,30 +148,30 @@ gen\MsgPack_Serialization_AbstractClassMemberRuntimeTypeSerializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs gen\MsgPack_Serialization_AddOnlyCollection_1_System_Object_Serializer.cs + + gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs + gen\MsgPack_Serialization_AnnotatedClassSerializer.cs @@ -287,6 +271,9 @@ gen\MsgPack_Serialization_EnumUInt64Serializer.cs + + gen\MsgPack_Serialization_GenericNonCollectionTypeSerializer.cs + gen\MsgPack_Serialization_HasEnumerableSerializer.cs @@ -323,6 +310,9 @@ gen\MsgPack_Serialization_ListValueType_1_System_Int32_Serializer.cs + + gen\MsgPack_Serialization_NonGenericNonCollectionTypeSerializer.cs + gen\MsgPack_Serialization_OuterSerializer.cs @@ -1388,54 +1378,54 @@ gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadWritePropertyAsObjectSerializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\MsgPack_Serialization_SimpleCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs gen\MsgPack_Serialization_SimpleCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs gen\MsgPack_Serialization_SimpleCollection_1_System_Object_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTime_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32_Serializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs gen\MsgPack_Serialization_StringKeyedCollection_1_System_Object_Serializer.cs + + gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + gen\MsgPack_Serialization_TestValueTypeSerializer.cs @@ -1454,90 +1444,99 @@ gen\MsgPack_Serialization_WithAbstractStringCollectionSerializer.cs - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\System_Collections_Generic_HashSet_1_System_DateTime_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs gen\System_Collections_Generic_HashSet_1_System_Int32_Serializer.cs - - gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs gen\System_Collections_Generic_HashSet_1_System_Object_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_System_DateTime_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_System_Int32_Serializer.cs - - gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs gen\System_Collections_ObjectModel_Collection_1_System_Object_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObject_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTimeArray_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTime_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32Array_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTimeArray_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32_Serializer.cs - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_ObjectArray_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32Array_Serializer.cs gen\System_Collections_ObjectModel_ObservableCollection_1_System_Object_Serializer.cs + + gen\System_Collections_ObjectModel_ObservableCollection_1_System_ObjectArray_Serializer.cs + gen\System_DayOfWeekSerializer.cs + + GenericExceptionTester.cs + Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -1595,18 +1594,15 @@ MessageUnpackableTest.cs + + PackerFactoryTest.cs + PackerTest.cs - - PackerTest.Miscs.cs - PackerTest.Pack.cs - - PackerTest.Pack.Miscs.cs - PackerTest.PackBinary.cs @@ -1697,6 +1693,9 @@ Serialization\IVerifiable`1.cs + + Serialization\KeyNameTransformersTest.cs + Serialization\MapGenerationBasedAutoMessagePackSerializerTest.cs @@ -1754,9 +1753,15 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs + + Serialization\TimestampSerializationTest.cs + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs @@ -1775,12 +1780,54 @@ SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs TestRandom.cs + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + UnpackerTest.cs @@ -1802,6 +1849,9 @@ UnpackerTest.Skip.Variations.cs + + UnpackerTest.Subtree.cs + UnpackingTest.Combinations.Array.cs @@ -1873,6 +1923,9 @@ + + linker.xml + gen\_ReadMe.txt @@ -1884,11 +1937,6 @@ - - - ..\..\src\netstandard\1.3\MsgPack\bin\Debug\netstandard1.3\MsgPack.dll - - @@ -1904,6 +1952,12 @@ Designer + + + False + ..\..\src\MsgPack\bin\Debug\netstandard1.3\MsgPack.dll + + 14.0 diff --git a/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.nuget.targets b/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.nuget.targets index fec9a75f8..6a5b85722 100644 --- a/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.nuget.targets +++ b/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp.nuget.targets @@ -1,9 +1,18 @@  - - $(UserProfile)\.nuget\packages\ + + True + NuGet + d:\Yusuke\git\msgpack-cli\test\MsgPack.UnitTest.Uwp\project.lock.json + $(UserProfile)\.nuget\packages\ + C:\Users\Yusuke\.nuget\packages\ + ProjectJson + 4.4.0 - - + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp_TemporaryKey.pfx b/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp_TemporaryKey.pfx index 82e6f7746..d2def697c 100644 Binary files a/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp_TemporaryKey.pfx and b/test/MsgPack.UnitTest.Uwp/MsgPack.UnitTest.Uwp_TemporaryKey.pfx differ diff --git a/test/MsgPack.UnitTest.Uwp/project.json b/test/MsgPack.UnitTest.Uwp/project.json index 39a785e95..358919ff8 100644 --- a/test/MsgPack.UnitTest.Uwp/project.json +++ b/test/MsgPack.UnitTest.Uwp/project.json @@ -1,13 +1,20 @@ { "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0", - "NUnit": "3.2.1", - "nunit.xamarin": "3.0.1", - "System.Collections.NonGeneric": "[4.0.0,]", - "System.Collections.Specialized": "[4.0.0,]", - "System.Data.Common": "4.0.1-rc2-24027", - "System.Numerics.Vectors": "4.1.1-rc2-24027", - "Xamarin.Forms": "2.2.0.31" + "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.3", + "NUnit": "3.6.1", + "nunit.xamarin": "3.6.1", + "System.Collections.NonGeneric": "4.3.0", + "System.Collections.Specialized": "4.3.0", + "System.Data.Common": "4.3.0", + "System.Diagnostics.Contracts": "4.3.0", + "System.Net.NameResolution": "4.3.0", + "System.Net.Primitives": "4.3.0", + "System.Numerics.Vectors": "4.3.0", + "System.Runtime.WindowsRuntime": "4.3.0", + "System.Threading.Overlapped": "4.3.0", + "System.ValueTuple": "4.3.1", + "Microsoft.Win32.Primitives" : "4.3.0", + "Xamarin.Forms": "2.3.3.180" }, "frameworks": { "uap10.0": {} diff --git a/test/MsgPack.UnitTest.WinRT.WindowsPhone/MsgPack.UnitTest.WinRT.WindowsPhone.csproj b/test/MsgPack.UnitTest.WinRT.WindowsPhone/MsgPack.UnitTest.WinRT.WindowsPhone.csproj index 233d60788..07981094b 100644 --- a/test/MsgPack.UnitTest.WinRT.WindowsPhone/MsgPack.UnitTest.WinRT.WindowsPhone.csproj +++ b/test/MsgPack.UnitTest.WinRT.WindowsPhone/MsgPack.UnitTest.WinRT.WindowsPhone.csproj @@ -2,12 +2,9 @@ - Debug x86 {70CB94DD-DA45-47AE-A370-940A094B9F10} Library - Properties - MsgPack MsgPack.UnitTest en-US 8.1 @@ -23,48 +20,26 @@ True true - - true - bin\x86\Debug\ - TRACE;DEBUG;NETFX_CORE;WINDOWS_PHONE_APP;NETSTANDARD1_1;MSTEST + + + + $(DefineConstants);NETFX_CORE;WINDOWS_PHONE_APP;NETSTANDARD1_1;FEATURE_TAP;MSTEST ;2008 + + full - x86 - false - prompt - true - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_PHONE_APP;NETSTANDARD1_1;MSTEST - true - ;2008 + pdbonly - x86 - false - prompt - true - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_PHONE_APP - ;2008 - full - ARM + + x86 false - prompt true - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_PHONE_APP - true - ;2008 - pdbonly + ARM false - prompt true @@ -77,12 +52,42 @@ + + _SetUpFixture.cs + + + AssertEx.cs + BigEndianBinaryTest.cs + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + CollectionAssertEx.cs + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + DirectConversionTest.cs @@ -95,18 +100,30 @@ ExceptionTest.cs + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + GenericExceptionTester.cs Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -164,18 +181,15 @@ MessageUnpackableTest.cs + + PackerFactoryTest.cs + PackerTest.cs - - PackerTest.Miscs.cs - PackerTest.Pack.cs - - PackerTest.Pack.Miscs.cs - PackerTest.PackBinary.cs @@ -194,6 +208,15 @@ PackUnpackTest.Scalar.cs + + Serialization\_SetUpFixture.cs + + + Serialization\MessagePackMemberAndDataMemberMixedTarget.cs + + + Serialization\MessagePackMemberAttributeTest.cs + Serialization\AddOnlyCollection`1.cs @@ -257,18 +280,15 @@ Serialization\IVerifiable`1.cs + + Serialization\KeyNameTransformersTest.cs + Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs Serialization\MapReflectionBasedEnumSerializationTest.cs - - Serialization\MessagePackMemberAndDataMemberMixedTarget.cs - - - Serialization\MessagePackMemberAttributeTest.cs - Serialization\MessagePackSerializerTest.cs @@ -308,9 +328,15 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs + + Serialization\TimestampSerializationTest.cs + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs @@ -326,14 +352,26 @@ Serialization\VersioningTest.cs - - Serialization\_SetUpFixture.cs - SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs TestRandom.cs @@ -341,6 +379,33 @@ TestSuite.cs + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + UnpackerTest.cs @@ -362,6 +427,9 @@ UnpackerTest.Skip.Variations.cs + + UnpackerTest.Subtree.cs + UnpackingTest.Combinations.Array.cs @@ -419,9 +487,6 @@ UnpackingTest.Scalar.cs - - _SetUpFixture.cs - @@ -457,12 +522,12 @@ - + False - ..\..\src\netstandard\1.1\MsgPack\bin\Debug\netstandard1.1\MsgPack.dll + ..\..\src\netstandard\bin\Debug\netstandard1.1\MsgPack.dll - - ..\..\packages\System.Data.Common.4.0.1-rc2-24027\lib\portable-net45+win8+wp8+wpa81\System.Data.Common.dll + + ..\..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll True diff --git a/test/MsgPack.UnitTest.WinRT.WindowsPhone/Properties/AssemblyInfo.cs b/test/MsgPack.UnitTest.WinRT.WindowsPhone/Properties/AssemblyInfo.cs index ff9389aee..b795283d8 100644 --- a/test/MsgPack.UnitTest.WinRT.WindowsPhone/Properties/AssemblyInfo.cs +++ b/test/MsgPack.UnitTest.WinRT.WindowsPhone/Properties/AssemblyInfo.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2015 FUJIWARA, Yusuke +// Copyright (C) 2015-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/test/MsgPack.UnitTest.WinRT.WindowsPhone/packages.config b/test/MsgPack.UnitTest.WinRT.WindowsPhone/packages.config index 28887c09e..7412b3cba 100644 --- a/test/MsgPack.UnitTest.WinRT.WindowsPhone/packages.config +++ b/test/MsgPack.UnitTest.WinRT.WindowsPhone/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT.csproj b/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT.csproj index fd0abefe1..856d1dc81 100644 --- a/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT.csproj +++ b/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT.csproj @@ -2,106 +2,47 @@ - Debug - AnyCPU 8.0.30703 2.0 {EC65EFFC-1D7B-4805-BCCB-3E8FCA99F8E8} Library - Properties - MsgPack MsgPack.UnitTest en-US 512 {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} MsgPack.UnitTest.WinRT_TemporaryKey.pfx - AAEEAD51A53A88AE379ED17BEA6E2B5DD85D956E + DEBDFCC31BC8F851996AD84C394EA999CA3ED9D1 8.1 12 Never - - true - full - false - bin\Debug\ - TRACE;DEBUG;NETFX_CORE;NETSTANDARD1_1;MSTEST - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE;NETFX_CORE;NETSTANDARD1_1;MSTEST - prompt - 4 - - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE + + + + + $(DefineConstants);NETFX_CORE;NETSTANDARD1_1;FEATURE_TAP;MSTEST ;2008 + + full - ARM - false - prompt - true - - bin\ARM\Release\ - TRACE;NETFX_CORE - true - ;2008 + pdbonly - ARM - false - prompt - true - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE - ;2008 - full - x64 + + ARM false - prompt true - - bin\x64\Release\ - TRACE;NETFX_CORE - true - ;2008 - pdbonly + x64 false - prompt true - - true - bin\x86\Debug\ - TRACE;DEBUG;NETFX_CORE;MSTEST - ;2008 - full + x86 false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE - true - ;2008 - pdbonly - x86 - false - prompt true @@ -118,12 +59,42 @@ + + _SetUpFixture.cs + + + AssertEx.cs + BigEndianBinaryTest.cs + + ByteArrayPackerTest.Allocation.cs + + + ByteArrayPackerTest.cs + + + ByteArrayUnpackerTest.cs + + + ByteArrayUnpackerTest.Ext.cs + + + ByteArrayUnpackerTest.Raw.cs + + + ByteArrayUnpackerTest.Scalar.cs + CollectionAssertEx.cs + + CollectionValidatingByteArrayUnpackerTest.cs + + + CollectionValidatingStreamUnpackerTest.cs + DirectConversionTest.cs @@ -136,18 +107,30 @@ ExceptionTest.cs + + FastByteArrayUnpackerTest.cs + + + FastStreamUnpackerTest.cs + GenericExceptionTester.cs Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -205,18 +188,15 @@ MessageUnpackableTest.cs + + PackerFactoryTest.cs + PackerTest.cs - - PackerTest.Miscs.cs - PackerTest.Pack.cs - - PackerTest.Pack.Miscs.cs - PackerTest.PackBinary.cs @@ -235,6 +215,15 @@ PackUnpackTest.Scalar.cs + + Serialization\_SetUpFixture.cs + + + Serialization\MessagePackMemberAndDataMemberMixedTarget.cs + + + Serialization\MessagePackMemberAttributeTest.cs + Serialization\AddOnlyCollection`1.cs @@ -298,18 +287,15 @@ Serialization\IVerifiable`1.cs + + Serialization\KeyNameTransformersTest.cs + Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs Serialization\MapReflectionBasedEnumSerializationTest.cs - - Serialization\MessagePackMemberAndDataMemberMixedTarget.cs - - - Serialization\MessagePackMemberAttributeTest.cs - Serialization\MessagePackSerializerTest.cs @@ -349,9 +335,15 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs + + Serialization\TimestampSerializationTest.cs + Serialization\TypeWithDuplicatedMessagePackMemberAttributeMember.cs @@ -367,14 +359,26 @@ Serialization\VersioningTest.cs - - Serialization\_SetUpFixture.cs - SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs + + + StreamPackerTest.cs + + + StreamUnpackerTest.cs + + + StreamUnpackerTest.Ext.cs + + + StreamUnpackerTest.Raw.cs + + + StreamUnpackerTest.Scalar.cs TestRandom.cs @@ -382,6 +386,33 @@ TestSuite.cs + + TimestampTest.Calculation.cs + + + TimestampTest.Comparison.cs + + + TimestampTest.Conversion.cs + + + TimestampTest.cs + + + TimestampTest.EncodeDecode.cs + + + TimestampTest.Parse.cs + + + TimestampTest.Properties.cs + + + TimestampTest.ToString.cs + + + UnpackerFactoryTest.cs + UnpackerTest.cs @@ -403,6 +434,9 @@ UnpackerTest.Skip.Variations.cs + + UnpackerTest.Subtree.cs + UnpackingTest.Combinations.Array.cs @@ -460,9 +494,6 @@ UnpackingTest.Scalar.cs - - _SetUpFixture.cs - @@ -505,16 +536,16 @@ - + False - ..\..\src\netstandard\1.1\MsgPack\bin\Debug\netstandard1.1\MsgPack.dll + ..\..\src\netstandard\bin\Debug\netstandard1.1\MsgPack.dll - - ..\..\packages\System.Data.Common.4.0.1-rc2-24027\lib\portable-net45+win8+wp8+wpa81\System.Data.Common.dll + + ..\..\packages\System.Numerics.Vectors.4.4.0\lib\portable-net45+win8+wp8+wpa81\System.Numerics.Vectors.dll True - - ..\..\packages\System.Numerics.Vectors.4.1.1-rc2-24027\lib\portable-net45+win8\System.Numerics.Vectors.dll + + ..\..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll True diff --git a/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT_TemporaryKey.pfx b/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT_TemporaryKey.pfx index 8e1afaa5f..d2def697c 100644 Binary files a/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT_TemporaryKey.pfx and b/test/MsgPack.UnitTest.WinRT/MsgPack.UnitTest.WinRT_TemporaryKey.pfx differ diff --git a/test/MsgPack.UnitTest.WinRT/Properties/AssemblyInfo.cs b/test/MsgPack.UnitTest.WinRT/Properties/AssemblyInfo.cs index b6441340d..62f44e852 100644 --- a/test/MsgPack.UnitTest.WinRT/Properties/AssemblyInfo.cs +++ b/test/MsgPack.UnitTest.WinRT/Properties/AssemblyInfo.cs @@ -2,7 +2,7 @@ // // MessagePack for CLI // -// Copyright (C) 2010 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/test/MsgPack.UnitTest.WinRT/packages.config b/test/MsgPack.UnitTest.WinRT/packages.config index 75c0734a0..936dc422d 100644 --- a/test/MsgPack.UnitTest.WinRT/packages.config +++ b/test/MsgPack.UnitTest.WinRT/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Xamarin.Android/MainActivity.cs b/test/MsgPack.UnitTest.Xamarin.Android/MainActivity.cs index 2807d9b67..81787dc3f 100644 --- a/test/MsgPack.UnitTest.Xamarin.Android/MainActivity.cs +++ b/test/MsgPack.UnitTest.Xamarin.Android/MainActivity.cs @@ -1,11 +1,11 @@ -using System.Reflection; +using System.Reflection; using Android.App; using Android.OS; using Xamarin.Android.NUnitLite; namespace MsgPack.UnitTest.Xamarin.Android { - [Activity (Label = "MsgPack.UnitTest.Xamarin.Android", MainLauncher = true)] + [Activity (Label = "MsgPack.UnitTest.Xamarin.Android", MainLauncher = true, Icon = "@drawable/icon" )] public class MainActivity : TestSuiteActivity { protected override void OnCreate (Bundle bundle) diff --git a/test/MsgPack.UnitTest.Xamarin.Android/MsgPack.UnitTest.Xamarin.Android.csproj b/test/MsgPack.UnitTest.Xamarin.Android/MsgPack.UnitTest.Xamarin.Android.csproj index 162cdd615..a7e8ea4cd 100644 --- a/test/MsgPack.UnitTest.Xamarin.Android/MsgPack.UnitTest.Xamarin.Android.csproj +++ b/test/MsgPack.UnitTest.Xamarin.Android/MsgPack.UnitTest.Xamarin.Android.csproj @@ -1,1506 +1,66 @@  - Debug - AnyCPU {5EDECDB4-5179-4441-974F-EC26B4F54528} {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - MsgPack.UnitTest.Xamarin.Android - True - Resources\Resource.designer.cs - Resource - Resources - Assets - False MsgPack.UnitTest.Xamarin.Android - true - ..\..\src\MsgPack.snk - v2.3 - Properties\AndroidManifest.xml - - true - full - false - bin\Debug - DEBUG;__MOBILE__;__ANDROID__;AOT;XAMARIN - prompt - 4 - None - false - 256M - - - full - true - bin\Release - __MOBILE__;__ANDROID__; - prompt - 4 - false - false - - - - - - - - - - - - - - - - - {A6210C9C-1614-46C5-97B2-6A37032AF143} - MsgPack.Xamarin.Android - - - - - MsgPack.snk - - - cases.mpac - - - cases_compact.mpac - - - - - - Serialization\AotTest.cs - - - BigEndianBinaryTest.cs - - - CollectionAssertEx.cs - - - DirectConversionTest.cs - - - DirectConversionTest.Scalar.cs - - - EqualsTest.cs - - - ExceptionTest.cs - - - GenericExceptionTester.cs - - - gen\MsgPack_ImageSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassCollectionKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassCollectionNoAttributeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassCollectionRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassDictKeyKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassDictKeyRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassListItemKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassListItemRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassMemberKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassMemberRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTime_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Object_Serializer.cs - - - gen\MsgPack_Serialization_AnnotatedClassSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeGeneratedEnclosureSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeGeneratedSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithDataContractSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithDataContractWithOrderSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithNonSerializedSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithOneBaseOrderSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithoutAnyAttributeSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs - - - gen\MsgPack_Serialization_DataMamberClassSerializer.cs - - - gen\MsgPack_Serialization_DataMemberAttributeNamedPropertyTestTargetSerializer.cs - - - gen\MsgPack_Serialization_DictionaryValueType_2_System_Int32_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_EnumByNameSerializer.cs - - - gen\MsgPack_Serialization_EnumByteFlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumByteSerializer.cs - - - gen\MsgPack_Serialization_EnumByUnderlyingValueSerializer.cs - - - gen\MsgPack_Serialization_EnumDefaultSerializer.cs - - - gen\MsgPack_Serialization_EnumInt16FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumInt16Serializer.cs - - - gen\MsgPack_Serialization_EnumInt32FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumInt32Serializer.cs - - - gen\MsgPack_Serialization_EnumInt64FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumInt64Serializer.cs - - - gen\MsgPack_Serialization_EnumMemberObjectSerializer.cs - - - gen\MsgPack_Serialization_EnumSByteFlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumSByteSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt16FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt16Serializer.cs - - - gen\MsgPack_Serialization_EnumUInt32FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt32Serializer.cs - - - gen\MsgPack_Serialization_EnumUInt64FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt64Serializer.cs - - - gen\MsgPack_Serialization_HasEnumerableSerializer.cs - - - gen\MsgPack_Serialization_InnerSerializer.cs - - - gen\MsgPack_Serialization_InterfaceCollectionKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceCollectionNoAttributeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceCollectionRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceDictKeyKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceDictKeyRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceListItemKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceListItemRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceMemberKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceMemberRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_ListValueType_1_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_OuterSerializer.cs - - - gen\MsgPack_Serialization_PlainClassSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitivePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferencePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValuePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitivePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferencePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValuePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeMixedSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitivePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferencePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValuePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitivePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferencePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValuePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTime_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32_Serializer.cs + + + + Serialization\AotTest.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs + + AssertEx.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Object_Serializer.cs + + BigEndianBinaryTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + CollectionAssertEx.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObject_Serializer.cs + + DirectConversionTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs + + DirectConversionTest.Scalar.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTime_Serializer.cs + + EqualsTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs + + ExceptionTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32_Serializer.cs + + gen\MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_InnerSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Object_Serializer.cs + + gen\MsgPack_Serialization_OuterSerializer.cs gen\MsgPack_Serialization_TestValueTypeSerializer.cs - - gen\MsgPack_Serialization_TupleAbstractTypeSerializer.cs - - - gen\MsgPack_Serialization_VersioningTestTargetSerializer.cs - - - gen\MsgPack_Serialization_WithAbstractInt32CollectionSerializer.cs - - - gen\MsgPack_Serialization_WithAbstractNonCollectionSerializer.cs - - - gen\MsgPack_Serialization_WithAbstractStringCollectionSerializer.cs - - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_DateTime_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_Int32_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_Object_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_DateTime_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_Int32_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_Object_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTimeArray_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTime_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32Array_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_ObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Object_Serializer.cs - - - gen\System_DayOfWeekSerializer.cs + + GenericExceptionTester.cs Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -1558,57 +118,27 @@ MessageUnpackableTest.cs - - PackerTest.cs - - - PackerTest.Miscs.cs - - - PackerTest.Pack.cs - - - PackerTest.Pack.Miscs.cs - - - PackerTest.PackBinary.cs - - - PackerTest.PackExtendedType.cs - - - PackerTest.PackObject.cs - - - PackerTest.PackT.cs - PackUnpackTest.cs PackUnpackTest.Scalar.cs + + Serialization\ArraySegmentEqualityComparer`1.cs + + + Serialization\PreGeneratedSerializerActivator.cs + + + Serialization\PreGeneratedSerializerActivator.Types.cs + Serialization\AddOnlyCollection`1.cs Serialization\AppendableReadOnlyCollections.cs - - Serialization\ArrayGenerationBasedAutoMessagePackSerializerTest.cs - - - Serialization\ArrayGenerationBasedEnumSerializationTest.cs - - - Serialization\ArrayReflectionBasedAutoMessagePackSerializerTest.cs - - - Serialization\ArrayReflectionBasedEnumSerializationTest.cs - - - Serialization\ArraySegmentEqualityComparer`1.cs - Serialization\AutoMessagePackSerializerTest.Types.cs @@ -1660,17 +190,8 @@ Serialization\IVerifiable`1.cs - - Serialization\MapGenerationBasedAutoMessagePackSerializerTest.cs - - - Serialization\MapGenerationBasedEnumSerializationTest.cs - - - Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs - - - Serialization\MapReflectionBasedEnumSerializationTest.cs + + Serialization\KeyNameTransformersTest.cs Serialization\MessagePackSerializerTest.cs @@ -1690,12 +211,6 @@ Serialization\PerformanceTest.cs - - Serialization\PreGeneratedSerializerActivator.cs - - - Serialization\PreGeneratedSerializerActivator.Types.cs - Serialization\ReflectionBasedNilImplicationTest.cs @@ -1717,6 +232,9 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs @@ -1738,102 +256,18 @@ SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs TestRandom.cs - - UnpackerTest.cs - - - UnpackerTest.Ext.cs - - - UnpackerTest.Object.cs - - - UnpackerTest.Raw.cs - - - UnpackerTest.Scalar.cs - - - UnpackerTest.Skip.cs - - - UnpackerTest.Skip.Variations.cs - - - UnpackingTest.Combinations.Array.cs - - - UnpackingTest.Combinations.Boolean.cs - - - UnpackingTest.Combinations.Byte.cs - - - UnpackingTest.Combinations.Double.cs - - - UnpackingTest.Combinations.Int16.cs - - - UnpackingTest.Combinations.Int32.cs - - - UnpackingTest.Combinations.Int64.cs - - - UnpackingTest.Combinations.Map.cs - - - UnpackingTest.Combinations.Nil.cs - - - UnpackingTest.Combinations.Raw.cs - - - UnpackingTest.Combinations.SByte.cs - - - UnpackingTest.Combinations.Single.cs - - - UnpackingTest.Combinations.UInt16.cs - - - UnpackingTest.Combinations.UInt32.cs - - - UnpackingTest.Combinations.UInt64.cs - - - UnpackingTest.cs - - - UnpackingTest.Ext.cs - - - UnpackingTest.Raw.cs - - - UnpackingTest.Scalar.cs - - - - - - - - cases.json - - - gen\_ReadMe.txt - + + + Designer + + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Xamarin.Android/Resources/Resource.designer.cs b/test/MsgPack.UnitTest.Xamarin.Android/Resources/Resource.designer.cs index e9e22caa4..a8f80078b 100644 --- a/test/MsgPack.UnitTest.Xamarin.Android/Resources/Resource.designer.cs +++ b/test/MsgPack.UnitTest.Xamarin.Android/Resources/Resource.designer.cs @@ -9,9 +9,9 @@ // //------------------------------------------------------------------------------ -[assembly: global::Android.Runtime.ResourceDesignerAttribute("MsgPack.UnitTest.Xamarin.Android.Resource", IsApplication=true)] +[assembly: global::Android.Runtime.ResourceDesignerAttribute("MsgPack.Resource", IsApplication=true)] -namespace MsgPack.UnitTest.Xamarin.Android +namespace MsgPack { @@ -26,28 +26,28 @@ static Resource() public static void UpdateIdValues() { - global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.OptionHostName; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.OptionPort; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.OptionRemoteServer; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.OptionsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultFullName; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultResultState; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultRunSingleMethodTest; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultStackTrace; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsFailed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsId; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsIgnored; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsInconclusive; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsPassed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.ResultsResult; - global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.RunTestsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::MsgPack.UnitTest.Xamarin.Android.Resource.Id.TestSuiteListView; - global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::MsgPack.UnitTest.Xamarin.Android.Resource.Layout.options; - global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::MsgPack.UnitTest.Xamarin.Android.Resource.Layout.results; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::MsgPack.UnitTest.Xamarin.Android.Resource.Layout.test_result; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::MsgPack.UnitTest.Xamarin.Android.Resource.Layout.test_suite; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::MsgPack.Resource.Id.OptionHostName; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::MsgPack.Resource.Id.OptionPort; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::MsgPack.Resource.Id.OptionRemoteServer; + global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::MsgPack.Resource.Id.OptionsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::MsgPack.Resource.Id.ResultFullName; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::MsgPack.Resource.Id.ResultMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::MsgPack.Resource.Id.ResultResultState; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::MsgPack.Resource.Id.ResultRunSingleMethodTest; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::MsgPack.Resource.Id.ResultStackTrace; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::MsgPack.Resource.Id.ResultsFailed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::MsgPack.Resource.Id.ResultsId; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::MsgPack.Resource.Id.ResultsIgnored; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::MsgPack.Resource.Id.ResultsInconclusive; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::MsgPack.Resource.Id.ResultsMessage; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::MsgPack.Resource.Id.ResultsPassed; + global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::MsgPack.Resource.Id.ResultsResult; + global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::MsgPack.Resource.Id.RunTestsButton; + global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::MsgPack.Resource.Id.TestSuiteListView; + global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::MsgPack.Resource.Layout.options; + global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::MsgPack.Resource.Layout.results; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::MsgPack.Resource.Layout.test_result; + global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::MsgPack.Resource.Layout.test_suite; } public partial class Attribute @@ -82,59 +82,59 @@ private Drawable() public partial class Id { - // aapt resource value: 0x7f040001 - public const int OptionHostName = 2130968577; + // aapt resource value: 0x7f050001 + public const int OptionHostName = 2131034113; - // aapt resource value: 0x7f040002 - public const int OptionPort = 2130968578; + // aapt resource value: 0x7f050002 + public const int OptionPort = 2131034114; - // aapt resource value: 0x7f040000 - public const int OptionRemoteServer = 2130968576; + // aapt resource value: 0x7f050000 + public const int OptionRemoteServer = 2131034112; - // aapt resource value: 0x7f040010 - public const int OptionsButton = 2130968592; + // aapt resource value: 0x7f050010 + public const int OptionsButton = 2131034128; - // aapt resource value: 0x7f04000b - public const int ResultFullName = 2130968587; + // aapt resource value: 0x7f05000b + public const int ResultFullName = 2131034123; - // aapt resource value: 0x7f04000d - public const int ResultMessage = 2130968589; + // aapt resource value: 0x7f05000d + public const int ResultMessage = 2131034125; - // aapt resource value: 0x7f04000c - public const int ResultResultState = 2130968588; + // aapt resource value: 0x7f05000c + public const int ResultResultState = 2131034124; - // aapt resource value: 0x7f04000a - public const int ResultRunSingleMethodTest = 2130968586; + // aapt resource value: 0x7f05000a + public const int ResultRunSingleMethodTest = 2131034122; - // aapt resource value: 0x7f04000e - public const int ResultStackTrace = 2130968590; + // aapt resource value: 0x7f05000e + public const int ResultStackTrace = 2131034126; - // aapt resource value: 0x7f040006 - public const int ResultsFailed = 2130968582; + // aapt resource value: 0x7f050006 + public const int ResultsFailed = 2131034118; - // aapt resource value: 0x7f040003 - public const int ResultsId = 2130968579; + // aapt resource value: 0x7f050003 + public const int ResultsId = 2131034115; - // aapt resource value: 0x7f040007 - public const int ResultsIgnored = 2130968583; + // aapt resource value: 0x7f050007 + public const int ResultsIgnored = 2131034119; - // aapt resource value: 0x7f040008 - public const int ResultsInconclusive = 2130968584; + // aapt resource value: 0x7f050008 + public const int ResultsInconclusive = 2131034120; - // aapt resource value: 0x7f040009 - public const int ResultsMessage = 2130968585; + // aapt resource value: 0x7f050009 + public const int ResultsMessage = 2131034121; - // aapt resource value: 0x7f040005 - public const int ResultsPassed = 2130968581; + // aapt resource value: 0x7f050005 + public const int ResultsPassed = 2131034117; - // aapt resource value: 0x7f040004 - public const int ResultsResult = 2130968580; + // aapt resource value: 0x7f050004 + public const int ResultsResult = 2131034116; - // aapt resource value: 0x7f04000f - public const int RunTestsButton = 2130968591; + // aapt resource value: 0x7f05000f + public const int RunTestsButton = 2131034127; - // aapt resource value: 0x7f040011 - public const int TestSuiteListView = 2130968593; + // aapt resource value: 0x7f050011 + public const int TestSuiteListView = 2131034129; static Id() { @@ -170,6 +170,22 @@ private Layout() { } } + + public partial class String + { + + // aapt resource value: 0x7f040000 + public const int ApplicationName = 2130968576; + + static String() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private String() + { + } + } } } #pragma warning restore 1591 diff --git a/test/MsgPack.UnitTest.Xamarin.Android/Resources/values/Strings.xml b/test/MsgPack.UnitTest.Xamarin.Android/Resources/values/Strings.xml new file mode 100644 index 000000000..f1a7b77b1 --- /dev/null +++ b/test/MsgPack.UnitTest.Xamarin.Android/Resources/values/Strings.xml @@ -0,0 +1,4 @@ + + + MsgPack.UnitTest.Xamarin.Android + diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/AppDelegate.cs b/test/MsgPack.UnitTest.Xamarin.iOS/AppDelegate.cs new file mode 100644 index 000000000..7067b9396 --- /dev/null +++ b/test/MsgPack.UnitTest.Xamarin.iOS/AppDelegate.cs @@ -0,0 +1,63 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using Foundation; +using MonoTouch.NUnit.UI; +using MsgPack.Serialization; +using UIKit; + +namespace MsgPack +{ + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register( "AppDelegate" )] + public partial class AppDelegate : UIApplicationDelegate + { + // class-level declarations + UIWindow window; + TouchRunner runner; + + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching( UIApplication app, NSDictionary options ) + { + // create a new window instance based on the screen size + this.window = new UIWindow( UIScreen.MainScreen.Bounds ); + this.runner = new TouchRunner( this.window ); + + // register every tests included in the main application/assembly + this.runner.Add( System.Reflection.Assembly.GetExecutingAssembly() ); + + this.window.RootViewController = new UINavigationController( this.runner.GetViewController() ); + + // make the window visible + this.window.MakeKeyAndVisible(); + + return true; + } + } +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Info.plist b/test/MsgPack.UnitTest.Xamarin.iOS/Info.plist index 5507ccb67..db2f4c795 100644 --- a/test/MsgPack.UnitTest.Xamarin.iOS/Info.plist +++ b/test/MsgPack.UnitTest.Xamarin.iOS/Info.plist @@ -12,8 +12,6 @@ 1.0 LSRequiresIPhoneOS - MinimumOSVersion - 7.0 UIDeviceFamily 1 @@ -36,5 +34,12 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + MinimumOSVersion + 7.0 diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Main.cs b/test/MsgPack.UnitTest.Xamarin.iOS/Main.cs index d271a2e21..f5fd1e83f 100644 --- a/test/MsgPack.UnitTest.Xamarin.iOS/Main.cs +++ b/test/MsgPack.UnitTest.Xamarin.iOS/Main.cs @@ -1,21 +1,17 @@ using System; -using System.Collections.Generic; -using System.Linq; -using MonoTouch.Foundation; -using MonoTouch.UIKit; -using MsgPack.Serialization; +using UIKit; -namespace MsgPack.UnitTest.Xamios +namespace MsgPack { public class Application { // This is the main entry point of the application. static void Main( string[] args ) { - // if you want to use a different Application Delegate class from "UnitTestAppDelegate" + // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main( args, null, "UnitTestAppDelegate" ); + UIApplication.Main( args, null, "AppDelegate" ); } } -} +} \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/MsgPack.UnitTest.Xamarin.iOS.csproj b/test/MsgPack.UnitTest.Xamarin.iOS/MsgPack.UnitTest.Xamarin.iOS.csproj index cc94e7a55..3619a69a6 100644 --- a/test/MsgPack.UnitTest.Xamarin.iOS/MsgPack.UnitTest.Xamarin.iOS.csproj +++ b/test/MsgPack.UnitTest.Xamarin.iOS/MsgPack.UnitTest.Xamarin.iOS.csproj @@ -1,1561 +1,66 @@  + - Debug - iPhoneSimulator {2B75A9C8-F891-4F78-9E27-8B6FE972DE6C} - {6BC8ED88-2882-458C-8E55-DFD12B67127B};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Exe - MsgPack - Resources - true - ..\..\src\MsgPack.snk + {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} MsgPackUnitTestXamariniOS - - true - full - false - bin\iPhoneSimulator\Debug - DEBUG;__MOBILE__;__IOS__;XAMIOS;MONO; - prompt - 4 - false - None - Entitlements.plist - true - MsgPackUnitTestXamariniOS - - ARMv7 - - - true - bin\iPhoneSimulator\Release - __MOBILE__;__IOS__;XAMIOS;MONO; - prompt - 4 - None - false - Entitlements.plist - MsgPackUnitTestXamariniOS - - - true - full - false - bin\iPhone\Debug - DEBUG;__MOBILE__;__IOS__;__MOBILE__;__IOS__;AOT;XAMARIN;MONO; - prompt - 4 - false - Entitlements.plist - iPhone Developer - MsgPackUnitTestXamariniOS - - ARMv7 - 9.3 - SdkOnly - False - False - False - True - False - False - False - False - True - --xml=${ProjectDir}/linker.xml - False - True - Default - HttpClientHandler - False - - - true - bin\iPhone\Release - __MOBILE__;__IOS__;XAMIOS;MONO; - prompt - 4 - Entitlements.plist - false - iPhone Developer - MsgPackUnitTestXamios - - - true - bin\iPhone\Ad-Hoc - __MOBILE__;__IOS__;XAMIOS;MONO; - prompt - 4 - false - Entitlements.plist - true - Automatic:AdHoc - iPhone Distribution - MsgPackUnitTestXamios - - - full - true - bin\iPhone\AppStore - __MOBILE__;__IOS__; - prompt - 4 - false - Entitlements.plist - Automatic:AppStore - iPhone Distribution - MsgPackUnitTestXamios - - - - - - - - - - - - - - - - cases.mpac - - - cases_compact.mpac - - - - - - - BigEndianBinaryTest.cs - - - CollectionAssertEx.cs - - - DirectConversionTest.cs - - - DirectConversionTest.Scalar.cs - - - EqualsTest.cs - - - ExceptionTest.cs - - - GenericExceptionTester.cs - - - gen\MsgPack_ImageSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassCollectionKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassCollectionNoAttributeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassCollectionRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassDictKeyKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassDictKeyRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassListItemKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassListItemRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassMemberKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_AbstractClassMemberRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTimeArray_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_DateTime_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32Array_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_ObjectArray_Serializer.cs - - - gen\MsgPack_Serialization_AddOnlyCollection_1_System_Object_Serializer.cs - - - gen\MsgPack_Serialization_AnnotatedClassSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeGeneratedEnclosureSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeGeneratedSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithDataContractSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithDataContractWithOrderSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithNonSerializedSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithOneBaseOrderSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithoutAnyAttributeSerializer.cs - - - gen\MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs - - - gen\MsgPack_Serialization_DataMamberClassSerializer.cs - - - gen\MsgPack_Serialization_DataMemberAttributeNamedPropertyTestTargetSerializer.cs - - - gen\MsgPack_Serialization_DictionaryValueType_2_System_Int32_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_EnumByNameSerializer.cs - - - gen\MsgPack_Serialization_EnumByteFlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumByteSerializer.cs - - - gen\MsgPack_Serialization_EnumByUnderlyingValueSerializer.cs - - - gen\MsgPack_Serialization_EnumDefaultSerializer.cs - - - gen\MsgPack_Serialization_EnumInt16FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumInt16Serializer.cs - - - gen\MsgPack_Serialization_EnumInt32FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumInt32Serializer.cs - - - gen\MsgPack_Serialization_EnumInt64FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumInt64Serializer.cs - - - gen\MsgPack_Serialization_EnumMemberObjectSerializer.cs - - - gen\MsgPack_Serialization_EnumSByteFlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumSByteSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt16FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt16Serializer.cs - - - gen\MsgPack_Serialization_EnumUInt32FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt32Serializer.cs - - - gen\MsgPack_Serialization_EnumUInt64FlagsSerializer.cs - - - gen\MsgPack_Serialization_EnumUInt64Serializer.cs - - - gen\MsgPack_Serialization_HasEnumerableSerializer.cs - - - gen\MsgPack_Serialization_InnerSerializer.cs - - - gen\MsgPack_Serialization_InterfaceCollectionKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceCollectionNoAttributeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceCollectionRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceDictKeyKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceDictKeyRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceListItemKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceListItemRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceMemberKnownTypeSerializer.cs - - - gen\MsgPack_Serialization_InterfaceMemberRuntimeTypeSerializer.cs - - - gen\MsgPack_Serialization_ListValueType_1_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_OuterSerializer.cs - - - gen\MsgPack_Serialization_PlainClassSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictObjectKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictStaticKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitivePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_PrimitiveReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferencePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ReferenceReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValuePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_ValueReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PolymorphicReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitivePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_PrimitiveReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferencePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ReferenceReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_StringReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1ObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple1StaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValuePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeKnownType_ValueReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeMixedSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictObjectKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictPolymorphicKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Dict_DictStaticKeyAndStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListPolymorphicItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemGetOnlyCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemPrivateSetterCollectionPropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemReadOnlyCollectionFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_List_ListStaticItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitivePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferencePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ReferenceReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_StringReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValuePrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_ValueReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PolymorphicReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitivePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferencePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ReferenceReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringPrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_StringReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItemReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1ObjectItselfReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1PolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple1StaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7FirstPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple7MidPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8AllStaticReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicGetOnlyPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicReadOnlyFieldAndConstructorSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicReadWriteFieldSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Tuple_Tuple8LastPolymorphicReadWritePropertySerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueGetOnlyPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValuePrivateSetterPropertyAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadOnlyFieldAndConstructorAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadWriteFieldAsObjectSerializer.cs - - - gen\MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_ValueReadWritePropertyAsObjectSerializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTimeArray_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_DateTime_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32Array_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_Int32_Serializer.cs - - - gen\MsgPack_Serialization_SimpleCollection_1_System_ObjectArray_Serializer.cs + + + + + + AssertEx.cs - - gen\MsgPack_Serialization_SimpleCollection_1_System_Object_Serializer.cs + + BigEndianBinaryTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs + + CollectionAssertEx.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_MsgPack_MessagePackObject_Serializer.cs + + DirectConversionTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTimeArray_Serializer.cs + + DirectConversionTest.Scalar.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_DateTime_Serializer.cs + + EqualsTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32Array_Serializer.cs + + ExceptionTest.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Int32_Serializer.cs + + gen\MsgPack_Serialization_ComplexTypeWithTwoMemberSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_ObjectArray_Serializer.cs + + gen\MsgPack_Serialization_InnerSerializer.cs - - gen\MsgPack_Serialization_StringKeyedCollection_1_System_Object_Serializer.cs + + gen\MsgPack_Serialization_OuterSerializer.cs gen\MsgPack_Serialization_TestValueTypeSerializer.cs - - gen\MsgPack_Serialization_TupleAbstractTypeSerializer.cs - - - gen\MsgPack_Serialization_VersioningTestTargetSerializer.cs - - - gen\MsgPack_Serialization_WithAbstractInt32CollectionSerializer.cs - - - gen\MsgPack_Serialization_WithAbstractNonCollectionSerializer.cs - - - gen\MsgPack_Serialization_WithAbstractStringCollectionSerializer.cs - - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_DateTimeArray_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_DateTime_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_Int32Array_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_Int32_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_ObjectArray_Serializer.cs - - - gen\System_Collections_Generic_HashSet_1_System_Object_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_DateTimeArray_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_DateTime_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_Int32Array_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_Int32_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_ObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_Collection_1_System_Object_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_MsgPack_MessagePackObject_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTimeArray_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_DateTime_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32Array_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Int32_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_ObjectArray_Serializer.cs - - - gen\System_Collections_ObjectModel_ObservableCollection_1_System_Object_Serializer.cs - - - gen\System_DayOfWeekSerializer.cs + + GenericExceptionTester.cs Image.cs + + LegacyJapaneseCultureInfo.cs + MessagePackConvertTest.cs MessagePackExtendedTypeObjectTest.cs + + MessagePackMemberSkipTest.cs + MessagePackObjectDictionaryTest.cs @@ -1613,57 +118,27 @@ MessageUnpackableTest.cs - - PackerTest.cs - - - PackerTest.Miscs.cs - - - PackerTest.Pack.cs - - - PackerTest.Pack.Miscs.cs - - - PackerTest.PackBinary.cs - - - PackerTest.PackExtendedType.cs - - - PackerTest.PackObject.cs - - - PackerTest.PackT.cs - PackUnpackTest.cs PackUnpackTest.Scalar.cs + + Serialization\ArraySegmentEqualityComparer`1.cs + + + Serialization\PreGeneratedSerializerActivator.cs + + + Serialization\PreGeneratedSerializerActivator.Types.cs + Serialization\AddOnlyCollection`1.cs Serialization\AppendableReadOnlyCollections.cs - - Serialization\ArrayGenerationBasedAutoMessagePackSerializerTest.cs - - - Serialization\ArrayGenerationBasedEnumSerializationTest.cs - - - Serialization\ArrayReflectionBasedAutoMessagePackSerializerTest.cs - - - Serialization\ArrayReflectionBasedEnumSerializationTest.cs - - - Serialization\ArraySegmentEqualityComparer`1.cs - Serialization\AutoMessagePackSerializerTest.Types.cs @@ -1715,17 +190,8 @@ Serialization\IVerifiable`1.cs - - Serialization\MapGenerationBasedAutoMessagePackSerializerTest.cs - - - Serialization\MapGenerationBasedEnumSerializationTest.cs - - - Serialization\MapReflectionBasedAutoMessagePackSerializerTest.cs - - - Serialization\MapReflectionBasedEnumSerializationTest.cs + + Serialization\KeyNameTransformersTest.cs Serialization\MessagePackSerializerTest.cs @@ -1745,12 +211,6 @@ Serialization\PerformanceTest.cs - - Serialization\PreGeneratedSerializerActivator.cs - - - Serialization\PreGeneratedSerializerActivator.Types.cs - Serialization\ReflectionBasedNilImplicationTest.cs @@ -1772,6 +232,9 @@ Serialization\StringKeyedCollection.cs + + Serialization\StructWithDataContractTest.cs + Serialization\TestValueType.cs @@ -1793,110 +256,13 @@ SplittingStream.cs - - SubtreeUnpackerTest.cs + + StreamExtensions.cs TestRandom.cs - - UnpackerTest.cs - - - UnpackerTest.Ext.cs - - - UnpackerTest.Object.cs - - - UnpackerTest.Raw.cs - - - UnpackerTest.Scalar.cs - - - UnpackerTest.Skip.cs - - - UnpackerTest.Skip.Variations.cs - - - UnpackingTest.Combinations.Array.cs - - - UnpackingTest.Combinations.Boolean.cs - - - UnpackingTest.Combinations.Byte.cs - - - UnpackingTest.Combinations.Double.cs - - - UnpackingTest.Combinations.Int16.cs - - - UnpackingTest.Combinations.Int32.cs - - - UnpackingTest.Combinations.Int64.cs - - - UnpackingTest.Combinations.Map.cs - - - UnpackingTest.Combinations.Nil.cs - - - UnpackingTest.Combinations.Raw.cs - - - UnpackingTest.Combinations.SByte.cs - - - UnpackingTest.Combinations.Single.cs - - - UnpackingTest.Combinations.UInt16.cs - - - UnpackingTest.Combinations.UInt32.cs - - - UnpackingTest.Combinations.UInt64.cs - - - UnpackingTest.cs - - - UnpackingTest.Ext.cs - - - UnpackingTest.Raw.cs - - - UnpackingTest.Scalar.cs - - - - - - - - {346B55F0-94FA-4B90-9C11-06031043B685} - MsgPack.Xamarin.iOS - - - - - cases.json - - - - - gen\_ReadMe.txt - - + \ No newline at end of file diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Properties/AssemblyInfo.cs b/test/MsgPack.UnitTest.Xamarin.iOS/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..019616045 --- /dev/null +++ b/test/MsgPack.UnitTest.Xamarin.iOS/Properties/AssemblyInfo.cs @@ -0,0 +1,38 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2018 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Resources; + +[assembly: AssemblyTitle( "Unit test of MessagePack for CLI" )] +[assembly: AssemblyDescription( "Unit test of MessagePack CLI binding for Xamarin for iOS (Xamios)" )] +[assembly: AssemblyConfiguration( "Develop" )] +[assembly: AssemblyProduct( "MessagePack" )] +[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010-2018" )] + +[assembly: ComVisible( false )] +[assembly: CLSCompliant( false )] +[assembly: NeutralResourcesLanguage( "en-US" )] +[assembly: AssemblyVersion( "1.0.0.0" )] +[assembly: AssemblyFileVersion( "0.1.0.0" )] +[assembly: AssemblyInformationalVersion( "0.1" )] diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default-568h@2x.png b/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default-568h@2x.png new file mode 100644 index 000000000..b3f66780c Binary files /dev/null and b/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default-568h@2x.png differ diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default.png b/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default.png new file mode 100644 index 000000000..7ad63b043 Binary files /dev/null and b/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default.png differ diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default@2x.png b/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default@2x.png new file mode 100644 index 000000000..8d59426f3 Binary files /dev/null and b/test/MsgPack.UnitTest.Xamarin.iOS/Resources/Default@2x.png differ diff --git a/test/MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs b/test/MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs index 3067b5522..8f63cc051 100644 --- a/test/MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs +++ b/test/MsgPack.UnitTest.Xamarin.iOS/Serialization/AotTest.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -36,9 +36,16 @@ public class AotTest [TestFixtureSetUp] public static void SetupFixture() { + MessagePackSerializer.PrepareType(); MessagePackSerializer.PrepareCollectionType(); MessagePackSerializer.PrepareCollectionType(); MessagePackSerializer.PrepareCollectionType(); + MessagePackSerializer.PrepareCollectionType(); + MessagePackSerializer.PrepareCollectionType(); + MessagePackSerializer.PrepareCollectionType(); + MessagePackSerializer.PrepareCollectionType(); + MessagePackSerializer.PrepareCollectionType(); + MessagePackSerializer.PrepareCollectionType(); MessagePackSerializer.PrepareDictionaryType(); new ArraySegmentEqualityComparer().Equals( default( ArraySegment ), default( ArraySegment ) ); new ArraySegmentEqualityComparer().Equals( default( ArraySegment ), default( ArraySegment ) ); @@ -121,6 +128,7 @@ private static void TestGenericDefaultSerializerCore( T value, Func + @@ -10,4 +10,6 @@ + + diff --git a/test/MsgPack.UnitTest/AssertEx.cs b/test/MsgPack.UnitTest/AssertEx.cs new file mode 100644 index 000000000..c4812c4d8 --- /dev/null +++ b/test/MsgPack.UnitTest/AssertEx.cs @@ -0,0 +1,43 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using Assert = NUnit.Framework.Assert; +#endif + +namespace MsgPack +{ + internal static class AssertEx + { + public static TException ThrowsAsync( Func assertion ) + where TException : Exception + { +#if MSTEST || XAMARIN + return Assert.Throws( () => assertion().GetAwaiter().GetResult() ); +#else + return Assert.ThrowsAsync( () => assertion() ); +#endif + } + } +} diff --git a/test/MsgPack.UnitTest/Augments.cs b/test/MsgPack.UnitTest/Augments.cs new file mode 100644 index 000000000..350e1bd08 --- /dev/null +++ b/test/MsgPack.UnitTest/Augments.cs @@ -0,0 +1,43 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; + +namespace MsgPack +{ + internal static class Augments + { + public static T[] ToArray( this ArraySegment source ) + { + var result = new T[ source.Count ]; + if ( result.Length > 0 ) + { + Array.Copy( source.Array, source.Offset, result, 0, source.Count ); + } + + return result; + } + + public static long ToUnixTimeSeconds( this DateTimeOffset source ) + { + return source.UtcDateTime.Ticks / TimeSpan.TicksPerSecond - 62135596800; + } + } +} diff --git a/test/MsgPack.UnitTest/ByteArrayPackerTest.Allocation.cs b/test/MsgPack.UnitTest/ByteArrayPackerTest.Allocation.cs new file mode 100644 index 000000000..d13339e88 --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayPackerTest.Allocation.cs @@ -0,0 +1,1049 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TestCaseAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.DataRowAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayPackerTest.Allocation.tt T4Template. + // Do not modify this file. Edit ByteArrayPackerTest.Allocation.tt instead. + + partial class ByteArrayPackerTest + { + private const int DefaultAllocationSize = 65536; + private const int FixedSizeAllocationSize = 8; + private const int CustomAllocationSize = 16; + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_Scalar_TooShortSize( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + Assert.Throws( + () => target.Pack( 0x123456789AL ) + ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_Scalar_EnoughSize( int offset ) + { + var buffer = new byte[ 9 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_Binary_TooShortSize( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + Assert.Throws( + () => target.Pack( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ) + ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_Binary_EnoughSize( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_String_TooShortSize( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + Assert.Throws( + () => target.Pack( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ) + ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_String_EnoughSize( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Default_Scalar_TooShortSize( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Default_Scalar_EnoughSize( int offset ) + { + var buffer = new byte[ 9 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Default_Binary_TooShortSize( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Default_Binary_EnoughSize( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Default_String_TooShortSize( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Default_String_EnoughSize( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Custom_Scalar_TooShortSize( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.True ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Custom_Scalar_EnoughSize( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 9 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.False ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Custom_Binary_TooShortSize( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.True ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Custom_Binary_EnoughSize( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.False ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Custom_String_TooShortSize( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.True ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Custom_String_EnoughSize( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + target.Pack( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.False ); + } + +#if FEATURE_TAP + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_Scalar_TooShortSizeAsync( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + AssertEx.ThrowsAsync( + async () => await target.PackAsync( 0x123456789AL ) + ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Fixed_Scalar_EnoughSizeAsync( int offset ) + { + var buffer = new byte[ 9 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_Binary_TooShortSizeAsync( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + AssertEx.ThrowsAsync( + async () => await target.PackAsync( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ) + ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Fixed_Binary_EnoughSizeAsync( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public void TestSingleAllocation_Fixed_String_TooShortSizeAsync( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + AssertEx.ThrowsAsync( + async () => await target.PackAsync( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ) + ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Fixed_String_EnoughSizeAsync( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, false ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Default_Scalar_TooShortSizeAsync( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Default_Scalar_EnoughSizeAsync( int offset ) + { + var buffer = new byte[ 9 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Default_Binary_TooShortSizeAsync( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Default_Binary_EnoughSizeAsync( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Default_String_TooShortSizeAsync( int offset ) + { + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Default_String_EnoughSizeAsync( int offset ) + { + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, true ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Custom_Scalar_TooShortSizeAsync( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.True ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Custom_Scalar_EnoughSizeAsync( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 9 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( 0x123456789AL ); + var expected = new byte[] { 0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.False ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Custom_Binary_TooShortSizeAsync( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.True ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Custom_Binary_EnoughSizeAsync( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray() ); + var expected = new byte[] { 0xC4, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.False ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Custom_String_TooShortSizeAsync( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 2 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.True ); + } + + [Test] + [TestCase( 0 )] + [TestCase( 1 )] + public async Task TestSingleAllocation_Custom_String_EnoughSizeAsync( int offset ) + { + var allocator = new Allocator(); + var buffer = new byte[ 34 + offset ]; + using ( var target = CreatePacker( buffer, offset, allocator.Reallocate ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + + await target.PackAsync( new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() ) ); + var expected = new byte[] { 0xD9, 0x20, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60 }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); + } + Assert.That( allocator.IsOnlyReallocateCalled(), Is.False ); + } + +#endif // FEATURE_TAP + + } +} diff --git a/test/MsgPack.UnitTest/ByteArrayPackerTest.Allocation.tt b/test/MsgPack.UnitTest/ByteArrayPackerTest.Allocation.tt new file mode 100644 index 000000000..b5eaaed2a --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayPackerTest.Allocation.tt @@ -0,0 +1,238 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly Name="System.Core" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<# + +var patterns = + new [] + { + new { Label = "Fixed", Single = "false", RequiresAllocator = false, CanAllocate = false }, + new { Label = "Default", Single = "true", RequiresAllocator = false, CanAllocate = true }, + new { Label = "FixedSize", Single = default( string ), RequiresAllocator = false, CanAllocate = true }, + new { Label = "Custom", Single = "Reallocate", RequiresAllocator = true, CanAllocate = true }, + }; + +var variations = + new [] + { + new { Label = "Scalar", Size = 9, Input = "0x123456789AL", Output = "0xD3, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x9A" }, + new { Label = "Binary", Size = 34, Input = "Enumerable.Range( 0, 32 ).Select( x => ( byte )x ).ToArray()", Output = "0xC4, 0x20, " + String.Join( ", ", Enumerable.Range( 0, 32 ).Select( x => "0x" + x.ToString( "X2" ) ) ) }, + new { Label = "String", Size = 34, Input = "new string( Enumerable.Range( ( int )'A', 32 ).Select( x => ( char )x ).ToArray() )", Output = "0xD9, 0x20, " + String.Join( ", ", Enumerable.Range( ( int )'A', 32 ).Select( x => "0x" + x.ToString( "X2" ) ) ) }, + }; + +#> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TestCaseAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.DataRowAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayPackerTest.Allocation.tt T4Template. + // Do not modify this file. Edit ByteArrayPackerTest.Allocation.tt instead. + + partial class ByteArrayPackerTest + { + private const int DefaultAllocationSize = 65536; + private const int FixedSizeAllocationSize = 8; + private const int CustomAllocationSize = 16; +<# +foreach ( var isAsync in new [] { false, true } ) +{ + if ( isAsync ) + { +#> + +#if FEATURE_TAP +<# + } + + // single + foreach ( var pattern in patterns ) + { + foreach ( var variation in variations ) + { + this.PutSingleTest( pattern.Label + "_" + variation.Label + "_TooShortSize", pattern.RequiresAllocator, pattern.Single, 2, pattern.CanAllocate ? AllocationResult.Success : AllocationResult.Fail, variation.Input, variation.Output, isAsync, new [] { 0, 1 } ); + + this.PutSingleTest( pattern.Label + "_" + variation.Label + "_EnoughSize", pattern.RequiresAllocator, pattern.Single, variation.Size, AllocationResult.None, variation.Input, variation.Output, isAsync, new [] { 0, 1 } ); + } + } + + if ( isAsync ) + { +#> + +#endif // FEATURE_TAP + +<# + } +} +#> + } +} +<#+ +private void PutSingleTest( string label, bool requiresAllocator, string allocation, int initialSize, AllocationResult allocationResult, string input, string output, bool isAsync, int[] offsets ) +{ + if ( allocation == null ) + { + // No case for this pattern. + return; + } +#> + + [Test] +<#+ + foreach ( var offset in offsets ) + { +#> + [TestCase( <#= offset #> )] +<#+ + } +#> + public <#= AsyncVoid( isAsync, allocationResult ) #> TestSingleAllocation_<#= label #><#= isAsync ? "Async" : String.Empty #>( int offset ) + { +<#+ + string allocationExpression; + + if ( requiresAllocator ) + { +#> + var allocator = new Allocator(); +<#+ + allocationExpression = "allocator." + allocation; + } + else + { + allocationExpression = allocation; + } +#> + var buffer = new byte[ <#= initialSize #> + offset ]; + using ( var target = CreatePacker( buffer, offset, <#= allocationExpression #> ) ) + { + Assert.That( target.InitialBufferOffset, Is.EqualTo( offset ) ); + +<#+ + switch ( allocationResult ) + { + case AllocationResult.None: + case AllocationResult.Success: + { +#> + <#= Pack( "target", isAsync ) #>( <#= input #> ); + var expected = new byte[] { <#= output #> }; + Assert.That( target.BytesUsed, Is.EqualTo( expected.Length ) ); + + var bytes = target.GetResultBytes(); + Assert.That( bytes.Offset, Is.EqualTo( target.InitialBufferOffset ) ); + Assert.That( bytes.Count, Is.EqualTo( target.BytesUsed ) ); +<#+ + if ( allocationResult == AllocationResult.None ) + { +#> + // Returns same array if buffer contains single array and its segment refers entire array. + Assert.That( target.GetResultBytes().Array, Is.SameAs( bytes.Array ) ); + // Returns same array if no allocation has been ocurred. + Assert.That( bytes.Array, Is.SameAs( buffer ) ); + + // Returns same array if no allocation has been ocurred. + Assert.That( target.GetFinalBuffer(), Is.SameAs( buffer ) ); +<#+ + } + else + { +#> + // Returns different array. + Assert.That( bytes.Array, Is.Not.Null ); + Assert.That( bytes.Array, Is.Not.SameAs( buffer ) ); + + Assert.That( target.GetFinalBuffer(), Is.Not.SameAs( buffer ) ); +<#+ + } +#> + + // Only used contents are returned. + Assert.That( bytes.ToArray(), Is.EqualTo( expected ) ); +<#+ + break; + } + default: + { +#> + <#= Throws( isAsync ) #>( + <#= isAsync ? "async " : String.Empty #>() => <#= Pack( "target", isAsync ) #>( <#= input #> ) + ); +<#+ + break; + } + } +#> + } +<#+ + if ( requiresAllocator ) + { +#> + Assert.That( allocator.IsOnly<#= allocation #>Called(), Is.<#= allocationResult == AllocationResult.Success #> ); +<#+ + } +#> + } +<#+ +} + +private static string AsyncVoid( bool isAsync, AllocationResult result ) +{ + return ( isAsync && result != AllocationResult.Fail ) ? "async Task" : "void"; +} + +private static string Pack( string variable, bool isAsync ) +{ + return ( isAsync ? "await " : String.Empty ) + variable + ".Pack" + ( isAsync ? "Async" : String.Empty ); +} + +private static string Throws( bool isAsync ) +{ + return isAsync ? "AssertEx.ThrowsAsync" : "Assert.Throws"; +} + +private enum AllocationResult +{ + None, + Success, + Fail +} +#> \ No newline at end of file diff --git a/test/MsgPack.UnitTest/ByteArrayPackerTest.cs b/test/MsgPack.UnitTest/ByteArrayPackerTest.cs new file mode 100644 index 000000000..9f89d1f81 --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayPackerTest.cs @@ -0,0 +1,104 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + [TestFixture] + [Timeout( 1000 )] + public partial class ByteArrayPackerTest : PackerTest + { + protected override Packer CreatePacker( MemoryStream stream ) + { + Assert.That( stream.Position, Is.EqualTo( 0 ) ); + return Packer.Create( new byte[ 64 * 1024 ] ); + } + + protected override Packer CreatePacker( MemoryStream stream, PackerCompatibilityOptions compatibilityOptions ) + { + Assert.That( stream.Position, Is.EqualTo( 0 ) ); + return Packer.Create( new byte[ 64 * 1024 ], true, compatibilityOptions ); + } + + private static ByteArrayPacker CreatePacker( byte[] buffer, int startOffset, bool allowsBufferExtension ) + { + return Packer.Create( buffer, startOffset, allowsBufferExtension, PackerCompatibilityOptions.None ); + } + + private static ByteArrayPacker CreatePacker( byte[] buffer, int startOffset, Func allocator ) + { + return Packer.Create( buffer, startOffset, allocator, PackerCompatibilityOptions.None ); + } + + protected override byte[] GetResult( Packer packer ) + { + return ( ( ByteArrayPacker )packer ).GetResultBytes().ToArray(); + } + + private sealed class Allocator + { + public int LastAllocationSize { get; private set; } + + public bool IsAllocateCalled { get; set; } + + public bool IsReallocateCalled { get; set; } + + public bool IsOnlyAllocateCalled() + { + return this.IsAllocateCalled && !this.IsReallocateCalled; + } + + public bool IsOnlyReallocateCalled() + { + return !this.IsAllocateCalled && this.IsReallocateCalled; + } + + public ArraySegment Allocate( int size ) + { + this.IsAllocateCalled = true; + int actualSize = Math.Max( size, 16 ); + this.LastAllocationSize = actualSize; + return new ArraySegment( new byte[ actualSize ] ); + } + + public byte[] Reallocate( byte[] old, int size ) + { + this.IsReallocateCalled = true; + int actualSize = old.Length + Math.Max( size, 16 ); + this.LastAllocationSize = actualSize; + var result = new byte[ actualSize ]; + Buffer.BlockCopy( old, 0, result, 0, old.Length ); + return result; + } + } + } +} diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Ext.cs b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Ext.cs new file mode 100644 index 000000000..bd04d2753 --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Ext.cs @@ -0,0 +1,1258 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayUnpackerTest.Ext.tt T4Template. + // Do not modify this file. Edit ByteArrayUnpackerTest.Ext.tt instead. + + partial class ByteArrayUnpackerTest + { + + [Test] + public void TestRead_FixExt1_AndBinaryLengthIs1_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD4, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_FixExt1_AndBinaryLengthIs1_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD4, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixExt2_AndBinaryLengthIs2_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD5, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 2 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_FixExt2_AndBinaryLengthIs2_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD5, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 2 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixExt4_AndBinaryLengthIs4_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD6, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 4 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 4 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_FixExt4_AndBinaryLengthIs4_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD6, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 4 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 4 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixExt8_AndBinaryLengthIs8_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD7, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 8 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 8 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_FixExt8_AndBinaryLengthIs8_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD7, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 8 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 8 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixExt16_AndBinaryLengthIs16_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD8, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 16 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 16 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_FixExt16_AndBinaryLengthIs16_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD8, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 16 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 16 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Ext8_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_Ext8_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Ext8_AndBinaryLengthIs255_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_Ext8_AndBinaryLengthIs255_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Ext16_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_Ext16_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Ext16_AndBinaryLengthIs65535_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0xFF, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_Ext16_AndBinaryLengthIs65535_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0xFF, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Ext32_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 0, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_Ext32_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 0, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Ext32_AndBinaryLengthIs65536_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 1, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 65536 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadExtendedTypeObject_Ext32_AndBinaryLengthIs65536_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 1, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 65536 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + +#if FEATURE_TAP + + [Test] + public async Task TestReadAsync_FixExt1_AndBinaryLengthIs1_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD4, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_FixExt1_AndBinaryLengthIs1_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD4, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_FixExt2_AndBinaryLengthIs2_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD5, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 2 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_FixExt2_AndBinaryLengthIs2_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD5, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 2 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_FixExt4_AndBinaryLengthIs4_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD6, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 4 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 4 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_FixExt4_AndBinaryLengthIs4_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD6, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 4 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 4 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_FixExt8_AndBinaryLengthIs8_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD7, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 8 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 8 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_FixExt8_AndBinaryLengthIs8_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD7, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 8 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 8 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_FixExt16_AndBinaryLengthIs16_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD8, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 16 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 16 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_FixExt16_AndBinaryLengthIs16_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xD8, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 16 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 16 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Ext8_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_Ext8_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Ext8_AndBinaryLengthIs255_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_Ext8_AndBinaryLengthIs255_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC7, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Ext16_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_Ext16_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Ext16_AndBinaryLengthIs65535_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0xFF, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_Ext16_AndBinaryLengthIs65535_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC8, 0xFF, 0xFF, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Ext32_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 0, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_Ext32_AndBinaryLengthIs0_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 0, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Ext32_AndBinaryLengthIs65536_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 1, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( 65536 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadExtendedTypeObjectAsync_Ext32_AndBinaryLengthIs65536_Extra() + { + var typeCode = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { 0xC9, 0, 1, 0, 0, typeCode } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + MessagePackExtendedTypeObject result; + + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result.TypeCode, Is.EqualTo( typeCode ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( 65536 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + +#endif // FEATURE_TAP + + } +} diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Ext.tt b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Ext.tt new file mode 100644 index 000000000..c4233dd07 --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Ext.tt @@ -0,0 +1,263 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly Name="System.Core" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<# + +var fixVariations = + new [] + { + // Label, Headers, Value Length + Tuple.Create( "FixExt1", "0xD4, {0}", 1 ), + Tuple.Create( "FixExt2", "0xD5, {0}", 2 ), + Tuple.Create( "FixExt4", "0xD6, {0}", 4 ), + Tuple.Create( "FixExt8", "0xD7, {0}", 8 ), + Tuple.Create( "FixExt16", "0xD8, {0}", 16 ), + }; + +var variableVariations = + new [] + { + // Label, Header Format, Actual Value Length, Expected Read Length in Limited cases + Tuple.Create( "Ext8", "0xC7, 0, {0}", 0, 2 ), // Will fail to read type code + Tuple.Create( "Ext8", "0xC7, 0xFF, {0}", 0xFF, 3 ), // Will fail to read body + Tuple.Create( "Ext16", "0xC8, 0, 0, {0}", 0, 3 ), // Will fail to read type code + Tuple.Create( "Ext16", "0xC8, 0xFF, 0xFF, {0}", 0xFFFF, 4 ), // Will fail to read body + Tuple.Create( "Ext32", "0xC9, 0, 0, 0, 0, {0}", 0, 5 ), // Will fail to read type code + Tuple.Create( "Ext32", "0xC9, 0, 1, 0, 0, {0}", 0x10000, 6 ), // Will fail to read body + }; + +#> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayUnpackerTest.Ext.tt T4Template. + // Do not modify this file. Edit ByteArrayUnpackerTest.Ext.tt instead. + + partial class ByteArrayUnpackerTest + { +<# +foreach ( var isAsync in new [] { false, true } ) +{ + if ( isAsync ) + { +#> + +#if FEATURE_TAP +<# + } + + foreach ( var testCase in fixVariations ) + { + // Expected read length is fixed header (1byte) + type code (1byte) = 2bytes + PutTest( testCase.Item1, testCase.Item2, 2, testCase.Item3, isAsync ); + } + + foreach ( var testCase in variableVariations ) + { + PutTest( testCase.Item1, testCase.Item2, testCase.Item4, testCase.Item3, isAsync ); + } + + if ( isAsync ) + { +#> + +#endif // FEATURE_TAP + +<# + } +} +#> + } +} +<#+ +private void PutTest( string label, string headerFormat, int expectedLengthInLimit, int actualValueLength, bool isAsync ) +{ + var readDataMethodPrefix = "TestRead" + ( isAsync ? "Async" : String.Empty ) + "_" + label + "_AndBinaryLengthIs" + actualValueLength; + PutTestMethod( readDataMethodPrefix, headerFormat, expectedLengthInLimit, actualValueLength, PutTestUnpackDataBody, isAsync ); + + var readDirectMethodPrefix = "TestReadExtendedTypeObject" + ( isAsync ? "Async" : String.Empty ) + "_" + label + "_AndBinaryLengthIs" + actualValueLength; + PutTestMethod( readDirectMethodPrefix, headerFormat, expectedLengthInLimit, actualValueLength, PutTestUnpackDirectBody, isAsync ); +} + +private void PutTestUnpackDataBody( string typeCodeVariable, int expectedLengthInLimit, int actualValueLength, bool isExtraOrSplit, bool isAsync ) +{ + if ( isExtraOrSplit ) + { + if ( !isAsync ) + { +#> + Assert.IsTrue( unpacker.Read() ); +<#+ + } + else + { +#> + Assert.IsTrue( await unpacker.ReadAsync() ); +<#+ + } +#> + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + var actual = ( MessagePackExtendedTypeObject )result; + Assert.That( actual.TypeCode, Is.EqualTo( <#= typeCodeVariable #> ) ); + Assert.That( actual.Body, Is.Not.Null ); + Assert.That( actual.Body.Length, Is.EqualTo( <#= actualValueLength #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); +<#+ + } + else + { + if ( !isAsync ) + { +#> + Assert.Throws( () => unpacker.Read() ); +<#+ + } + else + { +#> + AssertEx.ThrowsAsync( async () => await unpacker.ReadAsync() ); +<#+ + } +#> + + // Only header and type header are read. + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( <#= expectedLengthInLimit #> ) ); +<#+ + } +} + +private void PutTestUnpackDirectBody( string typeCodeVariable, int expectedLengthInLimit, int actualValueLength, bool isExtraOrSplit, bool isAsync ) +{ + if ( !isAsync || isExtraOrSplit ) + { +#> + MessagePackExtendedTypeObject result; + +<#+ + } + + if ( isExtraOrSplit ) + { + if ( !isAsync ) + { +#> + Assert.IsTrue( unpacker.ReadMessagePackExtendedTypeObject( out result ) ); +<#+ + } + else + { +#> + var ret = await unpacker.ReadMessagePackExtendedTypeObjectAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; +<#+ + } +#> + + Assert.That( result.TypeCode, Is.EqualTo( <#= typeCodeVariable #> ) ); + Assert.That( result.Body, Is.Not.Null ); + Assert.That( result.Body.Length, Is.EqualTo( <#= actualValueLength #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); +<#+ + } + else + { + if ( !isAsync ) + { +#> + Assert.Throws( () => unpacker.ReadMessagePackExtendedTypeObject( out result ) ); +<#+ + } + else + { +#> + AssertEx.ThrowsAsync( async () => await unpacker.ReadMessagePackExtendedTypeObjectAsync() ); +<#+ + } +#> + + // Only header and type header are read. + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( <#= expectedLengthInLimit #> ) ); +<#+ + } +} + +private void PutTestMethod( string methodName, string headerFormat, int expectedLengthInLimit, int actualValueLength, Action putTestBody, bool isAsync ) +{ + var typeCode = "typeCode"; + var headerValue = String.Format( CultureInfo.InvariantCulture, headerFormat, typeCode ); +#> + + [Test] + public <#= AsyncVoid( isAsync ) #> <#= methodName #>_Extra() + { + var <#= typeCode #> = ( byte )( Math.Abs( Environment.TickCount ) % 128 ); + var data = + new byte[] { <#= headerValue #> } + .Concat( Enumerable.Repeat( ( byte )0xFF, <#= actualValueLength #> ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + +<#+ + putTestBody( typeCode, expectedLengthInLimit, actualValueLength, true, isAsync ); +#> + } + } +<#+ +} + +private static string AsyncVoid( bool isAsync ) +{ + return ( isAsync ) ? "async Task" : "void"; +} +#> \ No newline at end of file diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Raw.cs b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Raw.cs new file mode 100644 index 000000000..e72b81f5e --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Raw.cs @@ -0,0 +1,3072 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayUnpackerTest.Raw.tt T4Template. + // Do not modify this file. Edit ByteArrayUnpackerTest.Raw.tt instead. + + partial class ByteArrayUnpackerTest + { + + [Test] + public void TestRead_FixStr_0_AsString_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_FixStr_0_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixStr_31_AsString_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 31 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_FixStr_31_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str8_0_AsString_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Str8_0_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str8_255_AsString_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 255 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Str8_255_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str16_0_AsString_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Str16_0_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str16_65535_AsString_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 65535 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Str16_65535_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str32_0_AsString_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Str32_0_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str32_65536_AsString_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 65536 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Str32_65536_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 65536 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin8_0_AsString_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Bin8_0_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin8_255_AsString_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Bin8_255_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin16_0_AsString_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Bin16_0_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin16_65535_AsString_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Bin16_65535_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin32_0_AsString_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Bin32_0_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin32_65536_AsString_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadString_Bin32_65536_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + Assert.IsTrue( unpacker.ReadString( out result ) ); + + Assert.That( result, Is.EqualTo( new String( 'A', 65536 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixStr_0_AsBinary_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_FixStr_0_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_FixStr_31_AsBinary_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_FixStr_31_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str8_0_AsBinary_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Str8_0_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str8_255_AsBinary_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Str8_255_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str16_0_AsBinary_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Str16_0_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str16_65535_AsBinary_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Str16_65535_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str32_0_AsBinary_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Str32_0_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Str32_65536_AsBinary_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Str32_65536_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin8_0_AsBinary_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Bin8_0_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin8_255_AsBinary_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Bin8_255_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin16_0_AsBinary_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Bin16_0_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin16_65535_AsBinary_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Bin16_65535_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin32_0_AsBinary_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Bin32_0_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Bin32_65536_AsBinary_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBinary_Bin32_65536_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + Assert.IsTrue( unpacker.ReadBinary( out result ) ); + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + +#if FEATURE_TAP + + [Test] + public async Task TestRead_FixStr_0Async_AsString_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_FixStrAsync_0_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_FixStr_31Async_AsString_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 31 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_FixStrAsync_31_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str8_0Async_AsString_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Str8Async_0_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str8_255Async_AsString_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 255 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Str8Async_255_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str16_0Async_AsString_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Str16Async_0_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str16_65535Async_AsString_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 65535 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Str16Async_65535_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str32_0Async_AsString_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 0 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Str32Async_0_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str32_65536Async_AsString_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( String )result.Value, Is.EqualTo( new String( 'A', 65536 ) ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( String ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Str32Async_65536_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 65536 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin8_0Async_AsString_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Bin8Async_0_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin8_255Async_AsString_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Bin8Async_255_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin16_0Async_AsString_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Bin16Async_0_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin16_65535Async_AsString_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Bin16Async_65535_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin32_0Async_AsString_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Bin32Async_0_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin32_65536Async_AsString_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadString_Bin32Async_65536_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + String result; + + var ret = await unpacker.ReadStringAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( new String( 'A', 65536 ) ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_FixStr_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_FixStrAsync_0_Extra() + { + var data = + new byte[] { 0xA0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_FixStr_31Async_AsBinary_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_FixStrAsync_31_Extra() + { + var data = + new byte[] { 0xBF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str8_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Str8Async_0_Extra() + { + var data = + new byte[] { 0xD9, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str8_255Async_AsBinary_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Str8Async_255_Extra() + { + var data = + new byte[] { 0xD9, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str16_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Str16Async_0_Extra() + { + var data = + new byte[] { 0xDA, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str16_65535Async_AsBinary_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Str16Async_65535_Extra() + { + var data = + new byte[] { 0xDA, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str32_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + var asString = ( String )result.Value; + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Str32Async_0_Extra() + { + var data = + new byte[] { 0xDB, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Str32_65536Async_AsBinary_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Str32Async_65536_Extra() + { + var data = + new byte[] { 0xDB, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin8_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Bin8Async_0_Extra() + { + var data = + new byte[] { 0xC4, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin8_255Async_AsBinary_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Bin8Async_255_Extra() + { + var data = + new byte[] { 0xC4, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin16_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Bin16Async_0_Extra() + { + var data = + new byte[] { 0xC5, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin16_65535Async_AsBinary_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Bin16Async_65535_Extra() + { + var data = + new byte[] { 0xC5, 0xFF, 0xFF } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin32_0Async_AsBinary_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Bin32Async_0_Extra() + { + var data = + new byte[] { 0xC6, 0, 0, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestRead_Bin32_65536Async_AsBinary_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + + Assert.That( ( Byte[] )result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( Byte[] ) ) ); + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + + Assert.Throws( () => { var asString = ( String )result.Value; } ); + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBinary_Bin32Async_65536_Extra() + { + var data = + new byte[] { 0xC6, 0, 1, 0, 0 } + .Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte[] result; + + var ret = await unpacker.ReadBinaryAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + + Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + +#endif // FEATURE_TAP + + } +} diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Raw.tt b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Raw.tt new file mode 100644 index 000000000..47686902c --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Raw.tt @@ -0,0 +1,309 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly Name="System.Core" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.Linq" #> +<# + +var testSituations = + new [] + { + // Suffix, Value Type, Unit Value Expression, Expected Value Expression Format, is str + Tuple.Create( "String", "String", "'A'", "new String( {0}, {1} )", true ), + Tuple.Create( "Binary", "Byte[]", "0xFF", "Enumerable.Repeat( {0}, {1} ).ToArray()", false ) + }; +var strVariations = + new [] + { + // Label, Length, Header Bytes, Header Type, Expected Read Length in Limited cases + Tuple.Create( "FixStr", 0, "0xA0", "String", 0 ), // Will fail to read entire header + Tuple.Create( "FixStr", 0x1F, "0xBF", "String", 1 ), // Will fail to read body + Tuple.Create( "Str8", 0, "0xD9, 0", "String", 1 ), // Will fail to read length + Tuple.Create( "Str8", 0xFF, "0xD9, 0xFF", "String", 2 ), // Will fail to read body + Tuple.Create( "Str16", 0, "0xDA, 0, 0", "String", 1 ), // Will fail to read length + Tuple.Create( "Str16", 0xFFFF, "0xDA, 0xFF, 0xFF", "String", 3 ), // Will fail to read body + Tuple.Create( "Str32", 0, "0xDB, 0, 0, 0, 0", "String", 1 ), // Will fail to read length + Tuple.Create( "Str32", 0x10000, "0xDB, 0, 1, 0, 0", "String", 5 ), // Will fail to read body + }; + +var binVariations = + new [] + { + // Label, Length, Header Bytes, Expected Read Length in Limited cases + Tuple.Create( "Bin8", 0, "0xC4, 0", "Byte[]", 1 ), // Will fail to read length + Tuple.Create( "Bin8", 0xFF, "0xC4, 0xFF", "Byte[]", 2 ), // Will fail to read body + Tuple.Create( "Bin16", 0, "0xC5, 0, 0", "Byte[]", 1 ), // Will fail to read length + Tuple.Create( "Bin16", 0xFFFF, "0xC5, 0xFF, 0xFF", "Byte[]", 3 ), // Will fail to read body + Tuple.Create( "Bin32", 0, "0xC6, 0, 0, 0, 0", "Byte[]", 1 ), // Will fail to read length + Tuple.Create( "Bin32", 0x10000, "0xC6, 0, 1, 0, 0", "Byte[]", 5 ), // Will fail to read body + }; + +#> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayUnpackerTest.Raw.tt T4Template. + // Do not modify this file. Edit ByteArrayUnpackerTest.Raw.tt instead. + + partial class ByteArrayUnpackerTest + { +<# +foreach( var isAsync in new [] { false, true } ) +{ + if ( isAsync ) + { +#> + +#if FEATURE_TAP +<# + } + + foreach( var testSituation in testSituations ) + { + foreach( var testCase in strVariations ) + { + PutTest( testSituation, testCase, testSituation.Item5 || testCase.Item2 == 0, isAsync ); + } + + // can be bin stream. + foreach( var testCase in binVariations ) + { + PutTest( testSituation, testCase, false, isAsync ); + } + } + + if ( isAsync ) + { +#> + +#endif // FEATURE_TAP + +<# + } +} +#> + } +} +<#+ +private void PutTest( Tuple testSituation, Tuple testCase, bool canConvertToString, bool isAsync ) +{ + // FIXME: too short data, too long data + var readDataMethodPrefix = "TestRead_" + testCase.Item1 + "_" + testCase.Item2 + ( isAsync ? "Async" : String.Empty ) + "_As" + testSituation.Item1; + PutTestMethod( readDataMethodPrefix, testSituation, testCase, canConvertToString, PutTestUnpackDataBody, isAsync ); + + var readDirectMethodPrefix = "TestRead" + testSituation.Item1 + "_" + testCase.Item1 + ( isAsync ? "Async" : String.Empty ) + "_" + testCase.Item2; + PutTestMethod( readDirectMethodPrefix, testSituation, testCase, canConvertToString, PutTestUnpackDirectBody, isAsync ); +} + +private void PutTestUnpackDataBody( Tuple testSituation, string sourceType, string expectedValue, bool canConvertToString, bool isExtraOrSplit, int expectedReadLength, bool isAsync ) +{ + if ( isExtraOrSplit ) + { + if ( !isAsync ) + { +#> + Assert.IsTrue( unpacker.Read() ); +<#+ + } + else + { +#> + Assert.IsTrue( await unpacker.ReadAsync() ); +<#+ + } +#> + +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + +<#+ + if ( testSituation.Item2 == sourceType ) + { +#> + Assert.That( ( <#= sourceType #> )result.Value, Is.EqualTo( <#= expectedValue #> ) ); + Assert.That( result.Value.UnderlyingType, Is.EqualTo( typeof( <#= sourceType #> ) ) ); +<#+ + } +#> + + // raw/str always can be byte[] + var asBinary = ( byte[] )result.Value; + +<#+ + if ( canConvertToString ) + { +#> + var asString = ( String )result.Value; +<#+ + } + else + { +#> + Assert.Throws( () => { var asString = ( String )result.Value; } ); +<#+ + } + + if ( canConvertToString ) + { +#> + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault() ); +<#+ + } + else + { +#> + Assert.That( result.Value.IsTypeOf( typeof( string ) ).GetValueOrDefault(), Is.False ); +<#+ + } +#> + Assert.That( result.Value.IsTypeOf( typeof( byte[] ) ).GetValueOrDefault() ); + + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); +<#+ + } + else + { + if ( !isAsync ) + { +#> + Assert.Throws( () => unpacker.Read() ); +<#+ + } + else + { +#> + AssertEx.ThrowsAsync( async () => await unpacker.ReadAsync() ); +<#+ + } +#> + + // Only header is read. + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( <#= expectedReadLength #> ) ); +<#+ + } +} + +private void PutTestUnpackDirectBody( Tuple testSituation, string sourceType, string expectedValue, bool canConvertToString, bool isExtraOrSplit, int expectedReadLength, bool isAsync ) +{ + if ( !isAsync || isExtraOrSplit ) + { +#> + <#= testSituation.Item2 #> result; + +<#+ + } + + if ( isExtraOrSplit ) + { + if ( !isAsync ) + { +#> + Assert.IsTrue( unpacker.Read<#= testSituation.Item1 #>( out result ) ); +<#+ + } + else + { +#> + var ret = await unpacker.Read<#= testSituation.Item1 #>Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; +<#+ + } +#> + + Assert.That( result, Is.EqualTo( <#= expectedValue #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); +<#+ + } + else + { + if ( !isAsync ) + { +#> + Assert.Throws( () => unpacker.Read<#= testSituation.Item1 #>( out result ) ); +<#+ + } + else + { +#> + AssertEx.ThrowsAsync( async () => await unpacker.Read<#= testSituation.Item1 #>Async() ); +<#+ + } +#> + + // Only header is read. + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( <#= expectedReadLength #> ) ); +<#+ + } +} + +private void PutTestMethod( string methodName, Tuple testSituation, Tuple testCase, bool canConvertToString, Action, string, string, bool, bool, int, bool> putTestBody, bool isAsync ) +{ + var expectedValue = String.Format( CultureInfo.InvariantCulture, testSituation.Item4, testSituation.Item3, testCase.Item2 ); +#> + + [Test] + public <#= AsyncVoid( isAsync ) #> <#= methodName #>_Extra() + { + var data = + new byte[] { <#= testCase.Item3 #> } + .Concat( Enumerable.Repeat( ( byte )<#= testSituation.Item3 #>, <#= testCase.Item2 #> ) ).ToArray(); + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + +<#+ + putTestBody( testSituation, testCase.Item4, expectedValue, canConvertToString, true, testCase.Item5, isAsync ); +#> + } + } +<#+ +} + +private static string AsyncVoid( bool isAsync ) +{ + return ( isAsync ) ? "async Task" : "void"; +} +#> \ No newline at end of file diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Scalar.cs b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Scalar.cs new file mode 100644 index 000000000..9fd3ec774 --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Scalar.cs @@ -0,0 +1,2420 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayUnpackerTest.Scalar.tt T4Template. + // Do not modify this file. Edit ByteArrayUnpackerTest.Scalar.tt instead. + + partial class ByteArrayUnpackerTest + { + + [Test] + public void TestRead_Int64MinValue_Extra() + { + var data = new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -9223372036854775808 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadInt64_Int64MinValue_Extra() + { + var data = new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + Assert.IsTrue( unpacker.ReadInt64( out result ) ); + Assert.That( result, Is.EqualTo( -9223372036854775808 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_Int64MinValue_Extra() + { + var data = new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( -9223372036854775808 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Int32MinValue_Extra() + { + var data = new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -2147483648 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadInt64_Int32MinValue_Extra() + { + var data = new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + Assert.IsTrue( unpacker.ReadInt64( out result ) ); + Assert.That( result, Is.EqualTo( -2147483648 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_Int32MinValue_Extra() + { + var data = new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( -2147483648 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Int16MinValue_Extra() + { + var data = new byte[] { 0xD1, 0x80, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -32768 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadInt64_Int16MinValue_Extra() + { + var data = new byte[] { 0xD1, 0x80, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + Assert.IsTrue( unpacker.ReadInt64( out result ) ); + Assert.That( result, Is.EqualTo( -32768 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_Int16MinValue_Extra() + { + var data = new byte[] { 0xD1, 0x80, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( -32768 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_SByteMinValue_Extra() + { + var data = new byte[] { 0xD0, 0x80 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -128 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadInt64_SByteMinValue_Extra() + { + var data = new byte[] { 0xD0, 0x80 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + Assert.IsTrue( unpacker.ReadInt64( out result ) ); + Assert.That( result, Is.EqualTo( -128 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_SByteMinValue_Extra() + { + var data = new byte[] { 0xD0, 0x80 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( -128 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_NegativeFixNumMinValue_Extra() + { + var data = new byte[] { 0xE0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -32 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadInt64_NegativeFixNumMinValue_Extra() + { + var data = new byte[] { 0xE0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + Assert.IsTrue( unpacker.ReadInt64( out result ) ); + Assert.That( result, Is.EqualTo( -32 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_NegativeFixNumMinValue_Extra() + { + var data = new byte[] { 0xE0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( -32 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_MinusOne_Extra() + { + var data = new byte[] { 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadInt64_MinusOne_Extra() + { + var data = new byte[] { 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + Assert.IsTrue( unpacker.ReadInt64( out result ) ); + Assert.That( result, Is.EqualTo( -1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_MinusOne_Extra() + { + var data = new byte[] { 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( -1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_Zero_Extra() + { + var data = new byte[] { 0x0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_Zero_Extra() + { + var data = new byte[] { 0x0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_Zero_Extra() + { + var data = new byte[] { 0x0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_PlusOne_Extra() + { + var data = new byte[] { 0x1 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_PlusOne_Extra() + { + var data = new byte[] { 0x1 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_PlusOne_Extra() + { + var data = new byte[] { 0x1 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_PositiveFixNumMaxValue_Extra() + { + var data = new byte[] { 0x7F }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 127 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_PositiveFixNumMaxValue_Extra() + { + var data = new byte[] { 0x7F }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 127 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_PositiveFixNumMaxValue_Extra() + { + var data = new byte[] { 0x7F }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 127 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_ByteMaxValue_Extra() + { + var data = new byte[] { 0xCC, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_ByteMaxValue_Extra() + { + var data = new byte[] { 0xCC, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_ByteMaxValue_Extra() + { + var data = new byte[] { 0xCC, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_UInt16MaxValue_Extra() + { + var data = new byte[] { 0xCD, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_UInt16MaxValue_Extra() + { + var data = new byte[] { 0xCD, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_UInt16MaxValue_Extra() + { + var data = new byte[] { 0xCD, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_UInt32MaxValue_Extra() + { + var data = new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 4294967295 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_UInt32MaxValue_Extra() + { + var data = new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 4294967295 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_UInt32MaxValue_Extra() + { + var data = new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 4294967295 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_UInt64MaxValue_Extra() + { + var data = new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 18446744073709551615 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadUInt64_UInt64MaxValue_Extra() + { + var data = new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + Assert.IsTrue( unpacker.ReadUInt64( out result ) ); + Assert.That( result, Is.EqualTo( 18446744073709551615 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_UInt64MaxValue_Extra() + { + var data = new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result.Value, Is.EqualTo( 18446744073709551615 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_BooleanTrue_Extra() + { + var data = new byte[] { 0xC3 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Boolean )result.Value, Is.EqualTo( true ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBoolean_BooleanTrue_Extra() + { + var data = new byte[] { 0xC3 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean result; + Assert.IsTrue( unpacker.ReadBoolean( out result ) ); + Assert.That( result, Is.EqualTo( true ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableBoolean_BooleanTrue_Extra() + { + var data = new byte[] { 0xC3 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean? result; + Assert.IsTrue( unpacker.ReadNullableBoolean( out result ) ); + Assert.That( result.Value, Is.EqualTo( true ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_BooleanFalse_Extra() + { + var data = new byte[] { 0xC2 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Boolean )result.Value, Is.EqualTo( false ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadBoolean_BooleanFalse_Extra() + { + var data = new byte[] { 0xC2 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean result; + Assert.IsTrue( unpacker.ReadBoolean( out result ) ); + Assert.That( result, Is.EqualTo( false ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableBoolean_BooleanFalse_Extra() + { + var data = new byte[] { 0xC2 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean? result; + Assert.IsTrue( unpacker.ReadNullableBoolean( out result ) ); + Assert.That( result.Value, Is.EqualTo( false ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_SingleMaxValue_Extra() + { + var data = new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( Single.MaxValue.Equals( ( System.Single )result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadSingle_SingleMaxValue_Extra() + { + var data = new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Single result; + Assert.IsTrue( unpacker.ReadSingle( out result ) ); + Assert.That( Single.MaxValue.Equals( result ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableSingle_SingleMaxValue_Extra() + { + var data = new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Single? result; + Assert.IsTrue( unpacker.ReadNullableSingle( out result ) ); + Assert.That( Single.MaxValue.Equals( result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestRead_DoubleMaxValue_Extra() + { + var data = new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( unpacker.Read() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( Double.MaxValue.Equals( ( System.Double )result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadDouble_DoubleMaxValue_Extra() + { + var data = new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Double result; + Assert.IsTrue( unpacker.ReadDouble( out result ) ); + Assert.That( Double.MaxValue.Equals( result ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableDouble_DoubleMaxValue_Extra() + { + var data = new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Double? result; + Assert.IsTrue( unpacker.ReadNullableDouble( out result ) ); + Assert.That( Double.MaxValue.Equals( result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableBoolean_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean? result; + Assert.IsTrue( unpacker.ReadNullableBoolean( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableSingle_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Single? result; + Assert.IsTrue( unpacker.ReadNullableSingle( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableDouble_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Double? result; + Assert.IsTrue( unpacker.ReadNullableDouble( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableSByte_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + SByte? result; + Assert.IsTrue( unpacker.ReadNullableSByte( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt16_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Int16? result; + Assert.IsTrue( unpacker.ReadNullableInt16( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt32_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Int32? result; + Assert.IsTrue( unpacker.ReadNullableInt32( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableInt64_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Int64? result; + Assert.IsTrue( unpacker.ReadNullableInt64( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableByte_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte? result; + Assert.IsTrue( unpacker.ReadNullableByte( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt16_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + UInt16? result; + Assert.IsTrue( unpacker.ReadNullableUInt16( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt32_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + UInt32? result; + Assert.IsTrue( unpacker.ReadNullableUInt32( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public void TestReadNullableUInt64_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + UInt64? result; + Assert.IsTrue( unpacker.ReadNullableUInt64( out result ) ); + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + +#if FEATURE_TAP + + [Test] + public async Task TestReadAsync_Int64MinValue_Extra() + { + var data = new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -9223372036854775808 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadInt64Async_Int64MinValue_Extra() + { + var data = new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + var ret = await unpacker.ReadInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( -9223372036854775808 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_Int64MinValue_Extra() + { + var data = new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( -9223372036854775808 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Int32MinValue_Extra() + { + var data = new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -2147483648 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadInt64Async_Int32MinValue_Extra() + { + var data = new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + var ret = await unpacker.ReadInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( -2147483648 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_Int32MinValue_Extra() + { + var data = new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( -2147483648 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Int16MinValue_Extra() + { + var data = new byte[] { 0xD1, 0x80, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -32768 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadInt64Async_Int16MinValue_Extra() + { + var data = new byte[] { 0xD1, 0x80, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + var ret = await unpacker.ReadInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( -32768 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_Int16MinValue_Extra() + { + var data = new byte[] { 0xD1, 0x80, 0x00 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( -32768 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_SByteMinValue_Extra() + { + var data = new byte[] { 0xD0, 0x80 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -128 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadInt64Async_SByteMinValue_Extra() + { + var data = new byte[] { 0xD0, 0x80 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + var ret = await unpacker.ReadInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( -128 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_SByteMinValue_Extra() + { + var data = new byte[] { 0xD0, 0x80 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( -128 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_NegativeFixNumMinValue_Extra() + { + var data = new byte[] { 0xE0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -32 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadInt64Async_NegativeFixNumMinValue_Extra() + { + var data = new byte[] { 0xE0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + var ret = await unpacker.ReadInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( -32 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_NegativeFixNumMinValue_Extra() + { + var data = new byte[] { 0xE0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( -32 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_MinusOne_Extra() + { + var data = new byte[] { 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Int64 )result.Value, Is.EqualTo( -1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadInt64Async_MinusOne_Extra() + { + var data = new byte[] { 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64 result; + var ret = await unpacker.ReadInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( -1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_MinusOne_Extra() + { + var data = new byte[] { 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( -1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_Zero_Extra() + { + var data = new byte[] { 0x0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_Zero_Extra() + { + var data = new byte[] { 0x0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_Zero_Extra() + { + var data = new byte[] { 0x0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 0 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_PlusOne_Extra() + { + var data = new byte[] { 0x1 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_PlusOne_Extra() + { + var data = new byte[] { 0x1 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_PlusOne_Extra() + { + var data = new byte[] { 0x1 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 1 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_PositiveFixNumMaxValue_Extra() + { + var data = new byte[] { 0x7F }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 127 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_PositiveFixNumMaxValue_Extra() + { + var data = new byte[] { 0x7F }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 127 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_PositiveFixNumMaxValue_Extra() + { + var data = new byte[] { 0x7F }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 127 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_ByteMaxValue_Extra() + { + var data = new byte[] { 0xCC, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_ByteMaxValue_Extra() + { + var data = new byte[] { 0xCC, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_ByteMaxValue_Extra() + { + var data = new byte[] { 0xCC, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 255 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_UInt16MaxValue_Extra() + { + var data = new byte[] { 0xCD, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_UInt16MaxValue_Extra() + { + var data = new byte[] { 0xCD, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_UInt16MaxValue_Extra() + { + var data = new byte[] { 0xCD, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 65535 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_UInt32MaxValue_Extra() + { + var data = new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 4294967295 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_UInt32MaxValue_Extra() + { + var data = new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 4294967295 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_UInt32MaxValue_Extra() + { + var data = new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 4294967295 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_UInt64MaxValue_Extra() + { + var data = new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.UInt64 )result.Value, Is.EqualTo( 18446744073709551615 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadUInt64Async_UInt64MaxValue_Extra() + { + var data = new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64 result; + var ret = await unpacker.ReadUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( 18446744073709551615 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_UInt64MaxValue_Extra() + { + var data = new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( 18446744073709551615 ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_BooleanTrue_Extra() + { + var data = new byte[] { 0xC3 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Boolean )result.Value, Is.EqualTo( true ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBooleanAsync_BooleanTrue_Extra() + { + var data = new byte[] { 0xC3 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean result; + var ret = await unpacker.ReadBooleanAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( true ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableBooleanAsync_BooleanTrue_Extra() + { + var data = new byte[] { 0xC3 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean? result; + var ret = await unpacker.ReadNullableBooleanAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( true ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_BooleanFalse_Extra() + { + var data = new byte[] { 0xC2 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( System.Boolean )result.Value, Is.EqualTo( false ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadBooleanAsync_BooleanFalse_Extra() + { + var data = new byte[] { 0xC2 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean result; + var ret = await unpacker.ReadBooleanAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.EqualTo( false ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableBooleanAsync_BooleanFalse_Extra() + { + var data = new byte[] { 0xC2 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean? result; + var ret = await unpacker.ReadNullableBooleanAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result.Value, Is.EqualTo( false ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_SingleMaxValue_Extra() + { + var data = new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( Single.MaxValue.Equals( ( System.Single )result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadSingleAsync_SingleMaxValue_Extra() + { + var data = new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Single result; + var ret = await unpacker.ReadSingleAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( Single.MaxValue.Equals( result ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableSingleAsync_SingleMaxValue_Extra() + { + var data = new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Single? result; + var ret = await unpacker.ReadNullableSingleAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( Single.MaxValue.Equals( result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadAsync_DoubleMaxValue_Extra() + { + var data = new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( await unpacker.ReadAsync() ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( Double.MaxValue.Equals( ( System.Double )result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadDoubleAsync_DoubleMaxValue_Extra() + { + var data = new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Double result; + var ret = await unpacker.ReadDoubleAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( Double.MaxValue.Equals( result ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableDoubleAsync_DoubleMaxValue_Extra() + { + var data = new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Double? result; + var ret = await unpacker.ReadNullableDoubleAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( Double.MaxValue.Equals( result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableBooleanAsync_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Boolean? result; + var ret = await unpacker.ReadNullableBooleanAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableSingleAsync_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Single? result; + var ret = await unpacker.ReadNullableSingleAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableDoubleAsync_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Double? result; + var ret = await unpacker.ReadNullableDoubleAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableSByteAsync_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + SByte? result; + var ret = await unpacker.ReadNullableSByteAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt16Async_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Int16? result; + var ret = await unpacker.ReadNullableInt16Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt32Async_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Int32? result; + var ret = await unpacker.ReadNullableInt32Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableInt64Async_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Int64? result; + var ret = await unpacker.ReadNullableInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableByteAsync_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Byte? result; + var ret = await unpacker.ReadNullableByteAsync(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt16Async_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + UInt16? result; + var ret = await unpacker.ReadNullableUInt16Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt32Async_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + UInt32? result; + var ret = await unpacker.ReadNullableUInt32Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + + [Test] + public async Task TestReadNullableUInt64Async_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + UInt64? result; + var ret = await unpacker.ReadNullableUInt64Async(); + Assert.IsTrue( ret.Success ); + result = ret.Value; + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } + +#endif // FEATURE_TAP + + } +} diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Scalar.tt b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Scalar.tt new file mode 100644 index 000000000..a6d1cc729 --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.Scalar.tt @@ -0,0 +1,434 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly Name="System.Core" #> +<#@ assembly Name="System.Numerics" #> +<#@ import namespace="System" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Numerics" #> +<#@ import namespace="System.Runtime.InteropServices" #> +<# + +var __integers = + new Tuple[] + { + // Label, Expected Value, byte array, Exepected Type + Tuple.Create( "Int64MinValue", new BigInteger( Int64.MinValue ), "new byte[] { 0xD3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }", typeof( long ) ), + Tuple.Create( "Int32MinValue", new BigInteger( Int32.MinValue ), "new byte[] { 0xD2, 0x80, 0x00, 0x00, 0x00 }", typeof( long ) ), + Tuple.Create( "Int16MinValue", new BigInteger( Int16.MinValue ), "new byte[] { 0xD1, 0x80, 0x00 }", typeof( long ) ), + Tuple.Create( "SByteMinValue", new BigInteger( SByte.MinValue ), "new byte[] { 0xD0, 0x80 }", typeof( long ) ), + Tuple.Create( "NegativeFixNumMinValue", new BigInteger( -32 ), "new byte[] { 0xE0 }", typeof( long ) ), + Tuple.Create( "MinusOne", new BigInteger( -1 ), "new byte[] { 0xFF }", typeof( long ) ), + Tuple.Create( "Zero", new BigInteger( 0 ), "new byte[] { 0x0 }", typeof( ulong ) ), + Tuple.Create( "PlusOne", new BigInteger( 1 ), "new byte[] { 0x1 }", typeof( ulong ) ), + Tuple.Create( "PositiveFixNumMaxValue", new BigInteger( 127 ), "new byte[] { 0x7F }", typeof( ulong ) ), + Tuple.Create( "ByteMaxValue", new BigInteger( Byte.MaxValue ), "new byte[] { 0xCC, 0xFF }", typeof( ulong ) ), + Tuple.Create( "UInt16MaxValue", new BigInteger( UInt16.MaxValue ), "new byte[] { 0xCD, 0xFF, 0xFF }", typeof( ulong ) ), + Tuple.Create( "UInt32MaxValue", new BigInteger( UInt32.MaxValue ), "new byte[] { 0xCE, 0xFF, 0xFF, 0xFF, 0xFF }", typeof( ulong ) ), + Tuple.Create( "UInt64MaxValue", new BigInteger( UInt64.MaxValue ), "new byte[] { 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }", typeof( ulong ) ), + }; + +var __booleans = + new Tuple[] + { + // Label, Expected Value, byte array, Exepected Type + Tuple.Create( "BooleanTrue", true, "new byte[] { 0xC3 }", typeof( bool ) ), + Tuple.Create( "BooleanFalse", false, "new byte[] { 0xC2 }", typeof( bool ) ), + }; + +var __reals = + new Tuple[] + { + // Label, byte array, Exepected Type, Testing Expression + Tuple.Create( "SingleMaxValue", "new byte[] { 0xCA, 0x7F, 0x7F, 0xFF, 0xFF }", typeof( float ), "Single.MaxValue.Equals(" ), + Tuple.Create( "DoubleMaxValue", "new byte[] { 0xCB, 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }", typeof( double ), "Double.MaxValue.Equals(" ), + }; + +#> +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + // This file was generated from ByteArrayUnpackerTest.Scalar.tt T4Template. + // Do not modify this file. Edit ByteArrayUnpackerTest.Scalar.tt instead. + + partial class ByteArrayUnpackerTest + { +<# +foreach( var isAsync in new [] { false, true } ) +{ + if ( isAsync ) + { +#> + +#if FEATURE_TAP +<# + } + + foreach( var __testCase in __integers ) + { + var length = __testCase.Item3.Count( c => c == ',' ) + 1; +#> + + [Test] + public <#= AsyncTest( isAsync ) #>_<#= __testCase.Item1 #>_Extra() + { + var data = <#= __testCase.Item3 #>; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( <#= ReadAwait( isAsync ) #> ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( <#= __testCase.Item4 #> )result.Value, Is.EqualTo( <#= __testCase.Item2 #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } +<# + foreach( var isNullable in new [] { false, true } ) + { +#> + + [Test] + public <#= AsyncTest( isAsync, isNullable, __testCase.Item4 ) #>_<#= __testCase.Item1 #>_Extra() + { + var data = <#= __testCase.Item3 #>; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + <#= __testCase.Item4.Name #><#= isNullable ? "?" : String.Empty #> result; +<# + if( !isAsync ) + { +#> + Assert.IsTrue( <#= Read( isNullable, __testCase.Item4 ) #> ); +<# + } + else + { +#> + var ret = <#= ReadAwait( isNullable, __testCase.Item4 ) #>; + Assert.IsTrue( ret.Success ); + result = ret.Value; +<# + } +#> + Assert.That( result<#= isNullable ? ".Value" : String.Empty #>, Is.EqualTo( <#= __testCase.Item2 #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset -1, Is.EqualTo( data.Length ) ); + } + } +<# + } // foreach( var isNullable + } // foreach( var __testCase + + foreach( var __testCase in __booleans ) + { +#> + + [Test] + public <#= AsyncTest( isAsync ) #>_<#= __testCase.Item1 #>_Extra() + { + var data = <#= __testCase.Item3 #>; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( <#= ReadAwait( isAsync ) #> ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( ( <#= __testCase.Item4 #> )result.Value, Is.EqualTo( <#= __testCase.Item2.ToString( CultureInfo.InvariantCulture ).ToLowerInvariant() #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } +<# + foreach( var isNullable in new [] { false, true } ) + { +#> + + [Test] + public <#= AsyncTest( isAsync, isNullable, __testCase.Item4 ) #>_<#= __testCase.Item1 #>_Extra() + { + var data = <#= __testCase.Item3 #>; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + <#= __testCase.Item4.Name #><#= isNullable ? "?" : String.Empty #> result; +<# + if( !isAsync ) + { +#> + Assert.IsTrue( <#= Read( isNullable, __testCase.Item4 ) #> ); +<# + } + else + { +#> + var ret = <#= ReadAwait( isNullable, __testCase.Item4 ) #>; + Assert.IsTrue( ret.Success ); + result = ret.Value; +<# + } +#> + Assert.That( result<#= isNullable ? ".Value" : String.Empty #>, Is.EqualTo( <#= __testCase.Item2.ToString( CultureInfo.InvariantCulture ).ToLowerInvariant() #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } +<# + } // foreach( var isNullable + } // foreach( var __testCase + + foreach( var __testCase in __reals ) + { +#> + + [Test] + public <#= AsyncTest( isAsync ) #>_<#= __testCase.Item1 #>_Extra() + { + var data = <#= __testCase.Item2 #>; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + Assert.IsTrue( <#= ReadAwait( isAsync ) #> ); +#pragma warning disable 612,618 + var result = unpacker.Data; +#pragma warning restore 612,618 + Assert.IsTrue( result.HasValue ); + Assert.That( <#= __testCase.Item4 #> ( <#= __testCase.Item3 #> )result.Value ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } +<# + foreach( var isNullable in new [] { false, true } ) + { +#> + + [Test] + public <#= AsyncTest( isAsync, isNullable, __testCase.Item3 ) #>_<#= __testCase.Item1 #>_Extra() + { + var data = <#= __testCase.Item2 #>; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + <#= __testCase.Item3.Name #><#= isNullable ? "?" : String.Empty #> result; +<# + if( !isAsync ) + { +#> + Assert.IsTrue( <#= Read( isNullable, __testCase.Item3 ) #> ); +<# + } + else + { +#> + var ret = <#= ReadAwait( isNullable, __testCase.Item3 ) #>; + Assert.IsTrue( ret.Success ); + result = ret.Value; +<# + } +#> + Assert.That( <#= __testCase.Item4 #> result<#= isNullable ? ".Value" : String.Empty #> ) ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } +<# + } // foreach( var isNullable + } // foreach( var __testCase + + foreach ( var __scalarType in + new [] + { + typeof( bool ), typeof( float ), typeof ( double ), + typeof( sbyte ), typeof( short ), typeof ( int ), typeof ( long ), + typeof( byte ), typeof( ushort ), typeof ( uint ), typeof ( ulong ), + } + ) + { +#> + + [Test] + public <#= AsyncTest( isAsync, true, __scalarType ) #>_Extra() + { + var data = new byte[] { 0xC0 }; + using( var unpacker = this.CreateUnpacker( PrependAppendExtra( data ), 1 ) ) + { + // Verify initial offset (prepended bytes length) + Assert.That( unpacker.Offset, Is.EqualTo( 1 ) ); + + <#= __scalarType.Name #>? result; +<# + if( !isAsync ) + { +#> + Assert.IsTrue( <#= Read( true, __scalarType ) #> ); +<# + } + else + { +#> + var ret = <#= ReadAwait( true, __scalarType ) #>; + Assert.IsTrue( ret.Success ); + result = ret.Value; +<# + } +#> + Assert.That( result, Is.Null ); + + // -1 is prepended extra bytes length + Assert.That( unpacker.Offset - 1, Is.EqualTo( data.Length ) ); + } + } +<# + } // foreach( var __scalarType + + if ( isAsync ) + { +#> + +#endif // FEATURE_TAP + +<# + } +} // foreach( var isAsync +#> + } +} +<#+ +private static string AsyncTest( bool isAsync ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "{0} TestRead{1}", + isAsync ? "async Task" : "void", + isAsync ? "Async" : String.Empty + ); +} + +private static string Test( bool isAsync ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "void TestRead{0}", + isAsync ? "Async" : String.Empty + ); +} + +private static string AsyncTest( bool isAsync, bool isNullable, Type type ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "{0} TestRead{1}{2}{3}", + isAsync ? "async Task" : "void", + isNullable ? "Nullable" : String.Empty, + type.Name, + isAsync ? "Async" : String.Empty + ); +} + +private static string Test( bool isAsync, bool isNullable, Type type ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "void TestRead{0}{1}{2}", + isNullable ? "Nullable" : String.Empty, + type.Name, + isAsync ? "Async" : String.Empty + ); +} + +private static string ReadAwait( bool isAsync ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "{0}unpacker.Read{1}()", + isAsync ? "await " : String.Empty, + isAsync ? "Async" : String.Empty + ); +} + +private static string Read( bool isNullable, Type type ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "unpacker.Read{0}{1}( out result )", + isNullable ? "Nullable" : String.Empty, + type.Name + ); +} + +private static string ReadAwait( bool isNullable, Type type ) +{ + return + String.Format( + CultureInfo.InvariantCulture, + "await unpacker.Read{0}{1}Async()", + isNullable ? "Nullable" : String.Empty, + type.Name + ); +} +#> \ No newline at end of file diff --git a/test/MsgPack.UnitTest/ByteArrayUnpackerTest.cs b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.cs new file mode 100644 index 000000000..a683ea0dd --- /dev/null +++ b/test/MsgPack.UnitTest/ByteArrayUnpackerTest.cs @@ -0,0 +1,79 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using System.IO; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + public abstract partial class ByteArrayUnpackerTest : UnpackerTest + { + protected override bool ShouldCheckStreamPosition + { + get { return false; } + } + + protected override bool CanReadFromEmptySource + { + get { return false; } + } + + protected override bool MayFailToRollback + { + get { return false; } + } + + protected sealed override Unpacker CreateUnpacker( MemoryStream stream ) + { + return this.CreateUnpacker( stream.ToArray(), 0 ); + } + + protected abstract ByteArrayUnpacker CreateUnpacker( byte[] source, int offset ); + + protected override bool CanRevert( Unpacker unpacker ) + { + return true; + } + + protected override long GetOffset( Unpacker unpacker ) + { + return ( ( ByteArrayUnpacker )unpacker ).Offset; + } + + private static byte[] PrependAppendExtra( byte[] data ) + { + var buffer = new byte[ data.Length + 2 ]; + data.CopyTo( buffer, 1 ); + buffer[ 0 ] = 0xC1; + buffer[ buffer.Length - 1 ] = 0xC1; + return buffer; + } + } +} diff --git a/test/MsgPack.UnitTest/CollectionValidatingByteArrayUnpackerTest.cs b/test/MsgPack.UnitTest/CollectionValidatingByteArrayUnpackerTest.cs new file mode 100644 index 000000000..71c3a0d5b --- /dev/null +++ b/test/MsgPack.UnitTest/CollectionValidatingByteArrayUnpackerTest.cs @@ -0,0 +1,49 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + [TestFixture] + [Timeout( 30000 )] + public class CollectionValidatingByteArrayUnpackerTest : ByteArrayUnpackerTest + { + protected override bool ShouldCheckSubtreeUnpacker + { + get { return true; } + } + + protected override ByteArrayUnpacker CreateUnpacker( byte[] source, int offset ) + { + return Unpacker.Create( source, offset, new UnpackerOptions { ValidationLevel = UnpackerValidationLevel.Collection } ); + } + } +} diff --git a/test/MsgPack.UnitTest/CollectionValidatingStreamUnpackerTest.cs b/test/MsgPack.UnitTest/CollectionValidatingStreamUnpackerTest.cs new file mode 100644 index 000000000..a49829820 --- /dev/null +++ b/test/MsgPack.UnitTest/CollectionValidatingStreamUnpackerTest.cs @@ -0,0 +1,49 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.IO; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + [TestFixture] + [Timeout( 30000 )] + public class CollectionValidatingStreamUnpackerTest : StreamUnpackerTest + { + protected override bool ShouldCheckSubtreeUnpacker + { + get { return true; } + } + + protected override Unpacker CreateUnpacker( Stream stream ) + { + return Unpacker.Create( stream, PackerUnpackerStreamOptions.None, new UnpackerOptions { ValidationLevel = UnpackerValidationLevel.Collection } ); + } + } +} diff --git a/test/MsgPack.UnitTest/DirectConversionTest.Scalar.cs b/test/MsgPack.UnitTest/DirectConversionTest.Scalar.cs index 6e4cc193d..99d0667b3 100644 --- a/test/MsgPack.UnitTest/DirectConversionTest.Scalar.cs +++ b/test/MsgPack.UnitTest/DirectConversionTest.Scalar.cs @@ -21,9 +21,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; -#if NETFX_35 +#if NET35 using Debug = System.Console; // For missing Debug.WriteLine(String, params Object[]) -#endif // NETFX_35 +#endif // NET35 using System.IO; using System.Text; #if !MSTEST diff --git a/test/MsgPack.UnitTest/DirectConversionTest.Scalar.tt b/test/MsgPack.UnitTest/DirectConversionTest.Scalar.tt index 9a1a96fc8..0d538f3df 100644 --- a/test/MsgPack.UnitTest/DirectConversionTest.Scalar.tt +++ b/test/MsgPack.UnitTest/DirectConversionTest.Scalar.tt @@ -71,9 +71,9 @@ Func __isUnsigned = using System; using System.Collections.Generic; using System.Diagnostics; -#if NETFX_35 +#if NET35 using Debug = System.Console; // For missing Debug.WriteLine(String, params Object[]) -#endif // NETFX_35 +#endif // NET35 using System.IO; using System.Text; #if !MSTEST diff --git a/test/MsgPack.UnitTest/DirectConversionTest.cs b/test/MsgPack.UnitTest/DirectConversionTest.cs index abebbbed6..ccbb79056 100644 --- a/test/MsgPack.UnitTest/DirectConversionTest.cs +++ b/test/MsgPack.UnitTest/DirectConversionTest.cs @@ -21,9 +21,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; -#if NETFX_35 +#if NET35 using Debug = System.Console; // For missing Debug.WriteLine(String, params Object[]) -#endif // NETFX_35 +#endif // NET35 using System.IO; using System.Text; #if !MSTEST @@ -87,6 +87,7 @@ private static void TestBoolean( bool value ) Assert.AreEqual( value, Unpacking.UnpackBoolean( output.ToArray() ).Value ); } +#if !SILVERLIGHT [Test] [Explicit] // FIXME : split public void TestString() @@ -101,7 +102,7 @@ public void TestString() var sw = Stopwatch.StartNew(); var avg = 0.0; Random random = new Random(); -#if !SKIP_LARGE_TEST && !NETFX_35 +#if !SKIP_LARGE_TEST && !NET35 var sb = new StringBuilder( 1000 * 1000 * 200 ); #else var sb = new StringBuilder( 1000 * 200 ); @@ -139,7 +140,7 @@ public void TestString() sw.Stop(); Debug.WriteLine( "Medium String ({1:#.0}): {0:0.###} msec/object", sw.ElapsedMilliseconds / 100.0, avg ); sw.Reset(); -#if !SKIP_LARGE_TEST && !NETFX_35 +#if !SKIP_LARGE_TEST && !NET35 sw.Start(); avg = 0.0; @@ -191,6 +192,7 @@ private static void TestString( String value ) Assert.AreEqual( value, Unpacking.UnpackString( new MemoryStream( output.ToArray() ) ) ); Assert.AreEqual( value, Unpacking.UnpackString( output.ToArray() ).Value ); } +#endif // !SILVERLIGHT [Test] [Timeout( 30000 )] diff --git a/test/MsgPack.UnitTest.Net35/Dummies/System.Threading.Tasks/Task.cs b/test/MsgPack.UnitTest/Dummies/System.Threading.Tasks/Task.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Dummies/System.Threading.Tasks/Task.cs rename to test/MsgPack.UnitTest/Dummies/System.Threading.Tasks/Task.cs diff --git a/test/MsgPack.UnitTest.Net35/Dummies/System.Threading.Tasks/TaskFactory.cs b/test/MsgPack.UnitTest/Dummies/System.Threading.Tasks/TaskFactory.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Dummies/System.Threading.Tasks/TaskFactory.cs rename to test/MsgPack.UnitTest/Dummies/System.Threading.Tasks/TaskFactory.cs diff --git a/test/MsgPack.UnitTest/FastByteArrayUnpackerTest.cs b/test/MsgPack.UnitTest/FastByteArrayUnpackerTest.cs new file mode 100644 index 000000000..498b51c97 --- /dev/null +++ b/test/MsgPack.UnitTest/FastByteArrayUnpackerTest.cs @@ -0,0 +1,49 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + [TestFixture] + [Timeout( 30000 )] + public class FastByteArrayUnpackerTest : ByteArrayUnpackerTest + { + protected override bool ShouldCheckSubtreeUnpacker + { + get { return false; } + } + + protected override ByteArrayUnpacker CreateUnpacker( byte[] source, int offset ) + { + return Unpacker.Create( source, offset, new UnpackerOptions { ValidationLevel = UnpackerValidationLevel.None } ); + } + } +} diff --git a/test/MsgPack.UnitTest/FastStreamUnpackerTest.cs b/test/MsgPack.UnitTest/FastStreamUnpackerTest.cs new file mode 100644 index 000000000..4c598bcb7 --- /dev/null +++ b/test/MsgPack.UnitTest/FastStreamUnpackerTest.cs @@ -0,0 +1,50 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion -- License Terms -- + +using System.IO; +using System.Linq; +using System.Threading.Tasks; +#if !MSTEST +using NUnit.Framework; +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + [TestFixture] + [Timeout( 30000 )] + public class FastStreamUnpackerTest : StreamUnpackerTest + { + protected override bool ShouldCheckSubtreeUnpacker + { + get { return false; } + } + + protected override Unpacker CreateUnpacker( Stream stream ) + { + return Unpacker.Create( stream, PackerUnpackerStreamOptions.None, new UnpackerOptions { ValidationLevel = UnpackerValidationLevel.None } ); + } + } +} diff --git a/test/MsgPack.UnitTest/GenericExceptionTester.cs b/test/MsgPack.UnitTest/GenericExceptionTester.cs index 611cc95e1..014ed9430 100644 --- a/test/MsgPack.UnitTest/GenericExceptionTester.cs +++ b/test/MsgPack.UnitTest/GenericExceptionTester.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -146,6 +146,9 @@ public void TestException() this.TestInnerExceptionConstructor_Null_SetToDefaultMessageAndNullInnerException(); #if !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 this.TestSerialization(); +#if !NETSTANDARD2_0 + this.TestSerializationOnPartialTrust(); +#endif // !NETSTANDARD2_0 #endif // !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 } @@ -220,7 +223,11 @@ private static void TestToStringCore( T target, string ctor ) #if !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 private void TestSerialization() { +#if !NETSTANDARD2_0 Assert.That( typeof( T ), Is.BinarySerializable ); +#else // !NETSTANDARD2_0 + Assert.That( typeof( T ).IsSerializable, Is.True ); +#endif // !NETSTANDARD2_0 var innerMessage = Guid.NewGuid().ToString(); var message = Guid.NewGuid().ToString(); var target = this._innerExceptionConstructor( message, new Exception( innerMessage ) ); @@ -237,11 +244,12 @@ private void TestSerialization() } } +#if !NETSTANDARD2_0 private void TestSerializationOnPartialTrust() { var appDomainSetUp = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; var evidence = new Evidence(); -#if MONO || NETFX_35 +#if MONO || NET35 #pragma warning disable 0612 // TODO: patching // currently, Mono does not declare AddHostEvidence @@ -252,7 +260,7 @@ private void TestSerializationOnPartialTrust() evidence.AddHostEvidence( new Zone( SecurityZone.Internet ) ); var permisions = SecurityManager.GetStandardSandbox( evidence ); #endif - AppDomain workerDomain = AppDomain.CreateDomain( "PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName( this.GetType() ) ); + AppDomain workerDomain = AppDomain.CreateDomain( "PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName( this.GetType() ), GetStrongName( typeof( Assert ) ) ); try { var innerMessage = Guid.NewGuid().ToString(); @@ -265,7 +273,7 @@ private void TestSerializationOnPartialTrust() var target = workerDomain.GetData( "MsgPack.GenericExceptionTester.Target" ) as T; Assert.That( target, Is.Not.Null ); Assert.That( target.Message, Is.EqualTo( target.Message ) ); - Assert.That( target.InnerException, Is.Not.Null.And.TypeOf( typeof( Exception ) ) ); + Assert.That( target.InnerException is Exception, target.InnerException == null ? "(null)" : target.InnerException.GetType().ToString() ); Assert.That( target.InnerException.Message, Is.EqualTo( target.InnerException.Message ) ); } finally @@ -274,7 +282,7 @@ private void TestSerializationOnPartialTrust() } } -#if MONO || NETFX_35 +#if MONO || NET35 private static PermissionSet GetDefaultInternetZoneSandbox() { var permissions = new PermissionSet( PermissionState.None ); @@ -292,7 +300,8 @@ private static PermissionSet GetDefaultInternetZoneSandbox() ); permissions.AddPermission( new SecurityPermission( - SecurityPermissionFlag.Execution + SecurityPermissionFlag.Execution | + SecurityPermissionFlag.SkipVerification // for unsafe code ) ); permissions.AddPermission( @@ -304,7 +313,7 @@ private static PermissionSet GetDefaultInternetZoneSandbox() return permissions; } -#endif // if MONO || NETFX_35 +#endif // if MONO || NET35 public static void TestSerializationOnPartialTrustCore() { @@ -314,7 +323,7 @@ public static void TestSerializationOnPartialTrustCore() var target = instance.CreateTargetInstance( message, new Exception( innerMessage ) ); Assert.That( target, Is.Not.Null ); Assert.That( target.Message, Is.EqualTo( target.Message ) ); - Assert.That( target.InnerException, Is.Not.Null.And.TypeOf( typeof( Exception ) ) ); + Assert.That( target.InnerException is Exception, target.InnerException == null ? "(null)" : target.InnerException.GetType().ToString() ); Assert.That( target.InnerException.Message, Is.EqualTo( target.InnerException.Message ) ); AppDomain.CurrentDomain.SetData( "MsgPack.GenericExceptionTester.Target", target ); } @@ -324,6 +333,7 @@ private static StrongName GetStrongName( Type type ) var assemblyName = type.Assembly.GetName(); return new StrongName( new StrongNamePublicKeyBlob( assemblyName.GetPublicKey() ), assemblyName.Name, assemblyName.Version ); } +#endif // !NETSTANDARD2_0 #endif // !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 } } diff --git a/test/MsgPack.UnitTest/LegacyJapaneseCultureInfo.cs b/test/MsgPack.UnitTest/LegacyJapaneseCultureInfo.cs new file mode 100644 index 000000000..3ff61c305 --- /dev/null +++ b/test/MsgPack.UnitTest/LegacyJapaneseCultureInfo.cs @@ -0,0 +1,47 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2017 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#endregion -- License Terms -- + +using System; +using System.Globalization; + +namespace MsgPack +{ + /// + /// Custom which uses full width hiphen for negative sign.!-- + /// +#if UNITY // Enabled by copy script for Unity + [Serializable] +#endif // UNITY + internal sealed class LegacyJapaneseCultureInfo : CultureInfo + { + public LegacyJapaneseCultureInfo() +#if NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT + : base( "ja-JP" ) +#else + : base( "ja-JP", true ) +#endif // NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT + { + var numberFormatInfo = CultureInfo.InvariantCulture.NumberFormat.Clone() as NumberFormatInfo; + numberFormatInfo.NegativeSign = "\uFF0D"; // Full width hiphen + this.NumberFormat = NumberFormatInfo.ReadOnly( numberFormatInfo ); + } + } +} diff --git a/test/MsgPack.UnitTest/MessagePackConvertTest.cs b/test/MsgPack.UnitTest/MessagePackConvertTest.cs index f67f67b4e..645342b06 100644 --- a/test/MsgPack.UnitTest/MessagePackConvertTest.cs +++ b/test/MsgPack.UnitTest/MessagePackConvertTest.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -317,19 +317,21 @@ public void TestToDateTime_MinimumMinusOne_IsUtcEpoc() [Test] public void TestFromDateTimeOffset_UtcNow_AsUnixEpoc() { + var utcNow = DateTimeOffset.UtcNow; Assert.AreEqual( - checked( DateTime.UtcNow.Subtract( UtcEpoc ).Ticks / TicksToMilliseconds ), - MessagePackConvert.FromDateTimeOffset( DateTimeOffset.UtcNow ) + checked( utcNow.DateTime.Subtract( UtcEpoc ).Ticks / TicksToMilliseconds ), + MessagePackConvert.FromDateTimeOffset( utcNow ) ); } [Test] public void TestFromDateTimeOffset_Now_AsUtcUnixEpoc() { + var utcNow = DateTimeOffset.UtcNow; // LocalTime will be converted to UtcTime Assert.AreEqual( - checked( DateTime.UtcNow.Subtract( UtcEpoc ).Ticks / TicksToMilliseconds ), - MessagePackConvert.FromDateTimeOffset( DateTimeOffset.Now ) + checked( utcNow.DateTime.Subtract( UtcEpoc ).Ticks / TicksToMilliseconds ), + MessagePackConvert.FromDateTimeOffset( utcNow.ToLocalTime() ) ); } diff --git a/test/MsgPack.UnitTest/MessagePackMemberSkipTest.cs b/test/MsgPack.UnitTest/MessagePackMemberSkipTest.cs new file mode 100644 index 000000000..5cddb9065 --- /dev/null +++ b/test/MsgPack.UnitTest/MessagePackMemberSkipTest.cs @@ -0,0 +1,214 @@ +#region -- License Terms -- +// +// MessagePack for CLI +// +// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Contributors: +// Shrenik Jhaveri (ShrenikOne) +// +#endregion -- License Terms -- + +using System; +using System.Collections.Generic; +using System.IO; + +using MsgPack.Serialization; + +#if !MSTEST +using NUnit.Framework; // For running checking +#else +using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; +using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; +using TimeoutAttribute = NUnit.Framework.TimeoutAttribute; +using Assert = NUnit.Framework.Assert; +using Is = NUnit.Framework.Is; +#endif + +namespace MsgPack +{ + [TestFixture] + public class MessagePackMemberSkipTest + { + [Test] + public void SerializeThenDeserialize_Array() + { + // They are object for just description. + var targetObject = new PhotoEntry + { + Id = 123, + Title = "My photo", + Date = DateTime.Now, + Image = new byte[] { 1, 2, 3, 4 }, + Comment = "This is test object to be serialize/deserialize using MsgPack." + }; + + targetObject.Tags.Add( new PhotoTag { Name = "Sample", Id = 123 } ); + targetObject.Tags.Add( new PhotoTag { Name = "Excellent", Id = 456 } ); + var stream = new MemoryStream(); + + // 1. Create serializer instance. + SerializationContext context = new SerializationContext(); + context.SerializationMethod = SerializationMethod.Array; + context.DefaultDateTimeConversionMethod = DateTimeConversionMethod.Native; + context.BindingOptions.SetIgnoringMembers( typeof( PhotoEntry ), new[] { nameof( PhotoEntry.Image ) } ); + context.BindingOptions.SetIgnoringMembers( typeof( PhotoTag ), new[] { nameof( PhotoTag.Name ) } ); + var serializer = MessagePackSerializer.Get( context ); + + // 2. Serialize object to the specified stream. + serializer.Pack( stream, targetObject ); + + // Set position to head of the stream to demonstrate deserialization. + stream.Position = 0; + + // 3. Deserialize object from the specified stream. + var deserializedObject = serializer.Unpack( stream ); + + Assert.AreEqual( targetObject.Comment, deserializedObject.Comment ); + Assert.AreEqual( targetObject.Id, deserializedObject.Id ); + Assert.AreEqual( targetObject.Date, deserializedObject.Date ); + Assert.AreEqual( targetObject.Title, deserializedObject.Title ); + Assert.Null( deserializedObject.Image ); + Assert.AreEqual( targetObject.Tags.Count, deserializedObject.Tags.Count ); + for ( int i = 0; i < deserializedObject.Tags.Count; i++ ) + { + Assert.AreEqual( targetObject.Tags[ i ].Id, deserializedObject.Tags[ i ].Id ); + Assert.Null( deserializedObject.Tags[ i ].Name ); + } + + //// TODO: @yfakariya, Need help, how i can achieve below.... + //// How i can inject Nil or Null for Skipped/Ignored member, to support interoperability... + + + //// SerializationContext newContext = new SerializationContext(); + //// newContext.SerializationMethod = SerializationMethod.Array; + //// newContext.DefaultDateTimeConversionMethod = DateTimeConversionMethod.Native; + //// serializer = MessagePackSerializer.Get( newContext ); + + //// // Set position to head of the stream to demonstrate deserialization. + //// stream.Position = 0; + + //// // 3. Deserialize object from the specified stream. + //// deserializedObject = serializer.Unpack( stream ); + + //// Assert.AreEqual( targetObject.Comment, deserializedObject.Comment ); + //// Assert.AreEqual( targetObject.Id, deserializedObject.Id ); + //// Assert.AreEqual( targetObject.Date, deserializedObject.Date ); + //// Assert.AreEqual( targetObject.Title, deserializedObject.Title ); + //// Assert.Null( deserializedObject.Image ); + //// Assert.AreEqual( targetObject.Tags.Count, deserializedObject.Tags.Count ); + //// for ( int i = 0; i < deserializedObject.Tags.Count; i++ ) + //// { + //// Assert.AreEqual( targetObject.Tags[ i ].Id, deserializedObject.Tags[ i ].Id ); + //// Assert.Null( deserializedObject.Tags[ i ].Name ); + //// } + } + + [Test] + public void SerializeThenDeserialize_Map() + { + // They are object for just description. + var targetObject = new PhotoEntry + { + Id = 123, + Title = "My photo", + Date = DateTime.Now, + Image = new byte[] { 1, 2, 3, 4 }, + Comment = "This is test object to be serialize/deserialize using MsgPack." + }; + + targetObject.Tags.Add( new PhotoTag { Name = "Sample", Id = 123 } ); + targetObject.Tags.Add( new PhotoTag { Name = "Excellent", Id = 456 } ); + var stream = new MemoryStream(); + + // 1. Create serializer instance. + SerializationContext context = new SerializationContext(); + context.SerializationMethod = SerializationMethod.Map; + context.DefaultDateTimeConversionMethod = DateTimeConversionMethod.Native; + context.BindingOptions.SetIgnoringMembers( typeof( PhotoEntry ), new[] { nameof( PhotoEntry.Image ) } ); + context.BindingOptions.SetIgnoringMembers( typeof( PhotoTag ), new[] { nameof( PhotoTag.Name ) } ); + var serializer = MessagePackSerializer.Get( context ); + + // 2. Serialize object to the specified stream. + serializer.Pack( stream, targetObject ); + + // Set position to head of the stream to demonstrate deserialization. + stream.Position = 0; + + // 3. Deserialize object from the specified stream. + var deserializedObject = serializer.Unpack( stream ); + + Assert.AreEqual( targetObject.Comment, deserializedObject.Comment ); + Assert.AreEqual( targetObject.Id, deserializedObject.Id ); + Assert.AreEqual( targetObject.Date, deserializedObject.Date ); + Assert.AreEqual( targetObject.Title, deserializedObject.Title ); + Assert.Null( deserializedObject.Image ); + Assert.AreEqual( targetObject.Tags.Count, deserializedObject.Tags.Count ); + for ( int i = 0; i < deserializedObject.Tags.Count; i++ ) + { + Assert.AreEqual( targetObject.Tags[ i ].Id, deserializedObject.Tags[ i ].Id ); + Assert.Null( deserializedObject.Tags[ i ].Name ); + } + + SerializationContext newContext = new SerializationContext(); + newContext.SerializationMethod = SerializationMethod.Map; + newContext.DefaultDateTimeConversionMethod = DateTimeConversionMethod.Native; + serializer = MessagePackSerializer.Get( context ); + + // Set position to head of the stream to demonstrate deserialization. + stream.Position = 0; + + // 3. Deserialize object from the specified stream. + deserializedObject = serializer.Unpack( stream ); + + Assert.AreEqual( targetObject.Comment, deserializedObject.Comment ); + Assert.AreEqual( targetObject.Id, deserializedObject.Id ); + Assert.AreEqual( targetObject.Date, deserializedObject.Date ); + Assert.AreEqual( targetObject.Title, deserializedObject.Title ); + Assert.Null( deserializedObject.Image ); + Assert.AreEqual( targetObject.Tags.Count, deserializedObject.Tags.Count ); + for ( int i = 0; i < deserializedObject.Tags.Count; i++ ) + { + Assert.AreEqual( targetObject.Tags[ i ].Id, deserializedObject.Tags[ i ].Id ); + Assert.Null( deserializedObject.Tags[ i ].Name ); + } + } + } + + /// + /// Simple class that will be used for serialization/deserialization. + /// + /// + /// If you want to interop with other platform using SerializationMethod.Array (default), you should use [MessagePackMember]. See Sample06 for details. + /// + public class PhotoEntry + { + public long Id { get; set; } + public string Title { get; set; } + public DateTime Date { get; set; } + public string Comment { get; set; } + public byte[] Image { get; set; } + private readonly List _tags = new List(); + // Note that non-null read-only collection members are OK (of course, collections themselves must not be readonly.) + public IList Tags { get { return this._tags; } } + } + + public class PhotoTag + { + public long Id { get; set; } + + public string Name { get; set; } + } +} diff --git a/test/MsgPack.UnitTest/MessagePackObjectDictionaryTest.cs b/test/MsgPack.UnitTest/MessagePackObjectDictionaryTest.cs index 4e52c253b..46997aae7 100644 --- a/test/MsgPack.UnitTest/MessagePackObjectDictionaryTest.cs +++ b/test/MsgPack.UnitTest/MessagePackObjectDictionaryTest.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -1337,7 +1337,7 @@ public void TestValuesCopyTo() Assert.That( array[ 4 ], Is.EqualTo( MessagePackObject.Nil ) ); } -#if !NETFX_CORE && !SILVERLIGHT && !UNITY && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETFX_CORE && !SILVERLIGHT && !UNITY && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 [Test] public void TestRuntimeSerialization_NotEmpty_RoundTripped() { @@ -1351,7 +1351,7 @@ public void TestRuntimeSerialization_NotEmpty_RoundTripped() Assert.AreEqual( target, deserialized ); } } -#endif // !NETFX_CORE && !SILVERLIGHT && !UNITY && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#endif // !NETFX_CORE && !SILVERLIGHT && !UNITY && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 private sealed class MyClass { } } diff --git a/test/MsgPack.UnitTest/MessagePackObjectTest.Conversion.cs b/test/MsgPack.UnitTest/MessagePackObjectTest.Conversion.cs index 72fbec6f3..1e7688b80 100644 --- a/test/MsgPack.UnitTest/MessagePackObjectTest.Conversion.cs +++ b/test/MsgPack.UnitTest/MessagePackObjectTest.Conversion.cs @@ -50,6 +50,13 @@ private TextWriter Console } } +#if !SILVERLIGHT + private static double GetMicroseconds( Stopwatch sw ) + { + return sw.ElapsedMilliseconds / 1000000.0; + } +#endif // !SILVERLIGHT + [Test] public void TestAsByte() { @@ -59,14 +66,17 @@ public void TestAsByte() TestAsByte( ( Byte )1 ); TestAsByte( Byte.MinValue ); TestAsByte( Byte.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsByte( rand.NextByte() ); } sw.Stop(); - Console.WriteLine( "Byte: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "Byte: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsByte( Byte value ) @@ -113,14 +123,17 @@ public void TestAsSByte() TestAsSByte( ( SByte )1 ); TestAsSByte( SByte.MinValue ); TestAsSByte( SByte.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsSByte( rand.NextSByte() ); } sw.Stop(); - Console.WriteLine( "SByte: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "SByte: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsSByte( SByte value ) @@ -168,14 +181,17 @@ public void TestAsInt16() TestAsInt16( ( Int16 )1 ); TestAsInt16( Int16.MinValue ); TestAsInt16( Int16.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsInt16( rand.NextInt16() ); } sw.Stop(); - Console.WriteLine( "Int16: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "Int16: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsInt16( Int16 value ) @@ -220,14 +236,17 @@ public void TestAsUInt16() TestAsUInt16( ( UInt16 )1 ); TestAsUInt16( UInt16.MinValue ); TestAsUInt16( UInt16.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsUInt16( rand.NextUInt16() ); } sw.Stop(); - Console.WriteLine( "UInt16: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "UInt16: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsUInt16( UInt16 value ) @@ -275,14 +294,17 @@ public void TestAsInt32() TestAsInt32( ( Int32 )1 ); TestAsInt32( Int32.MinValue ); TestAsInt32( Int32.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsInt32( rand.NextInt32() ); } sw.Stop(); - Console.WriteLine( "Int32: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "Int32: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsInt32( Int32 value ) @@ -327,14 +349,17 @@ public void TestAsUInt32() TestAsUInt32( ( UInt32 )1 ); TestAsUInt32( UInt32.MinValue ); TestAsUInt32( UInt32.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsUInt32( rand.NextUInt32() ); } sw.Stop(); - Console.WriteLine( "UInt32: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "UInt32: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsUInt32( UInt32 value ) @@ -382,14 +407,17 @@ public void TestAsInt64() TestAsInt64( ( Int64 )1 ); TestAsInt64( Int64.MinValue ); TestAsInt64( Int64.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsInt64( rand.NextInt64() ); } sw.Stop(); - Console.WriteLine( "Int64: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "Int64: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsInt64( Int64 value ) @@ -421,14 +449,17 @@ public void TestAsUInt64() TestAsUInt64( ( UInt64 )1 ); TestAsUInt64( UInt64.MinValue ); TestAsUInt64( UInt64.MaxValue ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); var rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsUInt64( rand.NextUInt64() ); } sw.Stop(); - Console.WriteLine( "UInt64: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "UInt64: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsUInt64( UInt64 value ) @@ -462,14 +493,17 @@ public void TestAsSingle() TestAsSingle( Single.NaN ); TestAsSingle( Single.NegativeInfinity ); TestAsSingle( Single.PositiveInfinity ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); TestRandom rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsSingle( rand.NextSingle() ); } sw.Stop(); - Console.WriteLine( "Single: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "Single: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsSingle( Single value ) @@ -490,14 +524,17 @@ public void TestAsDouble() TestAsDouble( Double.NaN ); TestAsDouble( Double.NegativeInfinity ); TestAsDouble( Double.PositiveInfinity ); + +#if !SILVERLIGHT var sw = Stopwatch.StartNew(); TestRandom rand = new TestRandom(); - for ( int i = 0; i < 100000; i++ ) + for ( int i = 0; i < 1000; i++ ) { TestAsDouble( rand.NextDouble() ); } sw.Stop(); - Console.WriteLine( "Double: {0:#,0.###} usec/object", sw.Elapsed.Ticks / 1000000.0 ); + Console.WriteLine( "Double: {0:#,0.###} usec/object", GetMicroseconds( sw ) ); +#endif // !SILVERLIGHT } private static void TestAsDouble( Double value ) diff --git a/test/MsgPack.UnitTest/MessagePackObjectTest.Miscs.cs b/test/MsgPack.UnitTest/MessagePackObjectTest.Miscs.cs index f6649e3bd..c30b1d734 100644 --- a/test/MsgPack.UnitTest/MessagePackObjectTest.Miscs.cs +++ b/test/MsgPack.UnitTest/MessagePackObjectTest.Miscs.cs @@ -1,8 +1,8 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // -// Copyright (C) 2010-2012 FUJIWARA, Yusuke +// Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ public void TestToString_ExtendedTypeObject_AsIs() [Test] public void TestToString_AllPossibleTypes_Success() { -#if MONO || XAMDROID +#if MONO || ENABLE_MONO || ( XAMARIN && !AOT ) || UNITY Assert.Inconclusive( "Mono Regex causes StackOverflow... "); #endif TestToStringCore( @@ -247,6 +247,6 @@ public static NUnit.Framework.Constraints.Constraint Match( string regex ) return Is.StringMatching( regex ); } } -#endif // NUNITLITE - } +#endif // NUNITLITE && !NETFX_CORE + } } diff --git a/test/MsgPack.UnitTest/MessagePackObjectTest.RuntimeSerialization.cs b/test/MsgPack.UnitTest/MessagePackObjectTest.RuntimeSerialization.cs index e0ff62bdc..2681b59aa 100644 --- a/test/MsgPack.UnitTest/MessagePackObjectTest.RuntimeSerialization.cs +++ b/test/MsgPack.UnitTest/MessagePackObjectTest.RuntimeSerialization.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -18,7 +18,7 @@ // #endregion -- License Terms -- -#if !NETFX_CORE && !WINDOWS_PHONE && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !NETFX_CORE && !WINDOWS_PHONE && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !SILVERLIGHT && !NETSTANDARD2_0 using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; @@ -171,4 +171,4 @@ private static void TestRuntimeSerializationCore( MessagePackObject target ) } } } -#endif // !NETFX_CORE && !WINDOWS_PHONE && !NETSTANDARD1_1 && !NETSTANDARD1_3 \ No newline at end of file +#endif // !NETFX_CORE && !WINDOWS_PHONE && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 diff --git a/test/MsgPack.UnitTest/MessagePackStringTest.cs b/test/MsgPack.UnitTest/MessagePackStringTest.cs index ba48f758a..86c837465 100644 --- a/test/MsgPack.UnitTest/MessagePackStringTest.cs +++ b/test/MsgPack.UnitTest/MessagePackStringTest.cs @@ -1,4 +1,4 @@ -#region -- License Terms -- +#region -- License Terms -- // // MessagePack for CLI // @@ -20,9 +20,9 @@ using System; using System.Diagnostics; -#if NETFX_35 +#if NET35 using Debug = System.Console; // For missing Debug.WriteLine(String, params Object[]) -#endif // NETFX_35 +#endif // NET35 using System.Security; #if !NETFX_CORE && !WINDOWS_PHONE && !NETSTANDARD1_1 && !NETSTANDARD1_3 using System.Security.Permissions; @@ -139,12 +139,17 @@ public void TestToString_EmptyString() Assert.AreEqual( String.Empty, target.ToString() ); } -#if !UNITY && !SILVERLIGHT && !AOT [Test] public void TestEqualsFullTrust() { var result = TestEqualsCore(); +#if !UNITY && !WINDOWS_PHONE && !NETFX_CORE +#if SILVERLIGHT && !SILVERLIGHT_PRIVILEGED + Assert.That( MessagePackString.IsFastEqualsDisabled, Is.True ); +#else // SILVERLIGHT && !SILVERLIGHT_PRIVILEGED Assert.That( MessagePackString.IsFastEqualsDisabled, Is.False ); +#endif // SILVERLIGHT && !SILVERLIGHT_PRIVILEGED +#endif // !UNITY && !WINDOWS_PHONE && !NETFX_CORE Debug.WriteLine( "TestEqualsFullTrust" ); ShowResult( result ); } @@ -157,9 +162,7 @@ private void ShowResult( Tuple result ) Debug.WriteLine( "Large(100,000 chars) : {0:#,0.0} usec", result.Item4 ); } -#endif // !UNITY && !SILVERLIGHT && !AOT - -#if !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 +#if !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETFX_CORE && !NETSTANDARD2_0 private static StrongName GetStrongName( Type type ) { var assemblyName = type.Assembly.GetName(); @@ -171,7 +174,8 @@ public void TestEqualsPartialTrust() { var appDomainSetUp = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; var evidence = new Evidence(); -#if MONO || NETFX_35 + +#if MONO || NET35 #pragma warning disable 0612 // TODO: patching // currently, Mono does not declare AddHostEvidence @@ -181,7 +185,7 @@ public void TestEqualsPartialTrust() #else evidence.AddHostEvidence( new Zone( SecurityZone.Internet ) ); var permisions = SecurityManager.GetStandardSandbox( evidence ); -#endif // if MONO || NETFX_35 +#endif // if MONO || NET35 AppDomain workerDomain = AppDomain.CreateDomain( "PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName( this.GetType() ), GetStrongName( typeof( Assert ) ) ); try { @@ -200,7 +204,7 @@ public void TestEqualsPartialTrust() } } -#if MONO || NETFX_35 +#if MONO || NET35 private static PermissionSet GetDefaultInternetZoneSandbox() { var permissions = new PermissionSet( PermissionState.None ); @@ -219,9 +223,9 @@ private static PermissionSet GetDefaultInternetZoneSandbox() permissions.AddPermission( new SecurityPermission( SecurityPermissionFlag.Execution -#if NETFX_35 +#if NET35 | SecurityPermissionFlag.SkipVerification -#endif // if NETFX_35 +#endif // if NET35 ) ); permissions.AddPermission( @@ -233,7 +237,7 @@ private static PermissionSet GetDefaultInternetZoneSandbox() return permissions; } -#endif // if MONO || NETFX_35 +#endif // if MONO || NET35 public static void TestEqualsWorker() { @@ -241,7 +245,8 @@ public static void TestEqualsWorker() AppDomain.CurrentDomain.SetData( "TestEqualsWorker.Performance", result ); AppDomain.CurrentDomain.SetData( "MessagePackString.IsFastEqualsDisabled", MessagePackString.IsFastEqualsDisabled ); } -#endif // !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 + +#endif // !SILVERLIGHT && !AOT && !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETFX_CORE && !NETSTANDARD2_0 private static Tuple TestEqualsCore() { @@ -320,7 +325,8 @@ private static Tuple TestEqualsCore() var sw = new Stopwatch(); for ( int i = 0; i < iteration; i++ ) { - sw.Restart(); + sw.Reset(); + sw.Start(); for ( int x = 0; x < values.Length; x++ ) { Assert.That( values[ x ].Equals( null ), Is.False ); @@ -331,7 +337,11 @@ private static Tuple TestEqualsCore() } } sw.Stop(); - tinyAvg = Math.Min( tinyAvg, sw.Elapsed.Ticks * 10.0 / ( values.Length * values.Length ) ); +#if SILVERLIGHT && !WINDOWS_PHONE + tinyAvg = Math.Min( tinyAvg, sw.ElapsedMilliseconds * 1000.0 / ( values.Length * values.Length ) ); +#else + tinyAvg = Math.Min( tinyAvg, sw.Elapsed.Ticks / 10.0 / ( values.Length * values.Length ) ); +#endif } var smallX = new MessagePackString( new String( 'A', 16 ) ); @@ -339,10 +349,15 @@ private static Tuple TestEqualsCore() for ( int i = 0; i < iteration; i++ ) { - sw.Restart(); + sw.Reset(); + sw.Start(); Assert.That( smallX.Equals( smallY ), Is.True ); sw.Stop(); - smallAvg = Math.Min( smallAvg, sw.Elapsed.Ticks * 10.0 ); +#if SILVERLIGHT && !WINDOWS_PHONE + smallAvg = Math.Min( smallAvg, sw.ElapsedMilliseconds * 1000.0 ); +#else + smallAvg = Math.Min( smallAvg, sw.Elapsed.Ticks / 10.0 ); +#endif } var mediumX = new MessagePackString( new String( 'A', 1000 ) ); @@ -350,10 +365,15 @@ private static Tuple TestEqualsCore() for ( int i = 0; i < iteration; i++ ) { - sw.Restart(); + sw.Reset(); + sw.Start(); Assert.That( mediumX.Equals( mediumY ), Is.True ); sw.Stop(); - mediumAvg = Math.Min( mediumAvg, sw.Elapsed.Ticks * 10.0 ); +#if SILVERLIGHT && !WINDOWS_PHONE + mediumAvg = Math.Min( mediumAvg, sw.ElapsedMilliseconds * 1000.0 ); +#else + mediumAvg = Math.Min( mediumAvg, sw.Elapsed.Ticks / 10.0 ); +#endif } var largeX = new MessagePackString( new String( 'A', 100000 ) ); @@ -361,10 +381,15 @@ private static Tuple TestEqualsCore() for ( int i = 0; i < iteration; i++ ) { - sw.Restart(); + sw.Reset(); + sw.Start(); Assert.That( largeX.Equals( largeY ), Is.True ); sw.Stop(); - largeAvg = Math.Min( largeAvg, sw.Elapsed.Ticks * 10.0 ); +#if SILVERLIGHT && !WINDOWS_PHONE + largeAvg = Math.Min( largeAvg, sw.ElapsedMilliseconds * 1000.0 ); +#else + largeAvg = Math.Min( largeAvg, sw.Elapsed.Ticks / 10.0 ); +#endif } return Tuple.Create( tinyAvg, smallAvg, mediumAvg, largeAvg ); diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/AggregateException.cs b/test/MsgPack.UnitTest/Mono/System/AggregateException.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/AggregateException.cs rename to test/MsgPack.UnitTest/Mono/System/AggregateException.cs diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/Threading/AtomicBoolean.cs b/test/MsgPack.UnitTest/Mono/System/Threading/AtomicBoolean.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/Threading/AtomicBoolean.cs rename to test/MsgPack.UnitTest/Mono/System/Threading/AtomicBoolean.cs diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/Threading/Barrier.cs b/test/MsgPack.UnitTest/Mono/System/Threading/Barrier.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/Threading/Barrier.cs rename to test/MsgPack.UnitTest/Mono/System/Threading/Barrier.cs diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/Threading/BarrierPostPhaseException.cs b/test/MsgPack.UnitTest/Mono/System/Threading/BarrierPostPhaseException.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/Threading/BarrierPostPhaseException.cs rename to test/MsgPack.UnitTest/Mono/System/Threading/BarrierPostPhaseException.cs diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/Threading/CountdownEvent.cs b/test/MsgPack.UnitTest/Mono/System/Threading/CountdownEvent.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/Threading/CountdownEvent.cs rename to test/MsgPack.UnitTest/Mono/System/Threading/CountdownEvent.cs diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/Threading/ManualResetEventSlim.cs b/test/MsgPack.UnitTest/Mono/System/Threading/ManualResetEventSlim.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/Threading/ManualResetEventSlim.cs rename to test/MsgPack.UnitTest/Mono/System/Threading/ManualResetEventSlim.cs diff --git a/test/MsgPack.UnitTest.Net35/Mono/System/Threading/SpinWait.cs b/test/MsgPack.UnitTest/Mono/System/Threading/SpinWait.cs similarity index 100% rename from test/MsgPack.UnitTest.Net35/Mono/System/Threading/SpinWait.cs rename to test/MsgPack.UnitTest/Mono/System/Threading/SpinWait.cs diff --git a/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj b/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj index 36e201396..d42dabf3c 100644 --- a/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj +++ b/test/MsgPack.UnitTest/MsgPack.UnitTest.csproj @@ -1,936 +1,438 @@  - + - Debug - AnyCPU - 8.0.30703 - 2.0 {3889C9BE-0473-4B41-80E8-C4C923E837E7} Library - Properties - MsgPack MsgPack.UnitTest - v4.6.1 - 512 - ..\..\ - true - - - - true - full - false - bin\Debug\ - TRACE;DEBUG;SKIP_LARGE_TEST;FEATURE_TAP - prompt - 4 - false - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - true - bin\PerformanceTest\ - DEBUG;TRACE;PERFORMANCE_TEST - full - AnyCPU - prompt - true - true - false + net46;netcoreapp1.0;netcoreapp2.0; + - true - - - ..\..\src\MsgPack.snk - - - bin\Instrument\ - TRACE - true - pdbonly - AnyCPU - prompt - true - true - false + - - bin\CodeAnalysis\ - TRACE - true - pdbonly - AnyCPU - prompt - false - false - false + + + $(DefineConstants);NETSTANDARD1_3 - - bin\CoreProfile\ - TRACE - true - pdbonly - AnyCPU - prompt - false + + + $(DefineConstants);NETSTANDARD2_0 - - - ..\..\packages\NUnit.3.2.1\lib\net45\nunit.framework.dll - True - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + True + True + ByteArrayPackerTest.Allocation.tt + + True True DirectConversionTest.Scalar.tt - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + True True MessagePackObjectTest.Conversion.tt - - + True True MessagePackObjectTest.Equals.Integer.tt - + True True MessagePackObjectTest.Equals.Real.tt - + True True MessagePackObjectTest.Exceptionals.Conversion.tt - - - + True True MessagePackObjectTest.IsTypeOf.Array.tt - - + True True MessagePackObjectTest.IsTypeOf.Integer.tt - + True True MessagePackObjectTest.IsTypeOf.Map.tt - + True True MessagePackObjectTest.IsTypeOf.Raw.tt - - - - - - - - + True True PackerTest.Pack.tt - + True True PackerTest.PackObject.tt - + True True PackerTest.PackT.tt - - - + True True PackUnpackTest.Scalar.tt - - - + ArrayReflectionBasedAutoMessagePackSerializerTest.tt True True - + ArrayReflectionBasedEnumSerializationTest.tt True True - + True True ArrayFieldBasedEnumSerializationTest.tt - + True True ArrayGenerationBasedAutoMessagePackSerializerTest.tt - + True True ArrayGenerationBasedEnumSerializationTest.tt - - + AutoMessagePackSerializerTest.Types.tt - Code True True - - - - - - - - - - - + True True EnumSerializationTest.EnumDefinitions.tt - + True True MapReflectionBasedAutoMessagePackSerializerTest.tt - - - + ReflectionBasedNilImplicationTest.tt True True - + True True FieldBasedNilImplicationTest.tt - - + MapReflectionBasedEnumSerializationTest.tt True True - - - + True True GenerationBasedNilImplicationTest.tt - - - + True True MapFieldBasedEnumSerializationTest.tt - + True True MapGenerationBasedAutoMessagePackSerializerTest.tt - + True True MapGenerationBasedEnumSerializationTest.tt - - - - - - - - - - + True True PreGeneratedSerializerActivator.Types.tt - - - - - - - - - - - + True True VersioningTest.Cases.tt - - - - - + ArrayFieldBasedAutoMessagePackSerializerTest.tt True True - + MapFieldBasedAutoMessagePackSerializerTest.tt True True - - - + + ByteArrayUnpackerTest.Ext.tt + True + True + + + ByteArrayUnpackerTest.Raw.tt + True + True + + + ByteArrayUnpackerTest.Scalar.tt + True + True + + + True + True + TimestampTest.Calculation.tt + + + True + True + TimestampTest.Comparison.tt + + + True + True + TimestampTest.Conversion.tt + + + True + True + TimestampTest.EncodeDecode.tt + + + True + True + TimestampTest.Parse.tt + + + True + True + TimestampTest.Properties.tt + + + True + True + TimestampTest.ToString.tt + + True True UnpackerTest.tt - + + StreamUnpackerTest.Ext.tt + True + True + + True True UnpackerTest.Ext.tt - + + StreamUnpackerTest.Scalar.tt + True + True + + + StreamUnpackerTest.Raw.tt + True + True + + True True UnpackerTest.Skip.tt - + True True UnpackerTest.Object.tt - + True True UnpackerTest.Raw.tt - + True True UnpackerTest.Scalar.tt - + True True UnpackerTest.Skip.Variations.tt - + True True UnpackingTest.Combinations.Array.tt - + True True UnpackingTest.Combinations.Boolean.tt - + True True UnpackingTest.Combinations.Byte.tt - + True True UnpackingTest.Combinations.Double.tt - + True True UnpackingTest.Combinations.Int16.tt - + True True UnpackingTest.Combinations.Int32.tt - + True True UnpackingTest.Combinations.Int64.tt - + True True UnpackingTest.Combinations.Map.tt - + True True UnpackingTest.Combinations.Nil.tt - + True True UnpackingTest.Combinations.Raw.tt - + True True UnpackingTest.Combinations.SByte.tt - + True True UnpackingTest.Combinations.Single.tt - + True True UnpackingTest.Combinations.UInt16.tt - + True True UnpackingTest.Combinations.UInt32.tt - + True True UnpackingTest.Combinations.UInt64.tt - - - + True True TestRandom.tt - - + PackerTest.PackBinary.tt True True - + PackerTest.PackExtendedType.tt True True - + UnpackingTest.Scalar.tt True True - + UnpackingTest.Raw.tt True True - + UnpackingTest.Ext.tt True True @@ -940,6 +442,7 @@ MsgPack.snk + PreserveNewest @@ -949,241 +452,273 @@ PreserveNewest - + + True + True + TimestampTest.EncodeDecode.tt + + TextTemplatingFileGenerator DirectConversionTest.Scalar.cs - + TextTemplatingFileGenerator MessagePackObjectTest.Conversion.cs - + TextTemplatingFileGenerator MessagePackObjectTest.Equals.Integer.cs - + TextTemplatingFileGenerator MessagePackObjectTest.Equals.Real.cs - + TextTemplatingFileGenerator MessagePackObjectTest.Exceptionals.Conversion.cs - + TextTemplatingFileGenerator MessagePackObjectTest.IsTypeOf.Array.cs - + TextTemplatingFileGenerator MessagePackObjectTest.IsTypeOf.Integer.cs - + TextTemplatingFileGenerator MessagePackObjectTest.IsTypeOf.Map.cs - + TextTemplatingFileGenerator MessagePackObjectTest.IsTypeOf.Raw.cs - - + TextTemplatingFileGenerator PackerTest.Pack.cs - + TextTemplatingFileGenerator PackerTest.PackObject.cs - + TextTemplatingFileGenerator PackerTest.PackT.cs - + TextTemplatingFileGenerator PackUnpackTest.Scalar.cs PreserveNewest - + TextTemplatingFileGenerator ArrayReflectionBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator ArrayReflectionBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator ArrayFieldBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator ArrayGenerationBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator ArrayGenerationBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator AutoMessagePackSerializerTest.Types.cs - + TextTemplatingFileGenerator EnumSerializationTest.EnumDefinitions.cs - + TextTemplatingFileGenerator ReflectionBasedNilImplicationTest.cs - + TextTemplatingFileGenerator FieldBasedNilImplicationTest.cs - + TextTemplatingFileGenerator GenerationBasedNilImplicationTest.cs - + TextTemplatingFileGenerator MapReflectionBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator MapReflectionBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator MapFieldBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator MapGenerationBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator MapGenerationBasedEnumSerializationTest.cs - + TextTemplatingFileGenerator PreGeneratedSerializerActivator.Types.cs - + TextTemplatingFileGenerator VersioningTest.Cases.cs - + TextTemplatingFileGenerator ArrayFieldBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator MapFieldBasedAutoMessagePackSerializerTest.cs - + TextTemplatingFileGenerator TestRandom.cs - + + TextTemplatingFileGenerator + TimestampTest.EncodeDecode.cs + + + TextTemplatingFileGenerator + TimestampTest.Calculation.cs + + + TextTemplatingFileGenerator + TimestampTest.Comparison.cs + + + TextTemplatingFileGenerator + TimestampTest.Conversion.cs + + + TextTemplatingFileGenerator + TimestampTest.Parse.cs + + + TextTemplatingFileGenerator + TimestampTest.Properties.cs + + + TextTemplatingFileGenerator + TimestampTest.ToString.cs + + TextTemplatingFileGenerator UnpackerTest.Ext.cs - + TextTemplatingFileGenerator UnpackerTest.Raw.cs - + TextTemplatingFileGenerator UnpackerTest.Scalar.cs - + TextTemplatingFileGenerator UnpackerTest.Skip.Variations.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Array.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Boolean.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Byte.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Double.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Int16.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Int32.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Int64.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Map.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Nil.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Raw.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.SByte.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.Single.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.UInt16.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.UInt32.cs - + TextTemplatingFileGenerator UnpackingTest.Combinations.UInt64.cs - + TextTemplatingFileGenerator PackerTest.PackBinary.cs - + TextTemplatingFileGenerator PackerTest.PackExtendedType.cs - + TextTemplatingFileGenerator UnpackingTest.Scalar.cs - + TextTemplatingFileGenerator UnpackingTest.Raw.cs - + TextTemplatingFileGenerator UnpackingTest.Ext.cs @@ -1193,28 +728,54 @@ - - {5BCEC32E-990E-4DE5-945F-BD27326A7418} - MsgPack - + - - + + TextTemplatingFileGenerator + ByteArrayPackerTest.Allocation.cs + + + + TextTemplatingFileGenerator + StreamUnpackerTest.Scalar.cs + + + TextTemplatingFileGenerator + StreamUnpackerTest.Raw.cs + + + TextTemplatingFileGenerator + StreamUnpackerTest.Ext.cs + + + TextTemplatingFileGenerator + ByteArrayUnpackerTest.Ext.cs + + + TextTemplatingFileGenerator + ByteArrayUnpackerTest.Raw.cs + + + TextTemplatingFileGenerator + ByteArrayUnpackerTest.Scalar.cs + + TextTemplatingFileGenerator UnpackerTest.Skip.cs - - + + TextTemplatingFileGenerator UnpackerTest.Object.cs - - + + TextTemplatingFileGenerator UnpackerTest.cs - + + + + - - {0} : {1}", inner.GetType().ToString(), inner.Message); + } + + return sb.ToString(); + } + + /// + /// Builds up a message, using the Message field of the specified exception + /// as well as any InnerExceptions. + /// + /// The exception. + /// A combined stack trace. + public static string BuildStackTrace(Exception exception) + { + StringBuilder sb = new StringBuilder(GetStackTrace(exception)); + + foreach (Exception inner in FlattenExceptionHierarchy(exception)) + { + sb.Append(NUnit.Env.NewLine); + sb.Append("--"); + sb.Append(inner.GetType().Name); + sb.Append(NUnit.Env.NewLine); + sb.Append(GetStackTrace(inner)); + } + + return sb.ToString(); + } + + /// + /// Gets the stack trace of the exception. + /// + /// The exception. + /// A string representation of the stack trace. + public static string GetStackTrace(Exception exception) + { + try + { + return exception.StackTrace; + } + catch (Exception) + { + return "No stack trace available"; + } + } + + private static List FlattenExceptionHierarchy(Exception exception) + { + var result = new List(); + +#if NET_4_0 || NET_4_5 || SILVERLIGHT || PORTABLE + if (exception is AggregateException) + { + var aggregateException = (exception as AggregateException); + result.AddRange(aggregateException.InnerExceptions); + + foreach (var innerException in aggregateException.InnerExceptions) + result.AddRange(FlattenExceptionHierarchy(innerException)); + } + else +#endif + if (exception.InnerException != null) + { + result.Add(exception.InnerException); + result.AddRange(FlattenExceptionHierarchy(exception.InnerException)); + } + + return result; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CommandBuilder.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CommandBuilder.cs new file mode 100644 index 000000000..50f63b539 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CommandBuilder.cs @@ -0,0 +1,195 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Reflection; +using System.Collections.Generic; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + using Commands; + using Interfaces; + + /// + /// A utility class to create TestCommands + /// + public static class CommandBuilder + { + /// + /// Gets the command to be executed before any of + /// the child tests are run. + /// + /// A TestCommand + public static TestCommand MakeOneTimeSetUpCommand(TestSuite suite, List setUpTearDown, List actions) + { + // Handle skipped tests + if (suite.RunState != RunState.Runnable && suite.RunState != RunState.Explicit) + return MakeSkipCommand(suite); + + // Build the OneTimeSetUpCommand itself + TestCommand command = new OneTimeSetUpCommand(suite, setUpTearDown, actions); + + // Prefix with any IApplyToContext items from attributes + IList changes = null; + + if (suite.TypeInfo != null) + changes = suite.TypeInfo.GetCustomAttributes(true); + else if (suite.Method != null) + changes = suite.Method.GetCustomAttributes(true); + else + { + var testAssembly = suite as TestAssembly; + if (testAssembly != null) +#if PORTABLE + changes = new List(testAssembly.Assembly.GetAttributes()); +#else + changes = (IApplyToContext[])testAssembly.Assembly.GetCustomAttributes(typeof(IApplyToContext), true); +#endif + } + + if (changes != null && changes.Count > 0) + command = new ApplyChangesToContextCommand(command, changes); + + return command; + } + + /// + /// Gets the command to be executed after all of the + /// child tests are run. + /// + /// A TestCommand + public static TestCommand MakeOneTimeTearDownCommand(TestSuite suite, List setUpTearDownItems, List actions) + { + // Build the OneTimeTearDown command itself + TestCommand command = new OneTimeTearDownCommand(suite, setUpTearDownItems, actions); + + // For Theories, follow with TheoryResultCommand to adjust result as needed + if (suite.TestType == "Theory") + command = new TheoryResultCommand(command); + + return command; + } + + /// + /// Creates a test command for use in running this test. + /// + /// + public static TestCommand MakeTestCommand(TestMethod test) + { + // Command to execute test + TestCommand command = new TestMethodCommand(test); + + // Add any wrappers to the TestMethodCommand + foreach (IWrapTestMethod wrapper in test.Method.GetCustomAttributes(true)) + command = wrapper.Wrap(command); + + // Wrap in TestActionCommand + command = new TestActionCommand(command); + + // Wrap in SetUpTearDownCommand + command = new SetUpTearDownCommand(command); + + // Add wrappers that apply before setup and after teardown + foreach (ICommandWrapper decorator in test.Method.GetCustomAttributes(true)) + command = decorator.Wrap(command); + + // Add command to set up context using attributes that implement IApplyToContext + IApplyToContext[] changes = test.Method.GetCustomAttributes(true); + if (changes.Length > 0) + command = new ApplyChangesToContextCommand(command, changes); + + return command; + } + + /// + /// Creates a command for skipping a test. The result returned will + /// depend on the test RunState. + /// + public static SkipCommand MakeSkipCommand(Test test) + { + return new SkipCommand(test); + } + + /// + /// Builds the set up tear down list. + /// + /// Type of the fixture. + /// Type of the set up attribute. + /// Type of the tear down attribute. + /// A list of SetUpTearDownItems + public static List BuildSetUpTearDownList(Type fixtureType, Type setUpType, Type tearDownType) + { + var setUpMethods = Reflect.GetMethodsWithAttribute(fixtureType, setUpType, true); + var tearDownMethods = Reflect.GetMethodsWithAttribute(fixtureType, tearDownType, true); + + var list = new List(); + + while (fixtureType != null && !fixtureType.Equals(typeof(object))) + { + var node = BuildNode(fixtureType, setUpMethods, tearDownMethods); + if (node.HasMethods) + list.Add(node); + + fixtureType = fixtureType.GetTypeInfo().BaseType; + } + + return list; + } + + // This method builds a list of nodes that can be used to + // run setup and teardown according to the NUnit specs. + // We need to execute setup and teardown methods one level + // at a time. However, we can't discover them by reflection + // one level at a time, because that would cause overridden + // methods to be called twice, once on the base class and + // once on the derived class. + // + // For that reason, we start with a list of all setup and + // teardown methods, found using a single reflection call, + // and then descend through the inheritance hierarchy, + // adding each method to the appropriate level as we go. + private static SetUpTearDownItem BuildNode(Type fixtureType, IList setUpMethods, IList tearDownMethods) + { + // Create lists of methods for this level only. + // Note that FindAll can't be used because it's not + // available on all the platforms we support. + var mySetUpMethods = SelectMethodsByDeclaringType(fixtureType, setUpMethods); + var myTearDownMethods = SelectMethodsByDeclaringType(fixtureType, tearDownMethods); + + return new SetUpTearDownItem(mySetUpMethods, myTearDownMethods); + } + + private static List SelectMethodsByDeclaringType(Type type, IList methods) + { + var list = new List(); + + foreach (var method in methods) + if (method.DeclaringType == type) + list.Add(method); + + return list; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CompositeWorkItem.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CompositeWorkItem.cs new file mode 100644 index 000000000..6ee7ed848 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CompositeWorkItem.cs @@ -0,0 +1,430 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Reflection; +using NUnit.Compatibility; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// A CompositeWorkItem represents a test suite and + /// encapsulates the execution of the suite as well + /// as all its child tests. + /// + public class CompositeWorkItem : WorkItem + { + // static Logger log = InternalTrace.GetLogger("CompositeWorkItem"); + + private TestSuite _suite; + private TestSuiteResult _suiteResult; + private ITestFilter _childFilter; + private TestCommand _setupCommand; + private TestCommand _teardownCommand; + private List _children; + + /// + /// List of Child WorkItems + /// + public List Children + { + get { return _children; } + private set { _children = value; } + } + + /// + /// A count of how many tests in the work item have a value for the Order Property + /// + private int _countOrder; + + private CountdownEvent _childTestCountdown; + + /// + /// Construct a CompositeWorkItem for executing a test suite + /// using a filter to select child tests. + /// + /// The TestSuite to be executed + /// A filter used to select child tests + public CompositeWorkItem(TestSuite suite, ITestFilter childFilter) + : base(suite) + { + _suite = suite; + _suiteResult = Result as TestSuiteResult; + _childFilter = childFilter; + _countOrder = 0; + } + + /// + /// Method that actually performs the work. Overridden + /// in CompositeWorkItem to do setup, run all child + /// items and then do teardown. + /// + protected override void PerformWork() + { + // Inititialize actions, setup and teardown + // We can't do this in the constructor because + // the context is not available at that point. + InitializeSetUpAndTearDownCommands(); + + if (!CheckForCancellation()) + if (Test.RunState == RunState.Explicit && !_childFilter.IsExplicitMatch(Test)) + SkipFixture(ResultState.Explicit, GetSkipReason(), null); + else + switch (Test.RunState) + { + default: + case RunState.Runnable: + case RunState.Explicit: + // Assume success, since the result will be inconclusive + // if there is no setup method to run or if the + // context initialization fails. + Result.SetResult(ResultState.Success); + + CreateChildWorkItems(); + + if (_children.Count > 0) + { + PerformOneTimeSetUp(); + + if (!CheckForCancellation()) + switch (Result.ResultState.Status) + { + case TestStatus.Passed: + RunChildren(); + return; + // Just return: completion event will take care + // of TestFixtureTearDown when all tests are done. + + case TestStatus.Skipped: + case TestStatus.Inconclusive: + case TestStatus.Failed: + SkipChildren(_suite, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message); + break; + } + + // Directly execute the OneTimeFixtureTearDown for tests that + // were skipped, failed or set to inconclusive in one time setup + // unless we are aborting. + if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) + PerformOneTimeTearDown(); + } + break; + + case RunState.Skipped: + SkipFixture(ResultState.Skipped, GetSkipReason(), null); + break; + + case RunState.Ignored: + SkipFixture(ResultState.Ignored, GetSkipReason(), null); + break; + + case RunState.NotRunnable: + SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace()); + break; + } + + // Fall through in case nothing was run. + // Otherwise, this is done in the completion event. + WorkItemComplete(); + + } + + #region Helper Methods + + private bool CheckForCancellation() + { + if (Context.ExecutionStatus != TestExecutionStatus.Running) + { + Result.SetResult(ResultState.Cancelled, "Test cancelled by user"); + return true; + } + + return false; + } + + private void InitializeSetUpAndTearDownCommands() + { + List setUpTearDownItems = _suite.TypeInfo != null + ? CommandBuilder.BuildSetUpTearDownList(_suite.TypeInfo.Type, typeof(OneTimeSetUpAttribute), typeof(OneTimeTearDownAttribute)) + : new List(); + + var actionItems = new List(); + foreach (ITestAction action in Actions) + { + // Special handling here for ParameterizedMethodSuite is a bit ugly. However, + // it is needed because Tests are not supposed to know anything about Action + // Attributes (or any attribute) and Attributes don't know where they were + // initially applied unless we tell them. + // + // ParameterizedMethodSuites and individual test cases both use the same + // MethodInfo as a source of attributes. We handle the Test and Default targets + // in the test case, so we don't want to doubly handle it here. + bool applyToSuite = (action.Targets & ActionTargets.Suite) == ActionTargets.Suite + || action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite); + + bool applyToTest = (action.Targets & ActionTargets.Test) == ActionTargets.Test + && !(Test is ParameterizedMethodSuite); + + if (applyToSuite) + actionItems.Add(new TestActionItem(action)); + + if (applyToTest) + Context.UpstreamActions.Add(action); + } + + _setupCommand = CommandBuilder.MakeOneTimeSetUpCommand(_suite, setUpTearDownItems, actionItems); + _teardownCommand = CommandBuilder.MakeOneTimeTearDownCommand(_suite, setUpTearDownItems, actionItems); + } + + private void PerformOneTimeSetUp() + { + try + { + _setupCommand.Execute(Context); + + // SetUp may have changed some things in the environment + Context.UpdateContextFromEnvironment(); + } + catch (Exception ex) + { + if (ex is NUnitException || ex is TargetInvocationException) + ex = ex.InnerException; + + Result.RecordException(ex, FailureSite.SetUp); + } + } + + private void RunChildren() + { + int childCount = _children.Count; + if (childCount == 0) + throw new InvalidOperationException("RunChildren called but item has no children"); + + _childTestCountdown = new CountdownEvent(childCount); + + foreach (WorkItem child in _children) + { + if (CheckForCancellation()) + break; + + child.Completed += new EventHandler(OnChildCompleted); + child.InitializeContext(new TestExecutionContext(Context)); + + Context.Dispatcher.Dispatch(child); + childCount--; + } + + if (childCount > 0) + { + while (childCount-- > 0) + CountDownChildTest(); + } + } + + private void CreateChildWorkItems() + { + _children = new List(); + + foreach (ITest test in _suite.Tests) + { + if (_childFilter.Pass(test)) + { + var child = WorkItem.CreateWorkItem(test, _childFilter); + child.WorkerId = this.WorkerId; + +#if !PORTABLE && !SILVERLIGHT && !NETCF + if (child.TargetApartment == ApartmentState.Unknown && TargetApartment != ApartmentState.Unknown) + child.TargetApartment = TargetApartment; +#endif + + if (test.Properties.ContainsKey(PropertyNames.Order)) + { + _children.Insert(0, child); + _countOrder++; + } + else + { + _children.Add(child); + } + } + } + + if (_countOrder !=0) SortChildren(); + } + + private class WorkItemOrderComparer : IComparer + { + /// + /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. + /// + /// + /// A signed integer that indicates the relative values of and , as shown in the following table.Value Meaning Less than zero is less than .Zero equals .Greater than zero is greater than . + /// + /// The first object to compare.The second object to compare. + public int Compare(WorkItem x, WorkItem y) + { + var xKey = int.MaxValue; + var yKey = int.MaxValue; + + if (x.Test.Properties.ContainsKey(PropertyNames.Order)) + xKey =(int)x.Test.Properties[PropertyNames.Order][0]; + + if (y.Test.Properties.ContainsKey(PropertyNames.Order)) + yKey =(int)y.Test.Properties[PropertyNames.Order][0]; + + return xKey.CompareTo(yKey); + } + } + + /// + /// Sorts tests under this suite. + /// + private void SortChildren() + { + _children.Sort(0, _countOrder, new WorkItemOrderComparer()); + } + + private void SkipFixture(ResultState resultState, string message, string stackTrace) + { + Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.Filter(stackTrace)); + SkipChildren(_suite, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message); + } + + private void SkipChildren(TestSuite suite, ResultState resultState, string message) + { + foreach (Test child in suite.Tests) + { + if (_childFilter.Pass(child)) + { + TestResult childResult = child.MakeTestResult(); + childResult.SetResult(resultState, message); + _suiteResult.AddResult(childResult); + + // Some runners may depend on getting the TestFinished event + // even for tests that have been skipped at a higher level. + Context.Listener.TestFinished(childResult); + + if (child.IsSuite) + SkipChildren((TestSuite)child, resultState, message); + } + } + } + + private void PerformOneTimeTearDown() + { + // Our child tests or even unrelated tests may have + // executed on the same thread since the time that + // this test started, so we have to re-establish + // the proper execution environment + this.Context.EstablishExecutionEnvironment(); + + _teardownCommand.Execute(this.Context); + } + + private string GetSkipReason() + { + return (string)Test.Properties.Get(PropertyNames.SkipReason); + } + + private string GetProviderStackTrace() + { + return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace); + } + + private object _completionLock = new object(); + + private void OnChildCompleted(object sender, EventArgs e) + { + lock (_completionLock) + { + WorkItem childTask = sender as WorkItem; + if (childTask != null) + { + childTask.Completed -= new EventHandler(OnChildCompleted); + _suiteResult.AddResult(childTask.Result); + + if (Context.StopOnError && childTask.Result.ResultState.Status == TestStatus.Failed) + Context.ExecutionStatus = TestExecutionStatus.StopRequested; + + // Check to see if all children completed + CountDownChildTest(); + } + } + } + + private void CountDownChildTest() + { + _childTestCountdown.Signal(); + if (_childTestCountdown.CurrentCount == 0) + { + if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) + PerformOneTimeTearDown(); + + foreach (var childResult in _suiteResult.Children) + if (childResult.ResultState == ResultState.Cancelled) + { + this.Result.SetResult(ResultState.Cancelled, "Cancelled by user"); + break; + } + + WorkItemComplete(); + } + } + + private static bool IsStaticClass(Type type) + { + return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed; + } + + private object cancelLock = new object(); + + /// + /// Cancel (abort or stop) a CompositeWorkItem and all of its children + /// + /// true if the CompositeWorkItem and all of its children should be aborted, false if it should allow all currently running tests to complete + public override void Cancel(bool force) + { + lock (cancelLock) + { + if (_children == null) + return; + + foreach (var child in _children) + { + var ctx = child.Context; + if (ctx != null) + ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; + + if (child.State == WorkItemState.Running) + child.Cancel(force); + } + } + } + + #endregion + } +} diff --git a/test/NUnitLite/src/framework/Internal/WorkItems/CountdownEvent.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs similarity index 97% rename from test/NUnitLite/src/framework/Internal/WorkItems/CountdownEvent.cs rename to test/NUnitLite/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs index 3c7c7c799..afef3a158 100644 --- a/test/NUnitLite/src/framework/Internal/WorkItems/CountdownEvent.cs +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs @@ -21,10 +21,10 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if !CLR_4_0 || SILVERLIGHT +#if !NET_4_0 && !NET_4_5 || SILVERLIGHT using System.Threading; -namespace NUnit.Framework.Internal.WorkItems +namespace NUnit.Framework.Internal.Execution { /// /// A simplified implementation of .NET 4 CountdownEvent diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventListenerTextWriter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventListenerTextWriter.cs new file mode 100644 index 000000000..af26ed27d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventListenerTextWriter.cs @@ -0,0 +1,103 @@ +// *********************************************************************** +// Copyright (c) 2007-2016 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if !NETCF && !SILVERLIGHT && !PORTABLE +using System; +using System.IO; +using System.Text; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// EventListenerTextWriter sends text output to the currently active + /// ITestEventListener in the form of a TestOutput object. If no event + /// listener is active in the contet, or if there is no context, + /// the output is forwarded to the supplied default writer. + /// + public class EventListenerTextWriter : TextWriter + { + private TextWriter _defaultWriter; + private string _streamName; + + /// + /// Construct an EventListenerTextWriter + /// + /// The name of the stream to use for events + /// The default writer to use if no listener is available + public EventListenerTextWriter( string streamName, TextWriter defaultWriter ) + { + _streamName = streamName; + _defaultWriter = defaultWriter; + } + + /// + /// Write a single char + /// + override public void Write(char aChar) + { + if (!TrySendToListener(aChar.ToString())) + _defaultWriter.Write(aChar); + } + + /// + /// Write a string + /// + override public void Write(string aString) + { + if (!TrySendToListener(aString)) + _defaultWriter.Write(aString); + } + + /// + /// Write a string followed by a newline + /// + override public void WriteLine(string aString) + { + if (!TrySendToListener(aString + Environment.NewLine)) + _defaultWriter.WriteLine(aString); + } + + /// + /// Get the Encoding for this TextWriter + /// + override public System.Text.Encoding Encoding + { + get { return Encoding.Default; } + } + + private bool TrySendToListener(string text) + { + var context = TestExecutionContext.GetTestExecutionContext(); + if (context == null || context.Listener == null) + return false; + + string testName = context.CurrentTest != null + ? context.CurrentTest.FullName + : null; + context.Listener.TestOutput(new TestOutput(text, _streamName, testName)); + return true; + } + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventPump.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventPump.cs new file mode 100644 index 000000000..f02458fd0 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventPump.cs @@ -0,0 +1,207 @@ +// *********************************************************************** +// Copyright (c) 2006-2016 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using System.Threading; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// The EventPumpState enum represents the state of an + /// EventPump. + /// + public enum EventPumpState + { + /// + /// The pump is stopped + /// + Stopped, + + /// + /// The pump is pumping events with no stop requested + /// + Pumping, + + /// + /// The pump is pumping events but a stop has been requested + /// + Stopping + } + + /// + /// EventPump pulls events out of an EventQueue and sends + /// them to a listener. It is used to send events back to + /// the client without using the CallContext of the test + /// runner thread. + /// + public class EventPump : IDisposable + { + static readonly Logger log = InternalTrace.GetLogger("EventPump"); + + #region Instance Variables + + /// + /// The downstream listener to which we send events + /// + private readonly ITestListener _eventListener; + + /// + /// The queue that holds our events + /// + private readonly EventQueue _events; + + /// + /// Thread to do the pumping + /// + private Thread _pumpThread; + + /// + /// The current state of the eventpump + /// + private int _pumpState = (int)EventPumpState.Stopped; + + #endregion + + #region Constructor + /// + /// Constructor + /// + /// The EventListener to receive events + /// The event queue to pull events from + public EventPump( ITestListener eventListener, EventQueue events) + { + _eventListener = eventListener; + _events = events; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the current state of the pump + /// + public EventPumpState PumpState + { + get + { + return (EventPumpState)_pumpState; + } + } + + /// + /// Gets or sets the name of this EventPump + /// (used only internally and for testing). + /// + public string Name { get; set; } + + #endregion + + #region Public Methods + + /// + /// Dispose stops the pump + /// Disposes the used WaitHandle, too. + /// + public void Dispose() + { + Stop(); + } + + /// + /// Start the pump + /// + public void Start() + { + if ( Interlocked.CompareExchange (ref _pumpState, (int)EventPumpState.Pumping, (int)EventPumpState.Stopped) == (int)EventPumpState.Stopped) // Ignore if already started + { + _pumpThread = new Thread (PumpThreadProc) + { + Name = "EventPumpThread" + Name, + Priority = ThreadPriority.Highest + }; + + _pumpThread.Start(); + } + } + + /// + /// Tell the pump to stop after emptying the queue. + /// + public void Stop() + { + if (Interlocked.CompareExchange (ref _pumpState, (int)EventPumpState.Stopping, (int)EventPumpState.Pumping) == (int)EventPumpState.Pumping) + { + _events.Stop(); + _pumpThread.Join(); + } + } + #endregion + + #region PumpThreadProc + + /// + /// Our thread proc for removing items from the event + /// queue and sending them on. Note that this would + /// need to do more locking if any other thread were + /// removing events from the queue. + /// + private void PumpThreadProc() + { + //ITestListener hostListeners = CoreExtensions.Host.Listeners; + try + { + while (true) + { + Event e = _events.Dequeue( PumpState == EventPumpState.Pumping ); + if ( e == null ) + break; + try + { + e.Send(_eventListener); + //e.Send(hostListeners); + } + catch (Exception ex) + { + log.Error( "Exception in event handler\r\n {0}", ex ); + } + } + } + catch (Exception ex) + { + log.Error( "Exception in pump thread", ex ); + } + finally + { + _pumpState = (int)EventPumpState.Stopped; + //pumpThread = null; + if (_events.Count > 0) + log.Error("Event pump thread exiting with {0} events remaining"); + } + } + #endregion + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventQueue.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventQueue.cs new file mode 100644 index 000000000..4c3aaa5ff --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/EventQueue.cs @@ -0,0 +1,291 @@ +// *********************************************************************** +// Copyright (c) 2007-2016 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Globalization; +using System.Runtime.Serialization; +using System.Threading; +#if NET_2_0 || NET_3_5 || NETCF +using ManualResetEventSlim = System.Threading.ManualResetEvent; +#endif +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + +#region Individual Event Classes + + /// + /// NUnit.Core.Event is the abstract base for all stored events. + /// An Event is the stored representation of a call to the + /// ITestListener interface and is used to record such calls + /// or to queue them for forwarding on another thread or at + /// a later time. + /// + public abstract class Event + { + /// + /// The Send method is implemented by derived classes to send the event to the specified listener. + /// + /// The listener. + public abstract void Send(ITestListener listener); + } + + /// + /// TestStartedEvent holds information needed to call the TestStarted method. + /// + public class TestStartedEvent : Event + { + private readonly ITest _test; + + /// + /// Initializes a new instance of the class. + /// + /// The test. + public TestStartedEvent(ITest test) + { + _test = test; + } + + /// + /// Calls TestStarted on the specified listener. + /// + /// The listener. + public override void Send(ITestListener listener) + { + listener.TestStarted(_test); + } + } + + /// + /// TestFinishedEvent holds information needed to call the TestFinished method. + /// + public class TestFinishedEvent : Event + { + private readonly ITestResult _result; + + /// + /// Initializes a new instance of the class. + /// + /// The result. + public TestFinishedEvent(ITestResult result) + { + _result = result; + } + + /// + /// Calls TestFinished on the specified listener. + /// + /// The listener. + public override void Send(ITestListener listener) + { + listener.TestFinished(_result); + } + } + + /// + /// TestOutputEvent holds information needed to call the TestOutput method. + /// + public class TestOutputEvent : Event + { + private readonly TestOutput _output; + + /// + /// Initializes a new instance of the class. + /// + /// The output object. + public TestOutputEvent(TestOutput output) + { + _output = output; + } + + /// + /// Calls TestOutput on the specified listener. + /// + /// The listener. + public override void Send(ITestListener listener) + { + listener.TestOutput(_output); + } + } + + #endregion + + /// + /// Implements a queue of work items each of which + /// is queued as a WaitCallback. + /// + public class EventQueue + { + private const int spinCount = 5; + +// static readonly Logger log = InternalTrace.GetLogger("EventQueue"); + + private readonly ConcurrentQueue _queue = new ConcurrentQueue(); + + /* This event is used solely for the purpose of having an optimized sleep cycle when + * we have to wait on an external event (Add or Remove for instance) + */ + private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false); + + /* The whole idea is to use these two values in a transactional + * way to track and manage the actual data inside the underlying lock-free collection + * instead of directly working with it or using external locking. + * + * They are manipulated with CAS and are guaranteed to increase over time and use + * of the instance thus preventing ABA problems. + */ + private int _addId = int.MinValue; + private int _removeId = int.MinValue; + + private int _stopped; + + /// + /// Gets the count of items in the queue. + /// + public int Count + { + get + { + return _queue.Count; + } + } + + /// + /// Enqueues the specified event + /// + /// The event to enqueue. + public void Enqueue(Event e) + { + do + { + int cachedAddId = _addId; + + // Validate that we have are the current enqueuer + if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId) + continue; + + // Add to the collection + _queue.Enqueue(e); + + // Wake up threads that may have been sleeping + _mreAdd.Set(); + + break; + } while (true); + + Thread.Sleep(1); // give EventPump thread a chance to process the event + } + + /// + /// Removes the first element from the queue and returns it (or null). + /// + /// + /// If true and the queue is empty, the calling thread is blocked until + /// either an element is enqueued, or is called. + /// + /// + /// + /// + /// If the queue not empty + /// the first element. + /// + /// + /// otherwise, if ==false + /// or has been called + /// null. + /// + /// + /// + public Event Dequeue(bool blockWhenEmpty) + { + SpinWait sw = new SpinWait(); + + do + { + int cachedRemoveId = _removeId; + int cachedAddId = _addId; + + // Empty case + if (cachedRemoveId == cachedAddId) + { + if (!blockWhenEmpty || _stopped != 0) + return null; + + // Spin a few times to see if something changes + if (sw.Count <= spinCount) + { + sw.SpinOnce(); + } + else + { + // Reset to wait for an enqueue + _mreAdd.Reset(); + + // Recheck for an enqueue to avoid a Wait + if (cachedRemoveId != _removeId || cachedAddId != _addId) + { + // Queue is not empty, set the event + _mreAdd.Set(); + continue; + } + + // Wait for something to happen + _mreAdd.Wait(500); + } + + continue; + } + + // Validate that we are the current dequeuer + if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId) + continue; + + + // Dequeue our work item + Event e; + while (!_queue.TryDequeue (out e)) + { + if (!blockWhenEmpty || _stopped != 0) + return null; + } + + return e; + } while (true); + } + + /// + /// Stop processing of the queue + /// + public void Stop() + { + if (Interlocked.CompareExchange(ref _stopped, 1, 0) == 0) + _mreAdd.Set(); + } + } +} + +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/IWorkItemDispatcher.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/IWorkItemDispatcher.cs new file mode 100644 index 000000000..a7d4502f1 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/IWorkItemDispatcher.cs @@ -0,0 +1,46 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// An IWorkItemDispatcher handles execution of work items. + /// + public interface IWorkItemDispatcher + { + /// + /// Dispatch a single work item for execution. The first + /// work item dispatched is saved as the top-level + /// work item and used when stopping the run. + /// + /// The item to dispatch + void Dispatch(WorkItem work); + + /// + /// Cancel the ongoing run completely. + /// If no run is in process, the call has no effect. + /// + /// true if the IWorkItemDispatcher should abort all currently running WorkItems, false if it should allow all currently running WorkItems to complete + void CancelRun(bool force); + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs new file mode 100644 index 000000000..eb6bb1b57 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs @@ -0,0 +1,278 @@ +// *********************************************************************** +// Copyright (c) 2012-2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using System.Collections.Generic; +using System.Threading; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// ParallelWorkItemDispatcher handles execution of work items by + /// queuing them for worker threads to process. + /// + public class ParallelWorkItemDispatcher : IWorkItemDispatcher + { + private static readonly Logger log = InternalTrace.GetLogger("WorkItemDispatcher"); + + private readonly int _levelOfParallelism; + private int _itemsDispatched; + + // Non-STA + private readonly WorkShift _parallelShift = new WorkShift("Parallel"); + private readonly WorkShift _nonParallelShift = new WorkShift("NonParallel"); + private readonly Lazy _parallelQueue; + private readonly Lazy _nonParallelQueue; + + // STA +#if !NETCF + private readonly WorkShift _nonParallelSTAShift = new WorkShift("NonParallelSTA"); + private readonly Lazy _parallelSTAQueue; + private readonly Lazy _nonParallelSTAQueue; +#endif + + // The first WorkItem to be dispatched, assumed to be top-level item + private WorkItem _topLevelWorkItem; + + /// + /// Construct a ParallelWorkItemDispatcher + /// + /// Number of workers to use + public ParallelWorkItemDispatcher(int levelOfParallelism) + { + _levelOfParallelism = levelOfParallelism; + + Shifts = new WorkShift[] + { + _parallelShift, + _nonParallelShift, +#if !NETCF + _nonParallelSTAShift +#endif + }; + foreach (var shift in Shifts) + shift.EndOfShift += OnEndOfShift; + + _parallelQueue = new Lazy(() => + { + var parallelQueue = new WorkItemQueue("ParallelQueue"); + _parallelShift.AddQueue(parallelQueue); + + for (int i = 1; i <= _levelOfParallelism; i++) + { + string name = string.Format("Worker#" + i.ToString()); +#if NETCF + _parallelShift.Assign(new TestWorker(parallelQueue, name)); +#else + _parallelShift.Assign(new TestWorker(parallelQueue, name, ApartmentState.MTA)); +#endif + } + + return parallelQueue; + }); + +#if !NETCF + _parallelSTAQueue = new Lazy(() => + { + var parallelSTAQueue = new WorkItemQueue("ParallelSTAQueue"); + _parallelShift.AddQueue(parallelSTAQueue); + _parallelShift.Assign(new TestWorker(parallelSTAQueue, "Worker#STA", ApartmentState.STA)); + + return parallelSTAQueue; + }); +#endif + + _nonParallelQueue = new Lazy(() => + { + var nonParallelQueue = new WorkItemQueue("NonParallelQueue"); + _nonParallelShift.AddQueue(nonParallelQueue); +#if NETCF + _nonParallelShift.Assign(new TestWorker(nonParallelQueue, "Worker#NP")); +#else + _nonParallelShift.Assign(new TestWorker(nonParallelQueue, "Worker#STA_NP", ApartmentState.MTA)); +#endif + + return nonParallelQueue; + }); + +#if !NETCF + _nonParallelSTAQueue = new Lazy(() => + { + var nonParallelSTAQueue = new WorkItemQueue("NonParallelSTAQueue"); + _nonParallelSTAShift.AddQueue(nonParallelSTAQueue); + _nonParallelSTAShift.Assign(new TestWorker(nonParallelSTAQueue, "Worker#NP_STA", ApartmentState.STA)); + + return nonParallelSTAQueue; + }); +#endif + } + + /// + /// Enumerates all the shifts supported by the dispatcher + /// + public IEnumerable Shifts { get; private set; } + + #region IWorkItemDispatcher Members + + /// + /// Dispatch a single work item for execution. The first + /// work item dispatched is saved as the top-level + /// work item and used when stopping the run. + /// + /// The item to dispatch + public void Dispatch(WorkItem work) + { + // Special handling of the top-level item + if (Interlocked.CompareExchange (ref _topLevelWorkItem, work, null) == null) + { + Enqueue(work); + StartNextShift(); + } + // We run child items directly, rather than enqueuing them... + // 1. If the context is single threaded. + // 2. If there is no fixture, and so nothing to do but dispatch grandchildren. + // 3. For now, if this represents a test case. This avoids issues of + // tests that access the fixture state and allows handling ApartmentState + // preferences set on the fixture. + else if (work.Context.IsSingleThreaded + || work.Test.TypeInfo == null + || work is SimpleWorkItem) + Execute(work); + else + Enqueue(work); + + Interlocked.Increment(ref _itemsDispatched); + } + + private void Execute(WorkItem work) + { + log.Debug("Directly executing {0}", work.Test.Name); + work.Execute(); + } + + private void Enqueue(WorkItem work) + { + log.Debug("Enqueuing {0}", work.Test.Name); + + if (work.IsParallelizable) + { +#if !NETCF + if (work.TargetApartment == ApartmentState.STA) + ParallelSTAQueue.Enqueue(work); + else +#endif + ParallelQueue.Enqueue(work); + } +#if !NETCF + else if (work.TargetApartment == ApartmentState.STA) + NonParallelSTAQueue.Enqueue(work); +#endif + else + NonParallelQueue.Enqueue(work); + } + + /// + /// Cancel the ongoing run completely. + /// If no run is in process, the call has no effect. + /// + public void CancelRun(bool force) + { + foreach (var shift in Shifts) + shift.Cancel(force); + } + + #endregion + + #region Private Queue Properties + + // Queues are not actually created until the first time the property + // is referenced by the Dispatch method adding a WorkItem to it. + + private WorkItemQueue ParallelQueue + { + get + { + return _parallelQueue.Value; + } + } + +#if !NETCF + private WorkItemQueue ParallelSTAQueue + { + get + { + return _parallelSTAQueue.Value; + } + } +#endif + + private WorkItemQueue NonParallelQueue + { + get + { + return _nonParallelQueue.Value; + } + } + +#if !NETCF + private WorkItemQueue NonParallelSTAQueue + { + get + { + return _nonParallelSTAQueue.Value; + } + } +#endif + #endregion + + #region Helper Methods + + private void OnEndOfShift(object sender, EventArgs ea) + { + if (!StartNextShift()) + { + foreach (var shift in Shifts) + shift.ShutDown(); + } + } + + private bool StartNextShift() + { + foreach (var shift in Shifts) + { + if (shift.HasWork) + { + shift.Start(); + return true; + } + } + + return false; + } + + #endregion + } +} + +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/QueuingEventListener.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/QueuingEventListener.cs new file mode 100644 index 000000000..3d2877647 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/QueuingEventListener.cs @@ -0,0 +1,80 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// QueuingEventListener uses an EventQueue to store any + /// events received on its EventListener interface. + /// + public class QueuingEventListener : ITestListener + { + /// + /// The EventQueue created and filled by this listener + /// + public EventQueue Events { get; private set; } + + /// + /// Construct a QueuingEventListener + /// + public QueuingEventListener() + { + Events = new EventQueue(); + } + + #region EventListener Methods + /// + /// A test has started + /// + /// The test that is starting + public void TestStarted(ITest test) + { + Events.Enqueue( new TestStartedEvent( test ) ); + } + + /// + /// A test case finished + /// + /// Result of the test case + public void TestFinished(ITestResult result) + { + Events.Enqueue( new TestFinishedEvent( result ) ); + } + + /// + /// Called when a test produces output for immediate display + /// + /// A TestOutput object containing the text to display + public void TestOutput(TestOutput output) + { + Events.Enqueue(new TestOutputEvent(output)); + } + + #endregion + } +} +#endif diff --git a/test/NUnitLite/src/framework/Internal/WorkItems/SimpleWorkItem.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs similarity index 80% rename from test/NUnitLite/src/framework/Internal/WorkItems/SimpleWorkItem.cs rename to test/NUnitLite/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs index f18bc19cc..004760583 100644 --- a/test/NUnitLite/src/framework/Internal/WorkItems/SimpleWorkItem.cs +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs @@ -23,9 +23,10 @@ using System; using System.Threading; +using NUnit.Framework.Interfaces; using NUnit.Framework.Internal.Commands; -namespace NUnit.Framework.Internal.WorkItems +namespace NUnit.Framework.Internal.Execution { /// /// A SimpleWorkItem represents a single test case and is @@ -40,18 +41,12 @@ public class SimpleWorkItem : WorkItem /// Construct a simple work item for a test. /// /// The test to be executed - public SimpleWorkItem(TestMethod test) : base(test) + /// The filter used to select this test + public SimpleWorkItem(TestMethod test, ITestFilter filter) : base(test) { - _command = test.MakeTestCommand(); - } - - /// - /// Construct a simple work item for a test command. - /// - /// The command to be executed - public SimpleWorkItem(TestCommand command) : base(command.Test) - { - _command = command; + _command = test.RunState == RunState.Runnable || test.RunState == RunState.Explicit && filter.IsExplicitMatch(test) + ? CommandBuilder.MakeTestCommand(test) + : CommandBuilder.MakeSkipCommand(test); } /// @@ -61,7 +56,7 @@ protected override void PerformWork() { try { - testResult = _command.Execute(Context); + Result = _command.Execute(Context); } finally { diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs new file mode 100644 index 000000000..29c0f382b --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs @@ -0,0 +1,111 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// SimpleWorkItemDispatcher handles execution of WorkItems by + /// directly executing them. It is provided so that a dispatcher + /// is always available in the context, thereby simplifying the + /// code needed to run child tests. + /// + public class SimpleWorkItemDispatcher : IWorkItemDispatcher + { +#if !PORTABLE + // The first WorkItem to be dispatched, assumed to be top-level item + private WorkItem _topLevelWorkItem; + + // Thread used to run and cancel tests + private Thread _runnerThread; +#endif + + #region IWorkItemDispatcher Members + + /// + /// Dispatch a single work item for execution. The first + /// work item dispatched is saved as the top-level + /// work item and a thread is created on which to + /// run it. Subsequent calls come from the top level + /// item or its descendants on the proper thread. + /// + /// The item to dispatch + public void Dispatch(WorkItem work) + { +#if PORTABLE + if (work != null) + work.Execute(); +#else + if (_topLevelWorkItem != null) + work.Execute(); + else + { + _topLevelWorkItem = work; + _runnerThread = new Thread(RunnerThreadProc); + +#if !NETCF && !SILVERLIGHT + if (work.TargetApartment == ApartmentState.STA) + _runnerThread.SetApartmentState(ApartmentState.STA); +#endif + + _runnerThread.Start(); + } +#endif + } + +#if !PORTABLE + private void RunnerThreadProc() + { + _topLevelWorkItem.Execute(); + } +#endif + +#if !PORTABLE + private object cancelLock = new object(); +#endif + + /// + /// Cancel (abort or stop) the ongoing run. + /// If no run is in process, the call has no effect. + /// + /// true if the run should be aborted, false if it should allow its currently running test to complete + public void CancelRun(bool force) + { +#if !PORTABLE + lock (cancelLock) + { + if (_topLevelWorkItem != null) + { + _topLevelWorkItem.Cancel(force); + if (force) + _topLevelWorkItem = null; + } + } +#endif + } + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TestWorker.cs new file mode 100644 index 000000000..208ff5387 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -0,0 +1,170 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using System.Threading; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// A TestWorker pulls work items from a queue + /// and executes them. + /// + public class TestWorker + { + private static Logger log = InternalTrace.GetLogger("TestWorker"); + + private WorkItemQueue _readyQueue; + private Thread _workerThread; + + private int _workItemCount = 0; + + private bool _running; + + /// + /// Event signaled immediately before executing a WorkItem + /// + public event EventHandler Busy; + + /// + /// Event signaled immediately after executing a WorkItem + /// + public event EventHandler Idle; + +#if NETCF + /// + /// Construct a new TestWorker. + /// + /// The queue from which to pull work items + /// The name of this worker + public TestWorker(WorkItemQueue queue, string name) +#else + /// + /// Construct a new TestWorker. + /// + /// The queue from which to pull work items + /// The name of this worker + /// The apartment state to use for running tests + public TestWorker(WorkItemQueue queue, string name, ApartmentState apartmentState) +#endif + { + _readyQueue = queue; + + _workerThread = new Thread(new ThreadStart(TestWorkerThreadProc)); + _workerThread.Name = name; +#if !NETCF + _workerThread.SetApartmentState(apartmentState); +#endif + } + + /// + /// The name of this worker - also used for the thread + /// + public string Name + { + get { return _workerThread.Name; } + } + + /// + /// Indicates whether the worker thread is running + /// + public bool IsAlive + { +#if NETCF + get { return !_workerThread.Join(0); } +#else + get { return _workerThread.IsAlive; } +#endif + } + + /// + /// Our ThreadProc, which pulls and runs tests in a loop + /// + private WorkItem _currentWorkItem; + + private void TestWorkerThreadProc() + { + log.Info("{0} starting ", _workerThread.Name); + + _running = true; + + try + { + while (_running) + { + _currentWorkItem = _readyQueue.Dequeue(); + if (_currentWorkItem == null) + break; + + log.Info("{0} executing {1}", _workerThread.Name, _currentWorkItem.Test.Name); + + if (Busy != null) + Busy(this, EventArgs.Empty); + + _currentWorkItem.WorkerId = Name; + _currentWorkItem.Execute(); + + if (Idle != null) + Idle(this, EventArgs.Empty); + + ++_workItemCount; + } + } + finally + { + log.Info("{0} stopping - {1} WorkItems processed.", _workerThread.Name, _workItemCount); + } + } + + /// + /// Start processing work items. + /// + public void Start() + { + _workerThread.Start(); + } + + private object cancelLock = new object(); + + /// + /// Stop the thread, either immediately or after finishing the current WorkItem + /// + /// true if the thread should be aborted, false if it should allow the currently running test to complete + public void Cancel(bool force) + { + if (force) + _running = false; + + lock (cancelLock) + if (_workerThread != null && _currentWorkItem != null) + { + _currentWorkItem.Cancel(force); + if (force) + _currentWorkItem = null; + } + } + } +} + +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TextCapture.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TextCapture.cs new file mode 100644 index 000000000..2e775bba0 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TextCapture.cs @@ -0,0 +1,102 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if !SILVERLIGHT && !NETCF && !PORTABLE +using System; +using System.IO; +//using System.Runtime.Remoting.Messaging; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// The TextCapture class intercepts console output and writes it + /// to the current execution context, if one is present on the thread. + /// If no execution context is found, the output is written to a + /// default destination, normally the original destination of the + /// intercepted output. + /// + public class TextCapture : TextWriter + { + private TextWriter _defaultWriter; + + /// + /// Construct a TextCapture object + /// + /// The default destination for non-intercepted output + public TextCapture(TextWriter defaultWriter) + { + _defaultWriter = defaultWriter; + } + + /// + /// Gets the Encoding in use by this TextWriter + /// + public override System.Text.Encoding Encoding + { + get { return _defaultWriter.Encoding; } + } + + /// + /// Writes a single character + /// + /// The char to write + public override void Write(char value) + { + var context = TestExecutionContext.GetTestExecutionContext(); + + if (context != null && context.CurrentResult != null) + context.CurrentResult.OutWriter.Write(value); + else + _defaultWriter.Write(value); + } + + /// + /// Writes a string + /// + /// The string to write + public override void Write(string value) + { + var context = TestExecutionContext.GetTestExecutionContext(); + + if (context != null && context.CurrentResult != null) + context.CurrentResult.OutWriter.Write(value); + else + _defaultWriter.Write(value); + } + + /// + /// Writes a string followed by a line terminator + /// + /// The string to write + public override void WriteLine(string value) + { + var context = TestExecutionContext.GetTestExecutionContext(); + + if (context != null && context.CurrentResult != null) + context.CurrentResult.OutWriter.WriteLine(value); + else + _defaultWriter.WriteLine(value); + } + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TextMessageWriter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TextMessageWriter.cs new file mode 100644 index 000000000..c023b5f86 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/TextMessageWriter.cs @@ -0,0 +1,297 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Globalization; +using NUnit.Framework.Constraints; + +namespace NUnit.Framework.Internal +{ + /// + /// TextMessageWriter writes constraint descriptions and messages + /// in displayable form as a text stream. It tailors the display + /// of individual message components to form the standard message + /// format of NUnit assertion failure messages. + /// + public class TextMessageWriter : MessageWriter + { + #region Message Formats and Constants + private static readonly int DEFAULT_LINE_LENGTH = 78; + + // Prefixes used in all failure messages. All must be the same + // length, which is held in the PrefixLength field. Should not + // contain any tabs or newline characters. + /// + /// Prefix used for the expected value line of a message + /// + public static readonly string Pfx_Expected = " Expected: "; + /// + /// Prefix used for the actual value line of a message + /// + public static readonly string Pfx_Actual = " But was: "; + /// + /// Length of a message prefix + /// + public static readonly int PrefixLength = Pfx_Expected.Length; + + #endregion + + private int maxLineLength = DEFAULT_LINE_LENGTH; + + #region Constructors + /// + /// Construct a TextMessageWriter + /// + public TextMessageWriter() { } + + /// + /// Construct a TextMessageWriter, specifying a user message + /// and optional formatting arguments. + /// + /// + /// + public TextMessageWriter(string userMessage, params object[] args) + { + if ( userMessage != null && userMessage != string.Empty) + this.WriteMessageLine(userMessage, args); + } + #endregion + + #region Properties + /// + /// Gets or sets the maximum line length for this writer + /// + public override int MaxLineLength + { + get { return maxLineLength; } + set { maxLineLength = value; } + } + #endregion + + #region Public Methods - High Level + /// + /// Method to write single line message with optional args, usually + /// written to precede the general failure message, at a given + /// indentation level. + /// + /// The indentation level of the message + /// The message to be written + /// Any arguments used in formatting the message + public override void WriteMessageLine(int level, string message, params object[] args) + { + if (message != null) + { + while (level-- >= 0) Write(" "); + + if (args != null && args.Length > 0) + message = string.Format(message, args); + + WriteLine(MsgUtils.EscapeNullCharacters(message)); + } + } + + /// + /// Display Expected and Actual lines for a constraint. This + /// is called by MessageWriter's default implementation of + /// WriteMessageTo and provides the generic two-line display. + /// + /// The result of the constraint that failed + public override void DisplayDifferences(ConstraintResult result) + { + WriteExpectedLine(result); + WriteActualLine(result); + } + + /// + /// Display Expected and Actual lines for given _values. This + /// method may be called by constraints that need more control over + /// the display of actual and expected _values than is provided + /// by the default implementation. + /// + /// The expected value + /// The actual value causing the failure + public override void DisplayDifferences(object expected, object actual) + { + WriteExpectedLine(expected); + WriteActualLine(actual); + } + + /// + /// Display Expected and Actual lines for given _values, including + /// a tolerance value on the expected line. + /// + /// The expected value + /// The actual value causing the failure + /// The tolerance within which the test was made + public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) + { + WriteExpectedLine(expected, tolerance); + WriteActualLine(actual); + } + + /// + /// Display the expected and actual string _values on separate lines. + /// If the mismatch parameter is >=0, an additional line is displayed + /// line containing a caret that points to the mismatch point. + /// + /// The expected string value + /// The actual string value + /// The point at which the strings don't match or -1 + /// If true, case is ignored in string comparisons + /// If true, clip the strings to fit the max line length + public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) + { + // Maximum string we can display without truncating + int maxDisplayLength = MaxLineLength + - PrefixLength // Allow for prefix + - 2; // 2 quotation marks + + if ( clipping ) + MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); + + expected = MsgUtils.EscapeControlChars(expected); + actual = MsgUtils.EscapeControlChars(actual); + + // The mismatch position may have changed due to clipping or white space conversion + mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); + + Write( Pfx_Expected ); + Write( MsgUtils.FormatValue(expected) ); + if ( ignoreCase ) + Write( ", ignoring case" ); + WriteLine(); + WriteActualLine( actual ); + //DisplayDifferences(expected, actual); + if (mismatch >= 0) + WriteCaretLine(mismatch); + } + #endregion + + #region Public Methods - Low Level + + /// + /// Writes the text for an actual value. + /// + /// The actual value. + public override void WriteActualValue(object actual) + { + WriteValue(actual); + } + + /// + /// Writes the text for a generalized value. + /// + /// The value. + public override void WriteValue(object val) + { + Write(MsgUtils.FormatValue(val)); + } + + /// + /// Writes the text for a collection value, + /// starting at a particular point, to a max length + /// + /// The collection containing elements to write. + /// The starting point of the elements to write + /// The maximum number of elements to write + public override void WriteCollectionElements(IEnumerable collection, long start, int max) + { + Write(MsgUtils.FormatCollection(collection, start, max)); + } + + #endregion + + #region Helper Methods + /// + /// Write the generic 'Expected' line for a constraint + /// + /// The constraint that failed + private void WriteExpectedLine(ConstraintResult result) + { + Write(Pfx_Expected); + WriteLine(result.Description); + } + + /// + /// Write the generic 'Expected' line for a given value + /// + /// The expected value + private void WriteExpectedLine(object expected) + { + WriteExpectedLine(expected, null); + } + + /// + /// Write the generic 'Expected' line for a given value + /// and tolerance. + /// + /// The expected value + /// The tolerance within which the test was made + private void WriteExpectedLine(object expected, Tolerance tolerance) + { + Write(Pfx_Expected); + Write(MsgUtils.FormatValue(expected)); + + if (tolerance != null && !tolerance.IsUnsetOrDefault) + { + Write(" +/- "); + Write(MsgUtils.FormatValue(tolerance.Value)); + if (tolerance.Mode != ToleranceMode.Linear) + Write(" {0}", tolerance.Mode); + } + + WriteLine(); + } + + /// + /// Write the generic 'Actual' line for a constraint + /// + /// The ConstraintResult for which the actual value is to be written + private void WriteActualLine(ConstraintResult result) + { + Write(Pfx_Actual); + result.WriteActualValueTo(this); + WriteLine(); + //WriteLine(MsgUtils.FormatValue(result.ActualValue)); + } + + /// + /// Write the generic 'Actual' line for a given value + /// + /// The actual value causing a failure + private void WriteActualLine(object actual) + { + Write(Pfx_Actual); + WriteActualValue(actual); + WriteLine(); + } + + private void WriteCaretLine(int mismatch) + { + // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote + WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); + } + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItem.cs new file mode 100644 index 000000000..5231dda3a --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -0,0 +1,468 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// A WorkItem may be an individual test case, a fixture or + /// a higher level grouping of tests. All WorkItems inherit + /// from the abstract WorkItem class, which uses the template + /// pattern to allow derived classes to perform work in + /// whatever way is needed. + /// + /// A WorkItem is created with a particular TestExecutionContext + /// and is responsible for re-establishing that context in the + /// current thread before it begins or resumes execution. + /// + public abstract class WorkItem + { + static Logger log = InternalTrace.GetLogger("WorkItem"); + + #region Static Factory Method + + /// + /// Creates a work item. + /// + /// The test for which this WorkItem is being created. + /// The filter to be used in selecting any child Tests. + /// + static public WorkItem CreateWorkItem(ITest test, ITestFilter filter) + { + TestSuite suite = test as TestSuite; + if (suite != null) + return new CompositeWorkItem(suite, filter); + else + return new SimpleWorkItem((TestMethod)test, filter); + } + + #endregion + + #region Construction and Initialization + + /// + /// Construct a WorkItem for a particular test. + /// + /// The test that the WorkItem will run + public WorkItem(Test test) + { + Test = test; + Result = test.MakeTestResult(); + State = WorkItemState.Ready; + Actions = new List(); +#if !PORTABLE && !SILVERLIGHT && !NETCF + TargetApartment = Test.Properties.ContainsKey(PropertyNames.ApartmentState) + ? (ApartmentState)Test.Properties.Get(PropertyNames.ApartmentState) + : ApartmentState.Unknown; +#endif + } + + /// + /// Initialize the TestExecutionContext. This must be done + /// before executing the WorkItem. + /// + /// + /// Originally, the context was provided in the constructor + /// but delaying initialization of the context until the item + /// is about to be dispatched allows changes in the parent + /// context during OneTimeSetUp to be reflected in the child. + /// + /// The TestExecutionContext to use + public void InitializeContext(TestExecutionContext context) + { + Guard.OperationValid(Context == null, "The context has already been initialized"); + + Context = context; + + if (Test is TestAssembly) + Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(((TestAssembly)Test).Assembly)); + else if (Test is ParameterizedMethodSuite) + Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(Test.Method.MethodInfo)); + else if (Test.TypeInfo != null) + Actions.AddRange(ActionsHelper.GetActionsFromTypesAttributes(Test.TypeInfo.Type)); + } + + #endregion + + #region Properties and Events + + /// + /// Event triggered when the item is complete + /// + public event EventHandler Completed; + + /// + /// Gets the current state of the WorkItem + /// + public WorkItemState State { get; private set; } + + /// + /// The test being executed by the work item + /// + public Test Test { get; private set; } + + /// + /// The execution context + /// + public TestExecutionContext Context { get; private set; } + + /// + /// The unique id of the worker executing this item. + /// + public string WorkerId {get; internal set;} + + /// + /// The test actions to be performed before and after this test + /// + public List Actions { get; private set; } + +#if PARALLEL + /// + /// Indicates whether this WorkItem may be run in parallel + /// + public bool IsParallelizable + { + get + { + ParallelScope scope = ParallelScope.None; + + if (Test.Properties.ContainsKey(PropertyNames.ParallelScope)) + { + scope = (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope); + + if ((scope & ParallelScope.Self) != 0) + return true; + } + else + { + scope = Context.ParallelScope; + + if ((scope & ParallelScope.Children) != 0) + return true; + } + + if (Test is TestFixture && (scope & ParallelScope.Fixtures) != 0) + return true; + + // Special handling for the top level TestAssembly. + // If it has any scope specified other than None, + // we will use the parallel queue. This heuristic + // is intended to minimize creation of unneeded + // queues and workers, since the assembly and + // namespace level tests can easily run in any queue. + if (Test is TestAssembly && scope != ParallelScope.None) + return true; + + return false; + } + } +#endif + + /// + /// The test result + /// + public TestResult Result { get; protected set; } + +#if !SILVERLIGHT && !NETCF && !PORTABLE + internal ApartmentState TargetApartment { get; set; } + private ApartmentState CurrentApartment { get; set; } +#endif + + #endregion + + #region OwnThreadReason Enumeration + + [Flags] + private enum OwnThreadReason + { + NotNeeded = 0, + RequiresThread = 1, + Timeout = 2, + DifferentApartment = 4 + } + + #endregion + + #region Public Methods + + /// + /// Execute the current work item, including any + /// child work items. + /// + public virtual void Execute() + { + // Timeout set at a higher level + int timeout = Context.TestCaseTimeout; + + // Timeout set on this test + if (Test.Properties.ContainsKey(PropertyNames.Timeout)) + timeout = (int)Test.Properties.Get(PropertyNames.Timeout); + + // Unless the context is single threaded, a supplementary thread + // is created on the various platforms... + // 1. If the test used the RequiresThreadAttribute. + // 2. If a test method has a timeout. + // 3. If the test needs to run in a different apartment. + // + // NOTE: We want to eliminate or significantly reduce + // cases 2 and 3 in the future. + // + // Case 2 requires the ability to stop and start test workers + // dynamically. We would cancel the worker thread, dispose of + // the worker and start a new worker on a new thread. + // + // Case 3 occurs when using either dispatcher whenever a + // child test calls for a different apartment from the one + // used by it's parent. It routinely occurs under the simple + // dispatcher (--workers=0 option). Under the parallel dispatcher + // it is needed when test cases are not enabled for parallel + // execution. Currently, test cases are always run sequentially, + // so this continues to apply fairly generally. + + var ownThreadReason = OwnThreadReason.NotNeeded; + +#if !PORTABLE + if (Test.RequiresThread) + ownThreadReason |= OwnThreadReason.RequiresThread; + if (timeout > 0 && Test is TestMethod) + ownThreadReason |= OwnThreadReason.Timeout; +#if !SILVERLIGHT && !NETCF + CurrentApartment = Thread.CurrentThread.GetApartmentState(); + if (CurrentApartment != TargetApartment && TargetApartment != ApartmentState.Unknown) + ownThreadReason |= OwnThreadReason.DifferentApartment; +#endif +#endif + + if (ownThreadReason == OwnThreadReason.NotNeeded) + RunTest(); + else if (Context.IsSingleThreaded) + { + var msg = "Test is not runnable in single-threaded context. " + ownThreadReason; + log.Error(msg); + Result.SetResult(ResultState.NotRunnable, msg); + WorkItemComplete(); + } + else + { + log.Debug("Running test on own thread. " + ownThreadReason); +#if SILVERLIGHT || NETCF + RunTestOnOwnThread(timeout); +#elif !PORTABLE + var apartment = (ownThreadReason | OwnThreadReason.DifferentApartment) != 0 + ? TargetApartment + : CurrentApartment; + RunTestOnOwnThread(timeout, apartment); +#endif + } + } + +#if SILVERLIGHT || NETCF + private Thread thread; + + private void RunTestOnOwnThread(int timeout) + { + thread = new Thread(RunTest); + RunThread(timeout); + } +#endif + +#if !SILVERLIGHT && !NETCF && !PORTABLE + private Thread thread; + + private void RunTestOnOwnThread(int timeout, ApartmentState apartment) + { + thread = new Thread(new ThreadStart(RunTest)); + thread.SetApartmentState(apartment); + RunThread(timeout); + } +#endif + +#if !PORTABLE + private void RunThread(int timeout) + { +#if !NETCF + thread.CurrentCulture = Context.CurrentCulture; + thread.CurrentUICulture = Context.CurrentUICulture; +#endif + + thread.Start(); + + if (timeout <= 0) + timeout = Timeout.Infinite; + + if (!thread.Join(timeout)) + { + // Don't enforce timeout when debugger is attached. + // We perform this check after the initial timeout has passed to + // give the user additional time to attach a debugger + // after the test has started execution + if (Debugger.IsAttached) + { + thread.Join(); + return; + } + + Thread tThread; + lock (threadLock) + { + if (thread == null) + return; + + tThread = thread; + thread = null; + } + + if (Context.ExecutionStatus == TestExecutionStatus.AbortRequested) + return; + + log.Debug("Killing thread {0}, which exceeded timeout", tThread.ManagedThreadId); + ThreadUtility.Kill(tThread); + + // NOTE: Without the use of Join, there is a race condition here. + // The thread sets the result to Cancelled and our code below sets + // it to Failure. In order for the result to be shown as a failure, + // we need to ensure that the following code executes after the + // thread has terminated. There is a risk here: the test code might + // refuse to terminate. However, it's more important to deal with + // the normal rather than a pathological case. + tThread.Join(); + + log.Debug("Changing result from {0} to Timeout Failure", Result.ResultState); + + Result.SetResult(ResultState.Failure, + string.Format("Test exceeded Timeout value of {0}ms", timeout)); + + WorkItemComplete(); + } + } +#endif + + private void RunTest() + { + Context.CurrentTest = this.Test; + Context.CurrentResult = this.Result; + Context.Listener.TestStarted(this.Test); + Context.StartTime = DateTime.UtcNow; + Context.StartTicks = Stopwatch.GetTimestamp(); + Context.WorkerId = this.WorkerId; + Context.EstablishExecutionEnvironment(); + + State = WorkItemState.Running; + + PerformWork(); + } + + private object threadLock = new object(); + + /// + /// Cancel (abort or stop) a WorkItem + /// + /// true if the WorkItem should be aborted, false if it should run to completion + public virtual void Cancel(bool force) + { + if (Context != null) + Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; + + if (!force) + return; + +#if !PORTABLE + Thread tThread; + + lock (threadLock) + { + if (thread == null) + return; + + tThread = thread; + thread = null; + } + + if (!tThread.Join(0)) + { + log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId); + ThreadUtility.Kill(tThread); + + tThread.Join(); + + log.Debug("Changing result from {0} to Cancelled", Result.ResultState); + + Result.SetResult(ResultState.Cancelled, "Cancelled by user"); + + WorkItemComplete(); + } +#endif + } + +#endregion + +#region Protected Methods + + /// + /// Method that performs actually performs the work. It should + /// set the State to WorkItemState.Complete when done. + /// + protected abstract void PerformWork(); + + /// + /// Method called by the derived class when all work is complete + /// + protected void WorkItemComplete() + { + State = WorkItemState.Complete; + + Result.StartTime = Context.StartTime; + Result.EndTime = DateTime.UtcNow; + + long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks; + double seconds = (double)tickCount / Stopwatch.Frequency; + Result.Duration = seconds; + + // We add in the assert count from the context. If + // this item is for a test case, we are adding the + // test assert count to zero. If it's a fixture, we + // are adding in any asserts that were run in the + // fixture setup or teardown. Each context only + // counts the asserts taking place in that context. + // Each result accumulates the count from child + // results along with it's own asserts. + Result.AssertCount += Context.AssertCount; + + Context.Listener.TestFinished(Result); + + if (Completed != null) + Completed(this, EventArgs.Empty); + + //Clear references to test objects to reduce memory usage + Context.TestObject = null; + Test.Fixture = null; + } + +#endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItemQueue.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItemQueue.cs new file mode 100644 index 000000000..e295631e1 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItemQueue.cs @@ -0,0 +1,287 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +#if NET_2_0 || NET_3_5 || NETCF +using ManualResetEventSlim = System.Threading.ManualResetEvent; +#endif + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// WorkItemQueueState indicates the current state of a WorkItemQueue + /// + public enum WorkItemQueueState + { + /// + /// The queue is paused + /// + Paused, + + /// + /// The queue is running + /// + Running, + + /// + /// The queue is stopped + /// + Stopped + } + + /// + /// A WorkItemQueue holds work items that are ready to + /// be run, either initially or after some dependency + /// has been satisfied. + /// + public class WorkItemQueue + { + private const int spinCount = 5; + + private Logger log = InternalTrace.GetLogger("WorkItemQueue"); + + private readonly ConcurrentQueue _innerQueue = new ConcurrentQueue(); + + /* This event is used solely for the purpose of having an optimized sleep cycle when + * we have to wait on an external event (Add or Remove for instance) + */ + private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false); + + /* The whole idea is to use these two values in a transactional + * way to track and manage the actual data inside the underlying lock-free collection + * instead of directly working with it or using external locking. + * + * They are manipulated with CAS and are guaranteed to increase over time and use + * of the instance thus preventing ABA problems. + */ + private int _addId = int.MinValue; + private int _removeId = int.MinValue; + + /// + /// Initializes a new instance of the class. + /// + /// The name of the queue. + public WorkItemQueue(string name) + { + Name = name; + State = WorkItemQueueState.Paused; + MaxCount = 0; + ItemsProcessed = 0; + } + + #region Properties + + /// + /// Gets the name of the work item queue. + /// + public string Name { get; private set; } + + private int _itemsProcessed; + /// + /// Gets the total number of items processed so far + /// + public int ItemsProcessed + { + get { return _itemsProcessed; } + private set { _itemsProcessed = value; } + } + + private int _maxCount; + + /// + /// Gets the maximum number of work items. + /// + public int MaxCount + { + get { return _maxCount; } + private set { _maxCount = value; } + } + + private int _state; + /// + /// Gets the current state of the queue + /// + public WorkItemQueueState State + { + get { return (WorkItemQueueState)_state; } + private set { _state = (int)value; } + } + + /// + /// Get a bool indicating whether the queue is empty. + /// + public bool IsEmpty + { + get { return _innerQueue.IsEmpty; } + } + + #endregion + + #region Public Methods + + /// + /// Enqueue a WorkItem to be processed + /// + /// The WorkItem to process + public void Enqueue(WorkItem work) + { + do + { + int cachedAddId = _addId; + + // Validate that we have are the current enqueuer + if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId) + continue; + + // Add to the collection + _innerQueue.Enqueue(work); + + // Set MaxCount using CAS + int i, j = _maxCount; + do + { + i = j; + j = Interlocked.CompareExchange(ref _maxCount, Math.Max(i, _innerQueue.Count), i); + } + while (i != j); + + // Wake up threads that may have been sleeping + _mreAdd.Set(); + + return; + } while (true); + } + + /// + /// Dequeue a WorkItem for processing + /// + /// A WorkItem or null if the queue has stopped + public WorkItem Dequeue() + { + SpinWait sw = new SpinWait(); + + do + { + WorkItemQueueState cachedState = State; + + if (cachedState == WorkItemQueueState.Stopped) + return null; // Tell worker to terminate + + int cachedRemoveId = _removeId; + int cachedAddId = _addId; + + // Empty case (or paused) + if (cachedRemoveId == cachedAddId || cachedState == WorkItemQueueState.Paused) + { + // Spin a few times to see if something changes + if (sw.Count <= spinCount) + { + sw.SpinOnce(); + } + else + { + // Reset to wait for an enqueue + _mreAdd.Reset(); + + // Recheck for an enqueue to avoid a Wait + if ((cachedRemoveId != _removeId || cachedAddId != _addId) && cachedState != WorkItemQueueState.Paused) + { + // Queue is not empty, set the event + _mreAdd.Set(); + continue; + } + + // Wait for something to happen + _mreAdd.Wait(500); + } + + continue; + } + + // Validate that we are the current dequeuer + if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId) + continue; + + + // Dequeue our work item + WorkItem work; + while (!_innerQueue.TryDequeue(out work)) { }; + + // Add to items processed using CAS + Interlocked.Increment(ref _itemsProcessed); + + return work; + } while (true); + } + + /// + /// Start or restart processing of items from the queue + /// + public void Start() + { + log.Info("{0} starting", Name); + + if (Interlocked.CompareExchange(ref _state, (int)WorkItemQueueState.Running, (int)WorkItemQueueState.Paused) == (int)WorkItemQueueState.Paused) + _mreAdd.Set(); + } + + /// + /// Signal the queue to stop + /// + public void Stop() + { + log.Info("{0} stopping - {1} WorkItems processed, max size {2}", Name, ItemsProcessed, MaxCount); + + if (Interlocked.Exchange(ref _state, (int)WorkItemQueueState.Stopped) != (int)WorkItemQueueState.Stopped) + _mreAdd.Set(); + } + + /// + /// Pause the queue for restarting later + /// + public void Pause() + { + log.Info("{0} pausing", Name); + + Interlocked.CompareExchange(ref _state, (int)WorkItemQueueState.Paused, (int)WorkItemQueueState.Running); + } + + #endregion + } + +#if NET_2_0 || NET_3_5 || NETCF + internal static class ManualResetEventExtensions + { + public static bool Wait (this ManualResetEvent mre, int millisecondsTimeout) + { + return mre.WaitOne(millisecondsTimeout, false); + } + } +#endif + +} +#endif diff --git a/test/NUnitLite/src/framework/Internal/WorkItems/WorkItemState.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItemState.cs similarity index 93% rename from test/NUnitLite/src/framework/Internal/WorkItems/WorkItemState.cs rename to test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItemState.cs index 581006ede..581f168aa 100644 --- a/test/NUnitLite/src/framework/Internal/WorkItems/WorkItemState.cs +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkItemState.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -namespace NUnit.Framework.Internal.WorkItems +namespace NUnit.Framework.Internal.Execution { /// /// The current state of a work item @@ -34,9 +34,9 @@ public enum WorkItemState Ready, /// - /// Waiting for a dependency to complete + /// Work Item is executing /// - Waiting, + Running, /// /// Complete diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkShift.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkShift.cs new file mode 100644 index 000000000..307bfc09c --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Execution/WorkShift.cs @@ -0,0 +1,210 @@ +// *********************************************************************** +// Copyright (c) 2012-2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if PARALLEL +using System; +using System.Collections.Generic; +using System.Threading; + +namespace NUnit.Framework.Internal.Execution +{ + /// + /// The dispatcher needs to do different things at different, + /// non-overlapped times. For example, non-parallel tests may + /// not be run at the same time as parallel tests. We model + /// this using the metaphor of a working shift. The WorkShift + /// class associates one or more WorkItemQueues with one or + /// more TestWorkers. + /// + /// Work in the queues is processed until all queues are empty + /// and all workers are idle. Both tests are needed because a + /// worker that is busy may end up adding more work to one of + /// the queues. At that point, the shift is over and another + /// shift may begin. This cycle continues until all the tests + /// have been run. + /// + public class WorkShift + { + private static Logger log = InternalTrace.GetLogger("WorkShift"); + + private object _syncRoot = new object(); + private int _busyCount = 0; + + // Shift name - used for logging + private string _name; + + /// + /// Construct a WorkShift + /// + public WorkShift(string name) + { + _name = name; + + this.IsActive = false; + this.Queues = new List(); + this.Workers = new List(); + } + + #region Public Events and Properties + + /// + /// Event that fires when the shift has ended + /// + public event EventHandler EndOfShift; + + /// + /// Gets a flag indicating whether the shift is currently active + /// + public bool IsActive { get; private set; } + + /// + /// Gets a list of the queues associated with this shift. + /// + /// Used for testing + public IList Queues { get; private set; } + + /// + /// Gets the list of workers associated with this shift. + /// + public IList Workers { get; private set; } + + /// + /// Gets a bool indicating whether this shift has any work to do + /// + public bool HasWork + { + get + { + foreach (var q in Queues) + if (!q.IsEmpty) + return true; + + return false; + } + } + + #endregion + + #region Public Methods + + /// + /// Add a WorkItemQueue to the shift, starting it if the + /// shift is currently active. + /// + public void AddQueue(WorkItemQueue queue) + { + log.Debug("{0} shift adding queue {1}", _name, queue.Name); + + Queues.Add(queue); + + if (this.IsActive) + queue.Start(); + } + + /// + /// Assign a worker to the shift. + /// + /// + public void Assign(TestWorker worker) + { + log.Debug("{0} shift assigned worker {1}", _name, worker.Name); + + Workers.Add(worker); + + worker.Busy += (s, ea) => Interlocked.Increment(ref _busyCount); + worker.Idle += (s, ea) => + { + // Quick check first using Interlocked.Decrement + if (Interlocked.Decrement(ref _busyCount) == 0) + lock (_syncRoot) + { + // Check busy count again under the lock + if (_busyCount == 0 && !HasWork) + this.EndShift(); + } + }; + + worker.Start(); + } + + /// + /// Start or restart processing for the shift + /// + public void Start() + { + log.Info("{0} shift starting", _name); + + this.IsActive = true; + + foreach (var q in Queues) + q.Start(); + } + + /// + /// End the shift, pausing all queues and raising + /// the EndOfShift event. + /// + public void EndShift() + { + log.Info("{0} shift ending", _name); + + this.IsActive = false; + + // Pause all queues + foreach (var q in Queues) + q.Pause(); + + // Signal the dispatcher that shift ended + if (EndOfShift != null) + EndOfShift(this, EventArgs.Empty); + } + + /// + /// Shut down the shift. + /// + public void ShutDown() + { + this.IsActive = false; + + foreach (var q in Queues) + q.Stop(); + } + + /// + /// Cancel (abort or stop) the shift without completing all work + /// + /// true if the WorkShift should be aborted, false if it should allow its currently running tests to complete + public void Cancel(bool force) + { + if (force) + this.IsActive = false; + + foreach (var w in Workers) + w.Cancel(force); + } + + #endregion + } +} + +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/AndFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/AndFilter.cs new file mode 100644 index 000000000..8447cc8ea --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/AndFilter.cs @@ -0,0 +1,101 @@ +// *********************************************************************** +// Copyright (c) 2007-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// Combines multiple filters so that a test must pass all + /// of them in order to pass this filter. + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class AndFilter : CompositeFilter + { + /// + /// Constructs an empty AndFilter + /// + public AndFilter() { } + + /// + /// Constructs an AndFilter from an array of filters + /// + /// + public AndFilter(params ITestFilter[] filters) : base(filters) { } + + /// + /// Checks whether the AndFilter is matched by a test + /// + /// The test to be matched + /// True if all the component filters pass, otherwise false + public override bool Pass( ITest test ) + { + foreach( ITestFilter filter in Filters ) + if ( !filter.Pass( test ) ) + return false; + + return true; + } + + /// + /// Checks whether the AndFilter is matched by a test + /// + /// The test to be matched + /// True if all the component filters match, otherwise false + public override bool Match( ITest test ) + { + foreach( TestFilter filter in Filters ) + if ( !filter.Match( test ) ) + return false; + + return true; + } + + /// + /// Checks whether the AndFilter is explicit matched by a test. + /// + /// The test to be matched + /// True if all the component filters explicit match, otherwise false + public override bool IsExplicitMatch( ITest test ) + { + foreach( TestFilter filter in Filters ) + if ( !filter.IsExplicitMatch( test ) ) + return false; + + return true; + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "and"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/CategoryFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/CategoryFilter.cs new file mode 100644 index 000000000..41f3ad34a --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/CategoryFilter.cs @@ -0,0 +1,74 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// CategoryFilter is able to select or exclude tests + /// based on their categories. + /// + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class CategoryFilter : ValueMatchFilter + { + /// + /// Construct a CategoryFilter using a single category name + /// + /// A category name + public CategoryFilter( string name ) : base(name) { } + + /// + /// Check whether the filter matches a test + /// + /// The test to be matched + /// + public override bool Match(ITest test) + { + IList testCategories = test.Properties[PropertyNames.Category]; + + if ( testCategories != null) + foreach (string cat in testCategories) + if ( Match(cat)) + return true; + + return false; + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "cat"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/ClassNameFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/ClassNameFilter.cs new file mode 100644 index 000000000..c40931f5e --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/ClassNameFilter.cs @@ -0,0 +1,65 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// ClassName filter selects tests based on the class FullName + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class ClassNameFilter : ValueMatchFilter + { + /// + /// Construct a FullNameFilter for a single name + /// + /// The name the filter will recognize. + public ClassNameFilter(string expectedValue) : base(expectedValue) { } + + /// + /// Match a test against a single value. + /// + public override bool Match(ITest test) + { + // tests below the fixture level may have non-null className + // but we don't want to match them explicitly. + if (!test.IsSuite || test is ParameterizedMethodSuite || test.ClassName == null) + return false; + + return Match(test.ClassName); + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "class"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/CompositeFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/CompositeFilter.cs new file mode 100644 index 000000000..e11e6e930 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/CompositeFilter.cs @@ -0,0 +1,107 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// A base class for multi-part filters + /// + public abstract class CompositeFilter : TestFilter + { + /// + /// Constructs an empty CompositeFilter + /// + public CompositeFilter() + { + Filters = new List(); + } + + /// + /// Constructs a CompositeFilter from an array of filters + /// + /// + public CompositeFilter( params ITestFilter[] filters ) + { + Filters = new List(filters); + } + + /// + /// Adds a filter to the list of filters + /// + /// The filter to be added + public void Add(ITestFilter filter) + { + Filters.Add(filter); + } + + /// + /// Return a list of the composing filters. + /// + public IList Filters { get; private set; } + + /// + /// Checks whether the CompositeFilter is matched by a test. + /// + /// The test to be matched + public abstract override bool Pass(ITest test); + + /// + /// Checks whether the CompositeFilter is matched by a test. + /// + /// The test to be matched + public abstract override bool Match(ITest test); + + /// + /// Checks whether the CompositeFilter is explicit matched by a test. + /// + /// The test to be matched + public abstract override bool IsExplicitMatch(ITest test); + + /// + /// Adds an XML node + /// + /// Parent node + /// True if recursive + /// The added XML node + public override TNode AddToXml(TNode parentNode, bool recursive) + { + TNode result = parentNode.AddElement(ElementName); + + if (recursive) + foreach (ITestFilter filter in Filters) + filter.AddToXml(result, true); + + return result; + } + + /// + /// Gets the element name + /// + /// Element name + protected abstract string ElementName { get; } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/FullNameFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/FullNameFilter.cs new file mode 100644 index 000000000..6833aab2a --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/FullNameFilter.cs @@ -0,0 +1,60 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// FullName filter selects tests based on their FullName + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class FullNameFilter : ValueMatchFilter + { + /// + /// Construct a FullNameFilter for a single name + /// + /// The name the filter will recognize. + public FullNameFilter(string expectedValue) : base(expectedValue) { } + + /// + /// Match a test against a single value. + /// + public override bool Match(ITest test) + { + return Match(test.FullName); + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "test"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/IdFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/IdFilter.cs new file mode 100644 index 000000000..4049b1da5 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/IdFilter.cs @@ -0,0 +1,63 @@ +// *********************************************************************** +// Copyright (c) 2013 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// IdFilter selects tests based on their id + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class IdFilter : ValueMatchFilter + { + /// + /// Construct an IdFilter for a single value + /// + /// The id the filter will recognize. + public IdFilter(string id) : base (id) { } + + /// + /// Match a test against a single value. + /// + public override bool Match(ITest test) + { + // We make a direct test here rather than calling ValueMatchFilter.Match + // because regular expressions are not supported for ID. + return test.Id == ExpectedValue; + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "id"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/MethodNameFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/MethodNameFilter.cs new file mode 100644 index 000000000..f89b7301d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/MethodNameFilter.cs @@ -0,0 +1,60 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// FullName filter selects tests based on their FullName + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class MethodNameFilter : ValueMatchFilter + { + /// + /// Construct a MethodNameFilter for a single name + /// + /// The name the filter will recognize. + public MethodNameFilter(string expectedValue) : base(expectedValue) { } + + /// + /// Match a test against a single value. + /// + public override bool Match(ITest test) + { + return Match(test.MethodName); + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "method"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/NotFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/NotFilter.cs new file mode 100644 index 000000000..b5e3c8c37 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/NotFilter.cs @@ -0,0 +1,119 @@ +// *********************************************************************** +// Copyright (c) 2007-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// NotFilter negates the operation of another filter + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class NotFilter : TestFilter + { + /// + /// Construct a not filter on another filter + /// + /// The filter to be negated + public NotFilter( TestFilter baseFilter) + { + BaseFilter = baseFilter; + } + + /// + /// Gets the base filter + /// + public TestFilter BaseFilter { get; private set; } + + /// + /// Determine if a particular test passes the filter criteria. The default + /// implementation checks the test itself, its parents and any descendants. + /// + /// Derived classes may override this method or any of the Match methods + /// to change the behavior of the filter. + /// + /// The test to which the filter is applied + /// True if the test passes the filter, otherwise false + public override bool Pass(ITest test) + { + return !BaseFilter.Match (test) && !BaseFilter.MatchParent (test); + } + + /// + /// Check whether the filter matches a test + /// + /// The test to be matched + /// True if it matches, otherwise false + public override bool Match( ITest test ) + { + return !BaseFilter.Match( test ); + } + + /// + /// Determine if a test matches the filter expicitly. That is, it must + /// be a direct match of the test itself or one of it's children. + /// + /// The test to which the filter is applied + /// True if the test matches the filter explicityly, otherwise false + public override bool IsExplicitMatch(ITest test) + { + return false; + } + + ///// + ///// Determine whether any descendant of the test matches the filter criteria. + ///// + ///// The test to be matched + ///// True if at least one descendant matches the filter criteria + //protected override bool MatchDescendant(ITest test) + //{ + // if (!test.HasChildren || test.Tests == null || TopLevel && test.RunState == RunState.Explicit) + // return false; + + // foreach (ITest child in test.Tests) + // { + // if (Match(child) || MatchDescendant(child)) + // return true; + // } + + // return false; + //} + + /// + /// Adds an XML node + /// + /// Parent node + /// True if recursive + /// The added XML node + public override TNode AddToXml(TNode parentNode, bool recursive) + { + TNode result = parentNode.AddElement("not"); + if (recursive) + BaseFilter.AddToXml(result, true); + return result; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/OrFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/OrFilter.cs new file mode 100644 index 000000000..593bd3a39 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/OrFilter.cs @@ -0,0 +1,101 @@ +// *********************************************************************** +// Copyright (c) 2007-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// Combines multiple filters so that a test must pass one + /// of them in order to pass this filter. + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class OrFilter : CompositeFilter + { + /// + /// Constructs an empty OrFilter + /// + public OrFilter() { } + + /// + /// Constructs an AndFilter from an array of filters + /// + /// + public OrFilter( params ITestFilter[] filters ) : base(filters) { } + + /// + /// Checks whether the OrFilter is matched by a test + /// + /// The test to be matched + /// True if any of the component filters pass, otherwise false + public override bool Pass( ITest test ) + { + foreach( ITestFilter filter in Filters ) + if ( filter.Pass( test ) ) + return true; + + return false; + } + + /// + /// Checks whether the OrFilter is matched by a test + /// + /// The test to be matched + /// True if any of the component filters match, otherwise false + public override bool Match( ITest test ) + { + foreach( TestFilter filter in Filters ) + if ( filter.Match( test ) ) + return true; + + return false; + } + + /// + /// Checks whether the OrFilter is explicit matched by a test + /// + /// The test to be matched + /// True if any of the component filters explicit match, otherwise false + public override bool IsExplicitMatch( ITest test ) + { + foreach( TestFilter filter in Filters ) + if ( filter.IsExplicitMatch( test ) ) + return true; + + return false; + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "or"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/PropertyFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/PropertyFilter.cs new file mode 100644 index 000000000..88dc0507d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/PropertyFilter.cs @@ -0,0 +1,93 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// PropertyFilter is able to select or exclude tests + /// based on their properties. + /// + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class PropertyFilter : ValueMatchFilter + { + private string _propertyName; + + /// + /// Construct a PropertyFilter using a property name and expected value + /// + /// A property name + /// The expected value of the property + public PropertyFilter(string propertyName, string expectedValue) : base(expectedValue) + { + _propertyName = propertyName; + } + + /// + /// Check whether the filter matches a test + /// + /// The test to be matched + /// + public override bool Match(ITest test) + { + IList values = test.Properties[_propertyName]; + + if (values != null) + foreach (string val in values) + if (Match(val)) + return true; + + return false; + } + + /// + /// Adds an XML node + /// + /// Parent node + /// True if recursive + /// The added XML node + public override TNode AddToXml(TNode parentNode, bool recursive) + { + TNode result = base.AddToXml(parentNode, recursive); + result.AddAttribute("name", _propertyName); + return result; + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "prop"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/TestNameFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/TestNameFilter.cs new file mode 100644 index 000000000..f674a672d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/TestNameFilter.cs @@ -0,0 +1,60 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// TestName filter selects tests based on their Name + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public class TestNameFilter : ValueMatchFilter + { + /// + /// Construct a TestNameFilter for a single name + /// + /// The name the filter will recognize. + public TestNameFilter(string expectedValue) : base(expectedValue) { } + + /// + /// Match a test against a single value. + /// + public override bool Match(ITest test) + { + return Match(test.Name); + } + + /// + /// Gets the element name + /// + /// Element name + protected override string ElementName + { + get { return "name"; } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Filters/ValueMatchFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/ValueMatchFilter.cs new file mode 100644 index 000000000..61ebf40e6 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Filters/ValueMatchFilter.cs @@ -0,0 +1,92 @@ +// *********************************************************************** +// Copyright (c) 2013 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Filters +{ + /// + /// ValueMatchFilter selects tests based on some value, which + /// is expected to be contained in the test. + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public abstract class ValueMatchFilter : TestFilter + { + /// + /// Returns the value matched by the filter - used for testing + /// + public string ExpectedValue { get; private set; } + + /// + /// Indicates whether the value is a regular expression + /// + public bool IsRegex { get; set; } + + /// + /// Construct a ValueMatchFilter for a single value. + /// + /// The value to be included. + public ValueMatchFilter(string expectedValue) + { + ExpectedValue = expectedValue; + } + + /// + /// Match the input provided by the derived class + /// + /// The value to be matchedT + /// True for a match, false otherwise. + protected bool Match(string input) + { + if (IsRegex) + return input != null && new Regex(ExpectedValue).IsMatch(input); + else + return ExpectedValue == input; + } + + /// + /// Adds an XML node + /// + /// Parent node + /// True if recursive + /// The added XML node + public override TNode AddToXml(TNode parentNode, bool recursive) + { + TNode result = parentNode.AddElement(ElementName, ExpectedValue); + if (IsRegex) + result.AddAttribute("re", "1"); + return result; + } + + /// + /// Gets the element name + /// + /// Element name + protected abstract string ElementName { get; } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/GenericMethodHelper.cs b/test/NUnitLite/NUnitFramework/framework/Internal/GenericMethodHelper.cs new file mode 100644 index 000000000..19b0425b0 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/GenericMethodHelper.cs @@ -0,0 +1,156 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Compatibility; + +namespace NUnit.Framework.Internal +{ + /// + /// GenericMethodHelper is able to deduce the Type arguments for + /// a generic method from the actual arguments provided. + /// + public class GenericMethodHelper + { + /// + /// Construct a GenericMethodHelper for a method + /// + /// MethodInfo for the method to examine + public GenericMethodHelper(MethodInfo method) + { + Guard.ArgumentValid(method.IsGenericMethod, "Specified method must be generic", "method"); + + Method = method; + + TypeParms = Method.GetGenericArguments(); + TypeArgs = new Type[TypeParms.Length]; + + var parms = Method.GetParameters(); + ParmTypes = new Type[parms.Length]; + for (int i = 0; i < parms.Length; i++) + ParmTypes[i] = parms[i].ParameterType; + } + + private MethodInfo Method { get; set; } + + private Type[] TypeParms { get; set; } + private Type[] TypeArgs { get; set; } + + private Type[] ParmTypes { get; set; } + + /// + /// Return the type argments for the method, deducing them + /// from the arguments actually provided. + /// + /// The arguments to the method + /// An array of type arguments. + public Type[] GetTypeArguments(object[] argList) + { + Guard.ArgumentValid(argList.Length == ParmTypes.Length, "Supplied arguments do not match required method parameters", "argList"); + + for (int argIndex = 0; argIndex < ParmTypes.Length; argIndex++) + { + var arg = argList[argIndex]; + + if (arg != null) + { + Type argType = arg.GetType(); + TryApplyArgType(ParmTypes[argIndex], argType); + } + } + + return TypeArgs; + } + + private void TryApplyArgType(Type parmType, Type argType) + { + if (parmType.IsGenericParameter) + { + ApplyArgType(parmType, argType); + } + else if (parmType.GetTypeInfo().ContainsGenericParameters) + { + var genericArgTypes = parmType.GetGenericArguments(); + + if (argType.HasElementType) + { + ApplyArgType(genericArgTypes[0], argType.GetElementType()); + } + else if (argType.GetTypeInfo().IsGenericType && IsAssignableToGenericType(argType, parmType)) + { + Type[] argTypes = argType.GetGenericArguments(); + + if (argTypes.Length == genericArgTypes.Length) + for (int i = 0; i < genericArgTypes.Length; i++) + TryApplyArgType(genericArgTypes[i], argTypes[i]); + } + } + } + + private void ApplyArgType(Type parmType, Type argType) + { + // Note: parmType must be generic parameter type - checked by caller +#if NETCF + var index = Array.IndexOf(TypeParms, parmType); +#else + var index = parmType.GenericParameterPosition; +#endif + TypeArgs[index] = TypeHelper.BestCommonType(TypeArgs[index], argType); + } + + // Simulates IsAssignableTo generics + private bool IsAssignableToGenericType(Type givenType, Type genericType) + { + var interfaceTypes = givenType.GetInterfaces(); + + foreach (var iterator in interfaceTypes) + { + if (iterator.GetTypeInfo().IsGenericType) + { + // The Type returned by GetGenericTyeDefinition may have the + // FullName set to null, so we do our own comparison + Type gtd = iterator.GetGenericTypeDefinition(); + if (gtd.Name == genericType.Name && gtd.Namespace == genericType.Namespace) + return true; + } + } + + if (givenType.GetTypeInfo().IsGenericType) + { + // The Type returned by GetGenericTyeDefinition may have the + // FullName set to null, so we do our own comparison + Type gtd = givenType.GetGenericTypeDefinition(); + if (gtd.Name == genericType.Name && gtd.Namespace == genericType.Namespace) + return true; + } + + Type baseType = givenType.GetTypeInfo().BaseType; + if (baseType == null) + return false; + + return IsAssignableToGenericType(baseType, genericType); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/InvalidDataSourceException.cs b/test/NUnitLite/NUnitFramework/framework/Internal/InvalidDataSourceException.cs new file mode 100644 index 000000000..1da8f8638 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/InvalidDataSourceException.cs @@ -0,0 +1,68 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal +{ + using System; +#if !NETCF + using System.Runtime.Serialization; +#endif + + /// + /// InvalidTestFixtureException is thrown when an appropriate test + /// fixture constructor using the provided arguments cannot be found. + /// +#if !NETCF && !PORTABLE && ! SILVERLIGHT + [Serializable] +#endif + public class InvalidDataSourceException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public InvalidDataSourceException() : base() {} + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public InvalidDataSourceException(string message) : base(message) + {} + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public InvalidDataSourceException(string message, Exception inner) : base(message, inner) + { } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// Serialization Constructor + /// + protected InvalidDataSourceException(SerializationInfo info, + StreamingContext context) : base(info,context){} +#endif + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/InvalidTestFixtureException.cs b/test/NUnitLite/NUnitFramework/framework/Internal/InvalidTestFixtureException.cs new file mode 100644 index 000000000..5b73fcbe2 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/InvalidTestFixtureException.cs @@ -0,0 +1,68 @@ +// *********************************************************************** +// Copyright (c) 2006 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal +{ + using System; +#if !NETCF + using System.Runtime.Serialization; +#endif + + /// + /// InvalidTestFixtureException is thrown when an appropriate test + /// fixture constructor using the provided arguments cannot be found. + /// +#if !NETCF && !PORTABLE && ! SILVERLIGHT + [Serializable] +#endif + public class InvalidTestFixtureException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public InvalidTestFixtureException() : base() {} + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public InvalidTestFixtureException(string message) : base(message) + {} + + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner. + public InvalidTestFixtureException(string message, Exception inner) : base(message, inner) + { } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// Serialization Constructor + /// + protected InvalidTestFixtureException(SerializationInfo info, + StreamingContext context) : base(info,context){} +#endif + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Logging/ILogger.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/ILogger.cs new file mode 100644 index 000000000..a62733c0e --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/ILogger.cs @@ -0,0 +1,83 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal +{ + /// + /// Interface for logging within the engine + /// + public interface ILogger + { + /// + /// Logs the specified message at the error level. + /// + /// The message. + void Error(string message); + + /// + /// Logs the specified message at the error level. + /// + /// The message. + /// The arguments. + void Error(string message, params object[] args); + + /// + /// Logs the specified message at the warning level. + /// + /// The message. + void Warning(string message); + + /// + /// Logs the specified message at the warning level. + /// + /// The message. + /// The arguments. + void Warning(string message, params object[] args); + + /// + /// Logs the specified message at the info level. + /// + /// The message. + void Info(string message); + + /// + /// Logs the specified message at the info level. + /// + /// The message. + /// The arguments. + void Info(string message, params object[] args); + + /// + /// Logs the specified message at the debug level. + /// + /// The message. + void Debug(string message); + + /// + /// Logs the specified message at the debug level. + /// + /// The message. + /// The arguments. + void Debug(string message, params object[] args); + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTrace.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTrace.cs new file mode 100644 index 000000000..f844a2949 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTrace.cs @@ -0,0 +1,118 @@ +// *********************************************************************** +// Copyright (c) 2008-2013 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.IO; + +namespace NUnit.Framework.Internal +{ + /// + /// InternalTrace provides facilities for tracing the execution + /// of the NUnit framework. Tests and classes under test may make use + /// of Console writes, System.Diagnostics.Trace or various loggers and + /// NUnit itself traps and processes each of them. For that reason, a + /// separate internal trace is needed. + /// + /// Note: + /// InternalTrace uses a global lock to allow multiple threads to write + /// trace messages. This can easily make it a bottleneck so it must be + /// used sparingly. Keep the trace Level as low as possible and only + /// insert InternalTrace writes where they are needed. + /// TODO: add some buffering and a separate writer thread as an option. + /// TODO: figure out a way to turn on trace in specific classes only. + /// + public static class InternalTrace + { + private static InternalTraceLevel traceLevel; + private static InternalTraceWriter traceWriter; + + /// + /// Gets a flag indicating whether the InternalTrace is initialized + /// + public static bool Initialized { get; private set; } + +#if !PORTABLE + /// + /// Initialize the internal trace facility using the name of the log + /// to be written to and the trace level. + /// + /// The log name + /// The trace level + public static void Initialize(string logName, InternalTraceLevel level) + { + if (!Initialized) + { + traceLevel = level; + + if (traceWriter == null && traceLevel > InternalTraceLevel.Off) + { + traceWriter = new InternalTraceWriter(logName); + traceWriter.WriteLine("InternalTrace: Initializing at level {0}", traceLevel); + } + + Initialized = true; + } + else + traceWriter.WriteLine("InternalTrace: Ignoring attempted re-initialization at level {0}", level); + } +#endif + + /// + /// Initialize the internal trace using a provided TextWriter and level + /// + /// A TextWriter + /// The InternalTraceLevel + public static void Initialize(TextWriter writer, InternalTraceLevel level) + { + if (!Initialized) + { + traceLevel = level; + + if (traceWriter == null && traceLevel > InternalTraceLevel.Off) + { + traceWriter = new InternalTraceWriter(writer); + traceWriter.WriteLine("InternalTrace: Initializing at level " + traceLevel.ToString()); + } + + Initialized = true; + } + } + + /// + /// Get a named Logger + /// + /// + public static Logger GetLogger(string name) + { + return new Logger(name, traceLevel, traceWriter); + } + + /// + /// Get a logger named for a particular Type. + /// + public static Logger GetLogger(Type type) + { + return GetLogger(type.FullName); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTraceLevel.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTraceLevel.cs new file mode 100644 index 000000000..0aa856e3a --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTraceLevel.cs @@ -0,0 +1,67 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal +{ + /// + /// InternalTraceLevel is an enumeration controlling the + /// level of detailed presented in the internal log. + /// + public enum InternalTraceLevel + { + /// + /// Use the default settings as specified by the user. + /// + Default, + + /// + /// Do not display any trace messages + /// + Off, + + /// + /// Display Error messages only + /// + Error, + + /// + /// Display Warning level and higher messages + /// + Warning, + + /// + /// Display informational and higher messages + /// + Info, + + /// + /// Display debug messages and higher - i.e. all messages + /// + Debug, + + /// + /// Display debug messages and higher - i.e. all messages + /// + Verbose = Debug + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTraceWriter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTraceWriter.cs new file mode 100644 index 000000000..6c05504fe --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/InternalTraceWriter.cs @@ -0,0 +1,126 @@ +// *********************************************************************** +// Copyright (c) 2008-2013 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +using System.IO; + +namespace NUnit.Framework.Internal +{ + /// + /// A trace listener that writes to a separate file per domain + /// and process using it. + /// + public class InternalTraceWriter : TextWriter + { + TextWriter writer; + object myLock = new object(); + +#if !PORTABLE + /// + /// Construct an InternalTraceWriter that writes to a file. + /// + /// Path to the file to use + public InternalTraceWriter(string logPath) + { + var streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write)); + streamWriter.AutoFlush = true; + this.writer = streamWriter; + } +#endif + + /// + /// Construct an InternalTraceWriter that writes to a + /// TextWriter provided by the caller. + /// + /// + public InternalTraceWriter(TextWriter writer) + { + this.writer = writer; + } + + /// + /// Returns the character encoding in which the output is written. + /// + /// The character encoding in which the output is written. + public override System.Text.Encoding Encoding + { + get { return writer.Encoding; } + } + + /// + /// Writes a character to the text string or stream. + /// + /// The character to write to the text stream. + public override void Write(char value) + { + lock (myLock) + { + writer.Write(value); + } + } + + /// + /// Writes a string to the text string or stream. + /// + /// The string to write. + public override void Write(string value) + { + lock (myLock) + { + base.Write(value); + } + } + + /// + /// Writes a string followed by a line terminator to the text string or stream. + /// + /// The string to write. If is null, only the line terminator is written. + public override void WriteLine(string value) + { + writer.WriteLine(value); + } + + /// + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected override void Dispose(bool disposing) + { + if (disposing && writer != null) + { + writer.Flush(); + writer.Dispose(); + writer = null; + } + + base.Dispose(disposing); + } + + /// + /// Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. + /// + public override void Flush() + { + if ( writer != null ) + writer.Flush(); + } + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Logging/Logger.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/Logger.cs new file mode 100644 index 000000000..5d45eebdb --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Logging/Logger.cs @@ -0,0 +1,179 @@ +// *********************************************************************** +// Copyright (c) 2008-2013 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.IO; + +namespace NUnit.Framework.Internal +{ + /// + /// Provides internal logging to the NUnit framework + /// + public class Logger : ILogger + { + private readonly static string TIME_FMT = "HH:mm:ss.fff"; + private readonly static string TRACE_FMT = "{0} {1,-5} [{2,2}] {3}: {4}"; + + private string name; + private string fullname; + private InternalTraceLevel maxLevel; + private TextWriter writer; + + /// + /// Initializes a new instance of the class. + /// + /// The name. + /// The log level. + /// The writer where logs are sent. + public Logger(string name, InternalTraceLevel level, TextWriter writer) + { + this.maxLevel = level; + this.writer = writer; + this.fullname = this.name = name; + int index = fullname.LastIndexOf('.'); + if (index >= 0) + this.name = fullname.Substring(index + 1); + } + + #region Error + /// + /// Logs the message at error level. + /// + /// The message. + public void Error(string message) + { + Log(InternalTraceLevel.Error, message); + } + + /// + /// Logs the message at error level. + /// + /// The message. + /// The message arguments. + public void Error(string message, params object[] args) + { + Log(InternalTraceLevel.Error, message, args); + } + + //public void Error(string message, Exception ex) + //{ + // if (service.Level >= InternalTraceLevel.Error) + // { + // service.Log(InternalTraceLevel.Error, message, name, ex); + // } + //} + #endregion + + #region Warning + /// + /// Logs the message at warm level. + /// + /// The message. + public void Warning(string message) + { + Log(InternalTraceLevel.Warning, message); + } + + /// + /// Logs the message at warning level. + /// + /// The message. + /// The message arguments. + public void Warning(string message, params object[] args) + { + Log(InternalTraceLevel.Warning, message, args); + } + #endregion + + #region Info + /// + /// Logs the message at info level. + /// + /// The message. + public void Info(string message) + { + Log(InternalTraceLevel.Info, message); + } + + /// + /// Logs the message at info level. + /// + /// The message. + /// The message arguments. + public void Info(string message, params object[] args) + { + Log(InternalTraceLevel.Info, message, args); + } + #endregion + + #region Debug + /// + /// Logs the message at debug level. + /// + /// The message. + public void Debug(string message) + { + Log(InternalTraceLevel.Verbose, message); + } + + /// + /// Logs the message at debug level. + /// + /// The message. + /// The message arguments. + public void Debug(string message, params object[] args) + { + Log(InternalTraceLevel.Verbose, message, args); + } + #endregion + + #region Helper Methods + private void Log(InternalTraceLevel level, string message) + { + if (writer != null && this.maxLevel >= level) + WriteLog(level, message); + } + + private void Log(InternalTraceLevel level, string format, params object[] args) + { + if (this.maxLevel >= level) + WriteLog(level, string.Format( format, args ) ); + } + + private void WriteLog(InternalTraceLevel level, string message) + { + writer.WriteLine(TRACE_FMT, + DateTime.Now.ToString(TIME_FMT), + level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), +#if PORTABLE + System.Environment.CurrentManagedThreadId, +#else + System.Threading.Thread.CurrentThread.ManagedThreadId, +#endif + name, + message); + } + +#endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/MethodWrapper.cs b/test/NUnitLite/NUnitFramework/framework/Internal/MethodWrapper.cs new file mode 100644 index 000000000..bd7c7c377 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/MethodWrapper.cs @@ -0,0 +1,205 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Reflection; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +#if PORTABLE +using System.Linq; +#endif + +namespace NUnit.Framework.Internal +{ + /// + /// The MethodWrapper class wraps a MethodInfo so that it may + /// be used in a platform-independent manner. + /// + public class MethodWrapper : IMethodInfo + { + /// + /// Construct a MethodWrapper for a Type and a MethodInfo. + /// + public MethodWrapper(Type type, MethodInfo method) + { + TypeInfo = new TypeWrapper(type); + MethodInfo = method; + } + + /// + /// Construct a MethodInfo for a given Type and method name. + /// + public MethodWrapper(Type type, string methodName) + { + TypeInfo = new TypeWrapper(type); + MethodInfo = type.GetMethod(methodName); + } + + #region IMethod Implementation + + /// + /// Gets the Type from which this method was reflected. + /// + public ITypeInfo TypeInfo { get; private set; } + + /// + /// Gets the MethodInfo for this method. + /// + public MethodInfo MethodInfo { get; private set; } + + /// + /// Gets the name of the method. + /// + public string Name + { + get { return MethodInfo.Name; } + } + + /// + /// Gets a value indicating whether the method is abstract. + /// + public bool IsAbstract + { + get { return MethodInfo.IsAbstract; } + } + + /// + /// Gets a value indicating whether the method is public. + /// + public bool IsPublic + { + get { return MethodInfo.IsPublic; } + } + + /// + /// Gets a value indicating whether the method contains unassigned generic type parameters. + /// + public bool ContainsGenericParameters + { + get { return MethodInfo.ContainsGenericParameters; } + } + + /// + /// Gets a value indicating whether the method is a generic method. + /// + public bool IsGenericMethod + { + get { return MethodInfo.IsGenericMethod; } + } + + /// + /// Gets a value indicating whether the MethodInfo represents the definition of a generic method. + /// + public bool IsGenericMethodDefinition + { + get { return MethodInfo.IsGenericMethodDefinition; } + } + + /// + /// Gets the return Type of the method. + /// + public ITypeInfo ReturnType + { + get { return new TypeWrapper(MethodInfo.ReturnType); } + } + + /// + /// Gets the parameters of the method. + /// + /// + public IParameterInfo[] GetParameters() + { + var parameters = MethodInfo.GetParameters(); + var result = new IParameterInfo[parameters.Length]; + + for (int i = 0; i < parameters.Length; i++) + result[i] = new ParameterWrapper(this, parameters[i]); + + return result; + } + + /// + /// Returns the Type arguments of a generic method or the Type parameters of a generic method definition. + /// + public Type[] GetGenericArguments() + { + return MethodInfo.GetGenericArguments(); + } + + /// + /// Replaces the type parameters of the method with the array of types provided and returns a new IMethodInfo. + /// + /// The type arguments to be used + /// A new IMethodInfo with the type arguments replaced + public IMethodInfo MakeGenericMethod(params Type[] typeArguments) + { + return new MethodWrapper(TypeInfo.Type, MethodInfo.MakeGenericMethod(typeArguments)); + } + + /// + /// Returns an array of custom attributes of the specified type applied to this method + /// + public T[] GetCustomAttributes(bool inherit) where T : class + { +#if PORTABLE + return MethodInfo.GetAttributes(inherit).ToArray(); +#else + return (T[])MethodInfo.GetCustomAttributes(typeof(T), inherit); +#endif + } + + /// + /// Gets a value indicating whether one or more attributes of the spcified type are defined on the method. + /// + public bool IsDefined(bool inherit) + { +#if PORTABLE + return MethodInfo.GetCustomAttributes(inherit).Any(a => typeof(T).IsAssignableFrom(a.GetType())); +#else + return MethodInfo.IsDefined(typeof(T), inherit); +#endif + } + + /// + /// Invokes the method, converting any TargetInvocationException to an NUnitException. + /// + /// The object on which to invoke the method + /// The argument list for the method + /// The return value from the invoked method + public object Invoke(object fixture, params object[] args) + { + return Reflect.InvokeMethod(MethodInfo, fixture, args); + } + + /// + /// Override ToString() so that error messages in NUnit's own tests make sense + /// + public override string ToString() + { + return MethodInfo.Name; + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/NUnitException.cs b/test/NUnitLite/NUnitFramework/framework/Internal/NUnitException.cs new file mode 100644 index 000000000..87b84041c --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/NUnitException.cs @@ -0,0 +1,73 @@ +// *********************************************************************** +// Copyright (c) 2009 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal +{ + using System; +#if !NETCF + using System.Runtime.Serialization; +#endif + + /// + /// Thrown when an assertion failed. Here to preserve the inner + /// exception and hence its stack trace. + /// +#if !NETCF && !PORTABLE && ! SILVERLIGHT + [Serializable] +#endif + public class NUnitException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public NUnitException () : base() + {} + + /// + /// Initializes a new instance of the class. + /// + /// The error message that explains + /// the reason for the exception + public NUnitException(string message) : base (message) + {} + + /// + /// Initializes a new instance of the class. + /// + /// The error message that explains + /// the reason for the exception + /// The exception that caused the + /// current exception + public NUnitException(string message, Exception inner) : + base(message, inner) + { } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// Serialization Constructor + /// + protected NUnitException(SerializationInfo info, + StreamingContext context) : base(info,context){} +#endif + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/NetCFExtensions.cs b/test/NUnitLite/NUnitFramework/framework/Internal/NetCFExtensions.cs new file mode 100644 index 000000000..d884cd3a8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/NetCFExtensions.cs @@ -0,0 +1,139 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if NETCF +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Reflection; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + static class NetCFExtensions + { + public static IMethodInfo MakeGenericMethodEx(this IMethodInfo method, object[] arguments) + { + var newMi = method.MethodInfo.MakeGenericMethodEx(arguments); + if (newMi == null) return null; + + return new MethodWrapper(method.TypeInfo.Type, newMi); + } + + public static MethodInfo MakeGenericMethodEx(this MethodInfo mi, object[] arguments) + { + return mi.MakeGenericMethodEx(arguments.Select(a => a == null ? typeof(object) : (a is Type ? typeof(Type) : a.GetType())).ToArray()); + } + + public static MethodInfo MakeGenericMethodEx(this MethodInfo mi, Type[] types) + { + if(!mi.ContainsGenericParameters) + return mi; + + if(!mi.IsGenericMethodDefinition) + return mi.MakeGenericMethod(types); + + var args = mi.GetGenericArguments(); + + if(args.Length == types.Length) + return mi.MakeGenericMethod(types); + + if(args.Length > types.Length) + return null; + + var tai = new TypeArrayIterator(types, args.Length); + + foreach(var ta in tai) + { + var newMi = mi.MakeGenericMethod(ta); + var pa = newMi.GetParameters(); + if(types.SequenceEqual(pa.Select(p => p.ParameterType))) + return newMi; + } + + foreach(var ta in tai) + { + var newMi = mi.MakeGenericMethod(ta); + var pa = newMi.GetParameters(); + if(types.Select((t,ix) => (Type)TypeHelper.BestCommonType(t, pa[ix].ParameterType)).SequenceEqual(pa.Select(p => p.ParameterType))) + return newMi; + } + + return null; + } + + } + + internal class TypeArrayIterator : IEnumerable + { + private Type[] _types; + private int _neededLength; + + public TypeArrayIterator(Type[] types, int neededLength) + { + _types = types; + _neededLength = neededLength; + } + + #region IEnumerable Members + + public IEnumerator GetEnumerator() + { + var indices = new int[_neededLength]; + while(true) + { + var results = new List (); + + for(int i = 0; i < _neededLength; ++i) + results.Add(_types[indices[i]]); + + if(indices.Distinct().Count() == _neededLength) + yield return results.ToArray(); + + for(int j = _neededLength - 1; j >= 0; --j) + { + if(++indices[j] < _types.Length) + break; + + if(j == 0) + yield break; + + indices[j] = 0; + } + } + } + + #endregion + + #region IEnumerable Members + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/OSPlatform.cs b/test/NUnitLite/NUnitFramework/framework/Internal/OSPlatform.cs new file mode 100644 index 000000000..8f4073772 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/OSPlatform.cs @@ -0,0 +1,562 @@ +// *********************************************************************** +// Copyright (c) 2008-2016 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if !PORTABLE +using Microsoft.Win32; +using System; +using System.Runtime.InteropServices; +using System.Security; + +namespace NUnit.Framework.Internal +{ + /// + /// OSPlatform represents a particular operating system platform + /// +#if !SILVERLIGHT && !NETCF + // This class invokes security critical P/Invoke and 'System.Runtime.InteropServices.Marshall' methods. + // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' + // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. + [SecuritySafeCritical] +#endif + public class OSPlatform + { + readonly PlatformID _platform; + readonly Version _version; + readonly ProductType _product; + + #region Static Members + private static readonly Lazy currentPlatform = new Lazy (() => + { + OSPlatform currentPlatform; + + OperatingSystem os = Environment.OSVersion; + +#if SILVERLIGHT || NETCF + // TODO: Runtime silverlight detection? + currentPlatform = new OSPlatform(os.Platform, os.Version); +#else + if (os.Platform == PlatformID.Win32NT && os.Version.Major >= 5) + { + OSVERSIONINFOEX osvi = new OSVERSIONINFOEX(); + osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); + GetVersionEx(ref osvi); + if (os.Version.Major == 6 && os.Version.Minor >= 2) + os = new OperatingSystem(os.Platform, GetWindows81PlusVersion(os.Version)); + currentPlatform = new OSPlatform(os.Platform, os.Version, (ProductType)osvi.ProductType); + } + else if (CheckIfIsMacOSX(os.Platform)) + { + // Mono returns PlatformID.Unix for OSX (see http://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform) + // The above check uses uname to confirm it is MacOSX and we change the PlatformId here. + currentPlatform = new OSPlatform(PlatformID.MacOSX, os.Version); + } + else + currentPlatform = new OSPlatform(os.Platform, os.Version); +#endif + return currentPlatform; + }); + + + /// + /// Platform ID for Unix as defined by Microsoft .NET 2.0 and greater + /// + public static readonly PlatformID UnixPlatformID_Microsoft = (PlatformID)4; + + /// + /// Platform ID for Unix as defined by Mono + /// + public static readonly PlatformID UnixPlatformID_Mono = (PlatformID)128; + + /// + /// Platform ID for XBox as defined by .NET and Mono, but not CF + /// + public static readonly PlatformID XBoxPlatformID = (PlatformID)5; + + /// + /// Platform ID for MacOSX as defined by .NET and Mono, but not CF + /// + public static readonly PlatformID MacOSXPlatformID = (PlatformID)6; + + /// + /// Get the OSPlatform under which we are currently running + /// + public static OSPlatform CurrentPlatform + { + get + { + return currentPlatform.Value; + } + } + +#if !SILVERLIGHT && !NETCF + /// + /// Gets the actual OS Version, not the incorrect value that might be + /// returned for Win 8.1 and Win 10 + /// + /// + /// If an application is not manifested as Windows 8.1 or Windows 10, + /// the version returned from Environment.OSVersion will not be 6.3 and 10.0 + /// respectively, but will be 6.2 and 6.3. The correct value can be found in + /// the registry. + /// + /// The original version + /// The correct OS version + private static Version GetWindows81PlusVersion(Version version) + { + try + { + using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) + { + if (key != null) + { + var buildStr = key.GetValue("CurrentBuildNumber") as string; + int build = 0; + int.TryParse(buildStr, out build); + + // These two keys are in Windows 10 only and are DWORDS + var major = key.GetValue("CurrentMajorVersionNumber") as int?; + var minor = key.GetValue("CurrentMinorVersionNumber") as int?; + if (major.HasValue && minor.HasValue) + { + return new Version(major.Value, minor.Value, build); + } + + // If we get here, we are not Windows 10, so we are Windows 8 + // or 8.1. 8.1 might report itself as 6.2, but will have 6.3 + // in the registry. We can't do this earlier because for backwards + // compatibility, Windows 10 also has 6.3 for this key. + var currentVersion = key.GetValue("CurrentVersion") as string; + if(currentVersion == "6.3") + { + return new Version(6, 3, build); + } + } + } + } + catch (Exception) + { + } + return version; + } +#endif + #endregion + + #region Members used for Win32NT platform only + /// + /// Product Type Enumeration used for Windows + /// + public enum ProductType + { + /// + /// Product type is unknown or unspecified + /// + Unknown, + + /// + /// Product type is Workstation + /// + WorkStation, + + /// + /// Product type is Domain Controller + /// + DomainController, + + /// + /// Product type is Server + /// + Server, + } + + [StructLayout(LayoutKind.Sequential)] + struct OSVERSIONINFOEX + { + public uint dwOSVersionInfoSize; + public readonly uint dwMajorVersion; + public readonly uint dwMinorVersion; + public readonly uint dwBuildNumber; + public readonly uint dwPlatformId; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public readonly string szCSDVersion; + public readonly Int16 wServicePackMajor; + public readonly Int16 wServicePackMinor; + public readonly Int16 wSuiteMask; + public readonly Byte ProductType; + public readonly Byte Reserved; + } + + [DllImport("Kernel32.dll")] + private static extern bool GetVersionEx(ref OSVERSIONINFOEX osvi); + #endregion + + /// + /// Construct from a platform ID and version + /// + public OSPlatform(PlatformID platform, Version version) + { + _platform = platform; + _version = version; + } + + /// + /// Construct from a platform ID, version and product type + /// + public OSPlatform(PlatformID platform, Version version, ProductType product) + : this( platform, version ) + { + _product = product; + } + + /// + /// Get the platform ID of this instance + /// + public PlatformID Platform + { + get { return _platform; } + } + + /// + /// Get the Version of this instance + /// + public Version Version + { + get { return _version; } + } + + /// + /// Get the Product Type of this instance + /// + public ProductType Product + { + get { return _product; } + } + + /// + /// Return true if this is a windows platform + /// + public bool IsWindows + { + get + { + return _platform == PlatformID.Win32NT + || _platform == PlatformID.Win32Windows + || _platform == PlatformID.Win32S + || _platform == PlatformID.WinCE; + } + } + + /// + /// Return true if this is a Unix or Linux platform + /// + public bool IsUnix + { + get + { + return _platform == UnixPlatformID_Microsoft + || _platform == UnixPlatformID_Mono; + } + } + + /// + /// Return true if the platform is Win32S + /// + public bool IsWin32S + { + get { return _platform == PlatformID.Win32S; } + } + + /// + /// Return true if the platform is Win32Windows + /// + public bool IsWin32Windows + { + get { return _platform == PlatformID.Win32Windows; } + } + + /// + /// Return true if the platform is Win32NT + /// + public bool IsWin32NT + { + get { return _platform == PlatformID.Win32NT; } + } + + /// + /// Return true if the platform is Windows CE + /// + public bool IsWinCE + { + get { return _platform == PlatformID.WinCE; } + } + + /// + /// Return true if the platform is Xbox + /// + public bool IsXbox + { + get { return _platform == XBoxPlatformID; } + } + + /// + /// Return true if the platform is MacOSX + /// + public bool IsMacOSX + { + get { return _platform == MacOSXPlatformID; } + } + +#if !NETCF && !SILVERLIGHT + [DllImport("libc")] + static extern int uname(IntPtr buf); + + static bool CheckIfIsMacOSX(PlatformID platform) + { + if (platform == PlatformID.MacOSX) + return true; + + if (platform != PlatformID.Unix) + return false; + + IntPtr buf = Marshal.AllocHGlobal(8192); + bool isMacOSX = false; + if (uname(buf) == 0) + { + string os = Marshal.PtrToStringAnsi(buf); + isMacOSX = os.Equals("Darwin"); + } + Marshal.FreeHGlobal(buf); + return isMacOSX; + } +#endif + + /// + /// Return true if the platform is Windows 95 + /// + public bool IsWin95 + { + get { return _platform == PlatformID.Win32Windows && _version.Major == 4 && _version.Minor == 0; } + } + + /// + /// Return true if the platform is Windows 98 + /// + public bool IsWin98 + { + get { return _platform == PlatformID.Win32Windows && _version.Major == 4 && _version.Minor == 10; } + } + + /// + /// Return true if the platform is Windows ME + /// + public bool IsWinME + { + get { return _platform == PlatformID.Win32Windows && _version.Major == 4 && _version.Minor == 90; } + } + + /// + /// Return true if the platform is NT 3 + /// + public bool IsNT3 + { + get { return _platform == PlatformID.Win32NT && _version.Major == 3; } + } + + /// + /// Return true if the platform is NT 4 + /// + public bool IsNT4 + { + get { return _platform == PlatformID.Win32NT && _version.Major == 4; } + } + + /// + /// Return true if the platform is NT 5 + /// + public bool IsNT5 + { + get { return _platform == PlatformID.Win32NT && _version.Major == 5; } + } + + /// + /// Return true if the platform is Windows 2000 + /// + public bool IsWin2K + { + get { return IsNT5 && _version.Minor == 0; } + } + + /// + /// Return true if the platform is Windows XP + /// + public bool IsWinXP + { + get { return IsNT5 && (_version.Minor == 1 || _version.Minor == 2 && Product == ProductType.WorkStation); } + } + + /// + /// Return true if the platform is Windows 2003 Server + /// + public bool IsWin2003Server + { + get { return IsNT5 && _version.Minor == 2 && Product == ProductType.Server; } + } + + /// + /// Return true if the platform is NT 6 + /// + public bool IsNT6 + { + get { return _platform == PlatformID.Win32NT && _version.Major == 6; } + } + + /// + /// Return true if the platform is NT 6.0 + /// + public bool IsNT60 + { + get { return IsNT6 && _version.Minor == 0; } + } + + /// + /// Return true if the platform is NT 6.1 + /// + public bool IsNT61 + { + get { return IsNT6 && _version.Minor == 1; } + } + + /// + /// Return true if the platform is NT 6.2 + /// + public bool IsNT62 + { + get { return IsNT6 && _version.Minor == 2; } + } + + /// + /// Return true if the platform is NT 6.3 + /// + public bool IsNT63 + { + get { return IsNT6 && _version.Minor == 3; } + } + + /// + /// Return true if the platform is Vista + /// + public bool IsVista + { + get { return IsNT60 && Product == ProductType.WorkStation; } + } + + /// + /// Return true if the platform is Windows 2008 Server (original or R2) + /// + public bool IsWin2008Server + { + get { return IsWin2008ServerR1 || IsWin2008ServerR2; } + } + + /// + /// Return true if the platform is Windows 2008 Server (original) + /// + public bool IsWin2008ServerR1 + { + get { return IsNT60 && Product == ProductType.Server; } + } + + /// + /// Return true if the platform is Windows 2008 Server R2 + /// + public bool IsWin2008ServerR2 + { + get { return IsNT61 && Product == ProductType.Server; } + } + + /// + /// Return true if the platform is Windows 2012 Server (original or R2) + /// + public bool IsWin2012Server + { + get { return IsWin2012ServerR1 || IsWin2012ServerR2; } + } + + /// + /// Return true if the platform is Windows 2012 Server (original) + /// + public bool IsWin2012ServerR1 + { + get { return IsNT62 && Product == ProductType.Server; } + } + + /// + /// Return true if the platform is Windows 2012 Server R2 + /// + public bool IsWin2012ServerR2 + { + get { return IsNT63 && Product == ProductType.Server; } + } + + /// + /// Return true if the platform is Windows 7 + /// + public bool IsWindows7 + { + get { return IsNT61 && Product == ProductType.WorkStation; } + } + + /// + /// Return true if the platform is Windows 8 + /// + public bool IsWindows8 + { + get { return IsNT62 && Product == ProductType.WorkStation; } + } + + /// + /// Return true if the platform is Windows 8.1 + /// + public bool IsWindows81 + { + get { return IsNT63 && Product == ProductType.WorkStation; } + } + + /// + /// Return true if the platform is Windows 10 + /// + public bool IsWindows10 + { + get { return _platform == PlatformID.Win32NT && _version.Major == 10 && Product == ProductType.WorkStation; } + } + + /// + /// Return true if the platform is Windows Server. This is named Windows + /// Server 10 to distinguish it from previous versions of Windows Server. + /// + public bool IsWindowsServer10 + { + get { return _platform == PlatformID.Win32NT && _version.Major == 10 && Product == ProductType.Server; } + } + } +} +#endif \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/ParameterWrapper.cs b/test/NUnitLite/NUnitFramework/framework/Internal/ParameterWrapper.cs new file mode 100644 index 000000000..4f11bc253 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/ParameterWrapper.cs @@ -0,0 +1,113 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +#if PORTABLE +using System.Linq; +#endif + +namespace NUnit.Framework.Internal +{ + /// + /// The ParameterWrapper class wraps a ParameterInfo so that it may + /// be used in a platform-independent manner. + /// + public class ParameterWrapper : IParameterInfo + { + /// + /// Construct a ParameterWrapper for a given method and parameter + /// + /// + /// + public ParameterWrapper(IMethodInfo method, ParameterInfo parameterInfo) + { + Method = method; + ParameterInfo = parameterInfo; + } + + #region Properties + +#if !NETCF + /// + /// Gets a value indicating whether the parameter is optional + /// + public bool IsOptional + { + get { return ParameterInfo.IsOptional; } + } +#endif + + /// + /// Gets an IMethodInfo representing the method for which this is a parameter. + /// + public IMethodInfo Method { get; private set; } + + /// + /// Gets the underlying ParameterInfo + /// + public ParameterInfo ParameterInfo { get; private set; } + + /// + /// Gets the Type of the parameter + /// + public Type ParameterType + { + get { return ParameterInfo.ParameterType; } + } + + #endregion + + #region Methods + + /// + /// Returns an array of custom attributes of the specified type applied to this method + /// + public T[] GetCustomAttributes(bool inherit) where T : class + { +#if PORTABLE + return ParameterInfo.GetAttributes(inherit).ToArray(); +#else + return (T[])ParameterInfo.GetCustomAttributes(typeof(T), inherit); +#endif + } + + /// + /// Gets a value indicating whether one or more attributes of the specified type are defined on the parameter. + /// + public bool IsDefined(bool inherit) + { +#if PORTABLE + return ParameterInfo.GetCustomAttributes(inherit).Any(a => typeof(T).IsAssignableFrom(a.GetType())); +#else + return ParameterInfo.IsDefined(typeof(T), inherit); +#endif + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/PlatformHelper.cs b/test/NUnitLite/NUnitFramework/framework/Internal/PlatformHelper.cs new file mode 100644 index 000000000..963b45206 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/PlatformHelper.cs @@ -0,0 +1,355 @@ +// *********************************************************************** +// Copyright (c) 2007-2016 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +#if !PORTABLE +using System; +using System.Linq; + +namespace NUnit.Framework.Internal +{ + /// + /// PlatformHelper class is used by the PlatformAttribute class to + /// determine whether a platform is supported. + /// + public class PlatformHelper + { + private readonly OSPlatform _os; + private readonly RuntimeFramework _rt; + + // Set whenever we fail to support a list of platforms + private string _reason = string.Empty; + + const string CommonOSPlatforms = + "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6," + + "Win2008Server,Win2008ServerR2,Win2012Server,Win2012ServerR2," + + "Win2K,WinXP,Win2003Server,Vista,Win7,Windows7,Win8,Windows8,"+ + "Win8.1,Windows8.1,Win10,Windows10,WindowsServer10,Unix,Linux"; + + /// + /// Comma-delimited list of all supported OS platform constants + /// +#if NETCF + public const string OSPlatforms = CommonOSPlatforms; +#else + public const string OSPlatforms = CommonOSPlatforms + ",Xbox,MacOSX"; +#endif + + /// + /// Comma-delimited list of all supported Runtime platform constants + /// + public static readonly string RuntimePlatforms = + "Net,NetCF,SSCLI,Rotor,Mono,MonoTouch"; + + /// + /// Default constructor uses the operating system and + /// common language runtime of the system. + /// + public PlatformHelper() + { + _os = OSPlatform.CurrentPlatform; + _rt = RuntimeFramework.CurrentFramework; + } + + /// + /// Construct a PlatformHelper for a particular operating + /// system and common language runtime. Used in testing. + /// + /// OperatingSystem to be used + /// RuntimeFramework to be used + public PlatformHelper( OSPlatform os, RuntimeFramework rt ) + { + _os = os; + _rt = rt; + } + + /// + /// Test to determine if one of a collection of platforms + /// is being used currently. + /// + /// + /// + public bool IsPlatformSupported( string[] platforms ) + { + return platforms.Any( IsPlatformSupported ); + } + + /// + /// Tests to determine if the current platform is supported + /// based on a platform attribute. + /// + /// The attribute to examine + /// + public bool IsPlatformSupported( PlatformAttribute platformAttribute ) + { + string include = platformAttribute.Include; + string exclude = platformAttribute.Exclude; + + return IsPlatformSupported( include, exclude ); + } + + /// + /// Tests to determine if the current platform is supported + /// based on a platform attribute. + /// + /// The attribute to examine + /// + public bool IsPlatformSupported(TestCaseAttribute testCaseAttribute) + { + string include = testCaseAttribute.IncludePlatform; + string exclude = testCaseAttribute.ExcludePlatform; + + return IsPlatformSupported(include, exclude); + } + + private bool IsPlatformSupported(string include, string exclude) + { + try + { + if (include != null && !IsPlatformSupported(include)) + { + _reason = string.Format("Only supported on {0}", include); + return false; + } + + if (exclude != null && IsPlatformSupported(exclude)) + { + _reason = string.Format("Not supported on {0}", exclude); + return false; + } + } + catch (Exception ex) + { + _reason = ex.Message; + return false; + } + + return true; + } + + /// + /// Test to determine if the a particular platform or comma- + /// delimited set of platforms is in use. + /// + /// Name of the platform or comma-separated list of platform ids + /// True if the platform is in use on the system + public bool IsPlatformSupported( string platform ) + { + if ( platform.IndexOf( ',' ) >= 0 ) + return IsPlatformSupported( platform.Split(',') ); + + string platformName = platform.Trim(); + bool isSupported; + +// string versionSpecification = null; +// +// string[] parts = platformName.Split( new char[] { '-' } ); +// if ( parts.Length == 2 ) +// { +// platformName = parts[0]; +// versionSpecification = parts[1]; +// } + + switch( platformName.ToUpper() ) + { + case "WIN": + case "WIN32": + isSupported = _os.IsWindows; + break; + case "WIN32S": + isSupported = _os.IsWin32S; + break; + case "WIN32WINDOWS": + isSupported = _os.IsWin32Windows; + break; + case "WIN32NT": + isSupported = _os.IsWin32NT; + break; + case "WINCE": + isSupported = _os.IsWinCE; + break; + case "WIN95": + isSupported = _os.IsWin95; + break; + case "WIN98": + isSupported = _os.IsWin98; + break; + case "WINME": + isSupported = _os.IsWinME; + break; + case "NT3": + isSupported = _os.IsNT3; + break; + case "NT4": + isSupported = _os.IsNT4; + break; + case "NT5": + isSupported = _os.IsNT5; + break; + case "WIN2K": + isSupported = _os.IsWin2K; + break; + case "WINXP": + isSupported = _os.IsWinXP; + break; + case "WIN2003SERVER": + isSupported = _os.IsWin2003Server; + break; + case "NT6": + isSupported = _os.IsNT6; + break; + case "VISTA": + isSupported = _os.IsVista; + break; + case "WIN2008SERVER": + isSupported = _os.IsWin2008Server; + break; + case "WIN2008SERVERR2": + isSupported = _os.IsWin2008ServerR2; + break; + case "WIN2012SERVER": + isSupported = _os.IsWin2012ServerR1 || _os.IsWin2012ServerR2; + break; + case "WIN2012SERVERR2": + isSupported = _os.IsWin2012ServerR2; + break; + case "WIN7": + case "WINDOWS7": + isSupported = _os.IsWindows7; + break; + case "WINDOWS8": + case "WIN8": + isSupported = _os.IsWindows8; + break; + case "WINDOWS8.1": + case "WIN8.1": + isSupported = _os.IsWindows81; + break; + case "WINDOWS10": + case "WIN10": + isSupported = _os.IsWindows10; + break; + case "WINDOWSSERVER10": + isSupported = _os.IsWindowsServer10; + break; + case "UNIX": + case "LINUX": + isSupported = _os.IsUnix; + break; + case "XBOX": + isSupported = _os.IsXbox; + break; + case "MACOSX": + isSupported = _os.IsMacOSX; + break; + // These bitness tests relate to the process, not the OS. + // We can't use Environment.Is64BitProcess because it's + // only supported in NET 4.0 and higher. + case "64-BIT": + case "64-BIT-PROCESS": + isSupported = IntPtr.Size == 8; + break; + case "32-BIT": + case "32-BIT-PROCESS": + isSupported = IntPtr.Size == 4; + break; + +#if NET_4_0 || NET_4_5 + // We only support bitness tests of the OS in .NET 4.0 and up + case "64-BIT-OS": + isSupported = Environment.Is64BitOperatingSystem; + break; + case "32-BIT-OS": + isSupported = !Environment.Is64BitOperatingSystem; + break; +#endif + + default: + isSupported = IsRuntimeSupported(platformName); + break; + } + + if (!isSupported) + _reason = "Only supported on " + platform; + + return isSupported; + } + + /// + /// Return the last failure reason. Results are not + /// defined if called before IsSupported( Attribute ) + /// is called. + /// + public string Reason + { + get { return _reason; } + } + + private bool IsRuntimeSupported(string platformName) + { + string versionSpecification = null; + string[] parts = platformName.Split('-'); + if (parts.Length == 2) + { + platformName = parts[0]; + versionSpecification = parts[1]; + } + + switch (platformName.ToUpper()) + { + case "NET": + return IsRuntimeSupported(RuntimeType.Net, versionSpecification); + + case "NETCF": + return IsRuntimeSupported(RuntimeType.NetCF, versionSpecification); + + case "SSCLI": + case "ROTOR": + return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification); + + case "MONO": + return IsRuntimeSupported(RuntimeType.Mono, versionSpecification); + + case "SL": + case "SILVERLIGHT": + return IsRuntimeSupported(RuntimeType.Silverlight, versionSpecification); + + case "MONOTOUCH": + return IsRuntimeSupported(RuntimeType.MonoTouch, versionSpecification); + + default: + throw new ArgumentException("Invalid platform name", platformName); + } + } + + private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification) + { + Version version = versionSpecification == null + ? RuntimeFramework.DefaultVersion + : new Version(versionSpecification); + + RuntimeFramework target = new RuntimeFramework(runtime, version); + + return _rt.Supports(target); + } + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/PropertyBag.cs b/test/NUnitLite/NUnitFramework/framework/Internal/PropertyBag.cs new file mode 100644 index 000000000..85597a6f2 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/PropertyBag.cs @@ -0,0 +1,178 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// A PropertyBag represents a collection of name value pairs + /// that allows duplicate entries with the same key. Methods + /// are provided for adding a new pair as well as for setting + /// a key to a single value. All keys are strings but _values + /// may be of any type. Null _values are not permitted, since + /// a null entry represents the absence of the key. + /// + public class PropertyBag : IPropertyBag + { + private Dictionary inner = new Dictionary(); + + #region IPropertyBagMembers + + /// + /// Adds a key/value pair to the property set + /// + /// The key + /// The value + public void Add(string key, object value) + { + IList list; + if (!inner.TryGetValue(key, out list)) + { + list = new List(); + inner.Add(key, list); + } + list.Add(value); + } + + /// + /// Sets the value for a key, removing any other + /// _values that are already in the property set. + /// + /// + /// + public void Set(string key, object value) + { + // Guard against mystery exceptions later! + Guard.ArgumentNotNull(key, "key"); + Guard.ArgumentNotNull(value, "value"); + + IList list = new List(); + list.Add(value); + inner[key] = list; + } + + /// + /// Gets a single value for a key, using the first + /// one if multiple _values are present and returning + /// null if the value is not found. + /// + /// + /// + public object Get(string key) + { + IList list; + return inner.TryGetValue(key, out list) && list.Count > 0 + ? list[0] + : null; + } + + /// + /// Gets a flag indicating whether the specified key has + /// any entries in the property set. + /// + /// The key to be checked + /// + /// True if their are _values present, otherwise false + /// + public bool ContainsKey(string key) + { + return inner.ContainsKey(key); + } + + /// + /// Gets a collection containing all the keys in the property set + /// + /// + public ICollection Keys + { + get { return inner.Keys; } + } + + /// + /// Gets or sets the list of _values for a particular key + /// + public IList this[string key] + { + get + { + IList list; + if (!inner.TryGetValue(key, out list)) + { + list = new List(); + inner.Add(key, list); + } + return list; + } + set + { + inner[key] = value; + } + } + + #endregion + + #region IXmlNodeBuilder Members + + /// + /// Returns an XmlNode representating the current PropertyBag. + /// + /// Not used + /// An XmlNode representing the PropertyBag + public TNode ToXml(bool recursive) + { + return AddToXml(new TNode("dummy"), recursive); + } + + /// + /// Returns an XmlNode representing the PropertyBag after + /// adding it as a child of the supplied parent node. + /// + /// The parent node. + /// Not used + /// + public TNode AddToXml(TNode parentNode, bool recursive) + { + TNode properties = parentNode.AddElement("properties"); + + foreach (string key in Keys) + { + foreach (object value in this[key]) + { + TNode prop = properties.AddElement("property"); + + // TODO: Format as string + prop.AddAttribute("name", key.ToString()); + prop.AddAttribute("value", value.ToString()); + } + } + + return properties; + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/PropertyNames.cs b/test/NUnitLite/NUnitFramework/framework/Internal/PropertyNames.cs new file mode 100644 index 000000000..be466233f --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/PropertyNames.cs @@ -0,0 +1,142 @@ +// *********************************************************************** +// Copyright (c) 2010 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; + +namespace NUnit.Framework.Internal +{ + /// + /// The PropertyNames class provides static constants for the + /// standard property ids that NUnit uses on tests. + /// + public class PropertyNames + { + #region Internal Properties + + /// + /// The FriendlyName of the AppDomain in which the assembly is running + /// + public const string AppDomain = "_APPDOMAIN"; + + /// + /// The selected strategy for joining parameter data into test cases + /// + public const string JoinType = "_JOINTYPE"; + + /// + /// The process ID of the executing assembly + /// + public const string ProcessID = "_PID"; + + /// + /// The stack trace from any data provider that threw + /// an exception. + /// + public const string ProviderStackTrace = "_PROVIDERSTACKTRACE"; + + /// + /// The reason a test was not run + /// + public const string SkipReason = "_SKIPREASON"; + + #endregion + + #region Standard Properties + + /// + /// The author of the tests + /// + public const string Author = "Author"; + + /// + /// The ApartmentState required for running the test + /// + public const string ApartmentState = "ApartmentState"; + + /// + /// The categories applying to a test + /// + public const string Category = "Category"; + + /// + /// The Description of a test + /// + public const string Description = "Description"; + + /// + /// The number of threads to be used in running tests + /// + public const string LevelOfParallelism = "LevelOfParallelism"; + + /// + /// The maximum time in ms, above which the test is considered to have failed + /// + public const string MaxTime = "MaxTime"; + + /// + /// The ParallelScope associated with a test + /// + public const string ParallelScope = "ParallelScope"; + + /// + /// The number of times the test should be repeated + /// + public const string RepeatCount = "Repeat"; + + /// + /// Indicates that the test should be run on a separate thread + /// + public const string RequiresThread = "RequiresThread"; + + /// + /// The culture to be set for a test + /// + public const string SetCulture = "SetCulture"; + + /// + /// The UI culture to be set for a test + /// + public const string SetUICulture = "SetUICulture"; + + /// + /// The type that is under test + /// + public const string TestOf = "TestOf"; + + /// + /// The timeout value for the test + /// + public const string Timeout = "Timeout"; + + /// + /// The test will be ignored until the given date + /// + public const string IgnoreUntilDate = "IgnoreUntilDate"; + + /// + /// The optional Order the test will run in + /// + public const string Order = "Order"; + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Randomizer.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Randomizer.cs new file mode 100644 index 000000000..ed7c48398 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Randomizer.cs @@ -0,0 +1,658 @@ +// *********************************************************************** +// Copyright (c) 2013-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace NUnit.Framework.Internal +{ + /// + /// Randomizer returns a set of random _values in a repeatable + /// way, to allow re-running of tests if necessary. It extends + /// the .NET Random class, providing random values for a much + /// wider range of types. + /// + /// The class is used internally by the framework to generate + /// test case data and is also exposed for use by users through + /// the TestContext.Random property. + /// + /// + /// For consistency with the underlying Random Type, methods + /// returning a single value use the prefix "Next..." Those + /// without an argument return a non-negative value up to + /// the full positive range of the Type. Overloads are provided + /// for specifying a maximum or a range. Methods that return + /// arrays or strings use the prefix "Get..." to avoid + /// confusion with the single-value methods. + /// + public class Randomizer : Random + { + #region Static Members + + // Static constructor initializes values + static Randomizer() + { + InitialSeed = new Random().Next(); + Randomizers = new Dictionary(); + } + + // Static Random instance used exclusively for the generation + // of seed values for new Randomizers. + private static Random _seedGenerator; + + /// + /// Initial seed used to create randomizers for this run + /// + public static int InitialSeed + { + get { return _initialSeed; } + set + { + _initialSeed = value; + // Setting or resetting the initial seed creates seed generator + _seedGenerator = new Random(_initialSeed); + } + } + private static int _initialSeed; + + // Lookup Dictionary used to find randomizers for each member + private static Dictionary Randomizers; + + /// + /// Get a Randomizer for a particular member, returning + /// one that has already been created if it exists. + /// This ensures that the same _values are generated + /// each time the tests are reloaded. + /// + public static Randomizer GetRandomizer(MemberInfo member) + { + if (Randomizers.ContainsKey(member)) + return Randomizers[member]; + else + { + var r = CreateRandomizer(); + Randomizers[member] = r; + return r; + } + } + + + /// + /// Get a randomizer for a particular parameter, returning + /// one that has already been created if it exists. + /// This ensures that the same values are generated + /// each time the tests are reloaded. + /// + public static Randomizer GetRandomizer(ParameterInfo parameter) + { + return GetRandomizer(parameter.Member); + } + + /// + /// Create a new Randomizer using the next seed + /// available to ensure that each randomizer gives + /// a unique sequence of values. + /// + /// + public static Randomizer CreateRandomizer() + { + return new Randomizer(_seedGenerator.Next()); + } + + #endregion + + #region Constructors + + /// + /// Default constructor + /// + public Randomizer() { } + + /// + /// Construct based on seed value + /// + /// + public Randomizer(int seed) : base(seed) { } + + #endregion + + #region Ints + + // NOTE: Next(), Next(int max) and Next(int min, int max) are + // inherited from Random. + + #endregion + + #region Unsigned Ints + + /// + /// Returns a random unsigned int. + /// + [CLSCompliant(false)] + public uint NextUInt() + { + return NextUInt(0u, uint.MaxValue); + } + + /// + /// Returns a random unsigned int less than the specified maximum. + /// + [CLSCompliant(false)] + public uint NextUInt(uint max) + { + return NextUInt(0u, max); + } + + /// + /// Returns a random unsigned int within a specified range. + /// + [CLSCompliant(false)] + public uint NextUInt(uint min, uint max) + { + Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max"); + + if (min == max) + return min; + + uint range = max - min; + + // Avoid introduction of modulo bias + uint limit = uint.MaxValue - uint.MaxValue % range; + uint raw; + do + { + raw = RawUInt(); + } + while (raw > limit); + + return unchecked(raw % range + min); + } + + #endregion + + #region Shorts + + /// + /// Returns a non-negative random short. + /// + public short NextShort() + { + return NextShort(0, short.MaxValue); + } + + /// + /// Returns a non-negative random short less than the specified maximum. + /// + public short NextShort(short max) + { + return NextShort((short)0, max); + } + + /// + /// Returns a non-negative random short within a specified range. + /// + public short NextShort(short min, short max) + { + return (short)Next(min, max); + } + + #endregion + + #region Unsigned Shorts + + /// + /// Returns a random unsigned short. + /// + [CLSCompliant(false)] + public ushort NextUShort() + { + return NextUShort((ushort)0, ushort.MaxValue); + } + + /// + /// Returns a random unsigned short less than the specified maximum. + /// + [CLSCompliant(false)] + public ushort NextUShort(ushort max) + { + return NextUShort((ushort)0, max); + } + + /// + /// Returns a random unsigned short within a specified range. + /// + [CLSCompliant(false)] + public ushort NextUShort(ushort min, ushort max) + { + return (ushort)Next(min, max); + } + + #endregion + + #region Longs + + /// + /// Returns a random long. + /// + public long NextLong() + { + return NextLong(0L, long.MaxValue); + } + + /// + /// Returns a random long less than the specified maximum. + /// + public long NextLong(long max) + { + return NextLong(0L, max); + } + + /// + /// Returns a non-negative random long within a specified range. + /// + public long NextLong(long min, long max) + { + Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max"); + + if (min == max) + return min; + + ulong range = (ulong)(max - min); + + // Avoid introduction of modulo bias + ulong limit = ulong.MaxValue - ulong.MaxValue % range; + ulong raw; + do + { + raw = RawULong(); + } + while (raw > limit); + + return (long)(raw % range + (ulong)min); + } + + #endregion + + #region Unsigned Longs + + /// + /// Returns a random ulong. + /// + [CLSCompliant(false)] + public ulong NextULong() + { + return NextULong(0ul, ulong.MaxValue); + } + + /// + /// Returns a random ulong less than the specified maximum. + /// + [CLSCompliant(false)] + public ulong NextULong(ulong max) + { + return NextULong(0ul, max); + } + + /// + /// Returns a non-negative random long within a specified range. + /// + [CLSCompliant(false)] + public ulong NextULong(ulong min, ulong max) + { + Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max"); + + ulong range = max - min; + + if (range == 0) + return min; + + // Avoid introduction of modulo bias + ulong limit = ulong.MaxValue - ulong.MaxValue % range; + ulong raw; + do + { + raw = RawULong(); + } + while (raw > limit); + + return unchecked(raw % range + min); + } + + #endregion + + #region Bytes + + /// + /// Returns a random Byte + /// + public byte NextByte() + { + return NextByte((byte)0, Byte.MaxValue); + } + + /// + /// Returns a random Byte less than the specified maximum. + /// + public byte NextByte(byte max) + { + return NextByte((byte)0, max); + } + + /// + /// Returns a random Byte within a specified range + /// + public byte NextByte(byte min, byte max) + { + return (byte)Next(min, max); + } + + #endregion + + #region SBytes + + /// + /// Returns a random SByte + /// + [CLSCompliant(false)] + public sbyte NextSByte() + { + return NextSByte((sbyte)0, SByte.MaxValue); + } + + /// + /// Returns a random sbyte less than the specified maximum. + /// + [CLSCompliant(false)] + public sbyte NextSByte(sbyte max) + { + return NextSByte((sbyte)0, max); + } + + /// + /// Returns a random sbyte within a specified range + /// + [CLSCompliant(false)] + public sbyte NextSByte(sbyte min, sbyte max) + { + return (sbyte)Next(min, max); + } + + #endregion + + #region Bools + + /// + /// Returns a random bool + /// + public bool NextBool() + { + return NextDouble() < 0.5; + } + + /// + /// Returns a random bool based on the probablility a true result + /// + public bool NextBool(double probability) + { + Guard.ArgumentInRange(probability >= 0.0 && probability <= 1.0, "Probability must be from 0.0 to 1.0", "probability"); + + return NextDouble() < probability; + } + + #endregion + + #region Doubles + + // NOTE: NextDouble() is inherited from Random. + + /// + /// Returns a random double between 0.0 and the specified maximum. + /// + public double NextDouble(double max) + { + return NextDouble() * max; + } + + /// + /// Returns a random double within a specified range. + /// + public double NextDouble(double min, double max) + { + Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max"); + + if (max == min) + return min; + + double range = max - min; + return NextDouble() * range + min; + } + + #endregion + + #region Floats + + /// + /// Returns a random float. + /// + public float NextFloat() + { + return (float)NextDouble(); + } + + /// + /// Returns a random float between 0.0 and the specified maximum. + /// + public float NextFloat(float max) + { + return (float)NextDouble(max); + } + + /// + /// Returns a random float within a specified range. + /// + public float NextFloat(float min, float max) + { + return (float)NextDouble(min, max); + } + + #endregion + + #region Enums + + /// + /// Returns a random enum value of the specified Type as an object. + /// + public object NextEnum(Type type) + { + Array enums = TypeHelper.GetEnumValues(type); + return enums.GetValue(Next(0, enums.Length)); + } + + /// + /// Returns a random enum value of the specified Type. + /// + public T NextEnum() + { + return (T)NextEnum(typeof(T)); + } + + #endregion + + #region String + + /// + /// Default characters for random functions. + /// + /// Default characters are the English alphabet (uppercase & lowercase), arabic numerals, and underscore + public const string DefaultStringChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789_"; + + private const int DefaultStringLength = 25; + + /// + /// Generate a random string based on the characters from the input string. + /// + /// desired length of output string. + /// string representing the set of characters from which to construct the resulting string + /// A random string of arbitrary length + public string GetString(int outputLength, string allowedChars) + { + + var sb = new StringBuilder(outputLength); + + for (int i = 0; i < outputLength ; i++) + { + sb.Append(allowedChars[Next(0,allowedChars.Length)]); + } + + return sb.ToString(); + } + + /// + /// Generate a random string based on the characters from the input string. + /// + /// desired length of output string. + /// A random string of arbitrary length + /// Uses DefaultStringChars as the input character set + public string GetString(int outputLength) + { + return GetString(outputLength, DefaultStringChars); + } + + /// + /// Generate a random string based on the characters from the input string. + /// + /// A random string of the default length + /// Uses DefaultStringChars as the input character set + public string GetString() + { + return GetString(DefaultStringLength, DefaultStringChars); + } + + #endregion + + #region Decimal + + // We treat decimal as an integral type for now. + // The scaling factor is always zero. + + /// + /// Returns a random decimal. + /// + public decimal NextDecimal() + { + int low = Next(0, int.MaxValue); + int mid = Next(0, int.MaxValue); + int high = Next(0, int.MaxValue); + return new Decimal(low, mid, high, false, 0); + } + + /// + /// Returns a random decimal between positive zero and the specified maximum. + /// + public decimal NextDecimal(decimal max) + { + return NextDecimal() % max; + } + + /// + /// Returns a random decimal within a specified range, which is not + /// permitted to exceed decimal.MaxVal in the current implementation. + /// + /// + /// A limitation of this implementation is that the range from min + /// to max must not exceed decimal.MaxVal. + /// + public decimal NextDecimal(decimal min, decimal max) + { + Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", "max"); + + // Check that the range is not greater than MaxValue without + // first calculating it, since this would cause overflow + Guard.ArgumentValid(max < 0M == min < 0M || min + decimal.MaxValue >= max, + "Range too great for decimal data, use double range", "max"); + + if (min == max) + return min; + + decimal range = max - min; + + // Avoid introduction of modulo bias + decimal limit = decimal.MaxValue - decimal.MaxValue % range; + decimal raw; + do + { + raw = NextDecimal(); + } + while (raw > limit); + + return unchecked(raw % range + min); + } + + #endregion + + #region Helper Methods + + private uint RawUInt() + { + var buffer = new byte[sizeof(uint)]; + NextBytes(buffer); + return BitConverter.ToUInt32(buffer, 0); + } + + private uint RawUShort() + { + var buffer = new byte[sizeof(uint)]; + NextBytes(buffer); + return BitConverter.ToUInt32(buffer, 0); + } + + private ulong RawULong() + { + var buffer = new byte[sizeof(ulong)]; + NextBytes(buffer); + return BitConverter.ToUInt64(buffer, 0); + } + + private long RawLong() + { + var buffer = new byte[sizeof(long)]; + NextBytes(buffer); + return BitConverter.ToInt64(buffer, 0); + } + + private decimal RawDecimal() + { + int low = Next(0, int.MaxValue); + int mid = Next(0, int.MaxValue); + int hi = Next(0, int.MaxValue); + bool isNegative = NextBool(); + byte scale = NextByte(29); + return new Decimal(low, mid, hi, isNegative, scale); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Reflect.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Reflect.cs new file mode 100644 index 000000000..04af81dc6 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Reflect.cs @@ -0,0 +1,249 @@ +// *********************************************************************** +// Copyright (c) 2007-2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +#if PORTABLE +using System.Linq; +#endif + +namespace NUnit.Framework.Internal +{ + /// + /// Helper methods for inspecting a type by reflection. + /// + /// Many of these methods take ICustomAttributeProvider as an + /// argument to avoid duplication, even though certain attributes can + /// only appear on specific types of members, like MethodInfo or Type. + /// + /// In the case where a type is being examined for the presence of + /// an attribute, interface or named member, the Reflect methods + /// operate with the full name of the member being sought. This + /// removes the necessity of the caller having a reference to the + /// assembly that defines the item being sought and allows the + /// NUnit core to inspect assemblies that reference an older + /// version of the NUnit framework. + /// + public static class Reflect + { + private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + + // A zero-length Type array - not provided by System.Type for all CLR versions we support. + private static readonly Type[] EmptyTypes = new Type[0]; + + #region Get Methods of a type + + /// + /// Examine a fixture type and return an array of methods having a + /// particular attribute. The array is order with base methods first. + /// + /// The type to examine + /// The attribute Type to look for + /// Specifies whether to search the fixture type inheritance chain + /// The array of methods found + public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit) + { + List list = new List(); + +#if NETCF + if (fixtureType.IsGenericTypeDefinition) + { + var genArgs = fixtureType.GetGenericArguments(); + Type[] args = new Type[genArgs.Length]; + for (int ix = 0; ix < genArgs.Length; ++ix) + { + args[ix] = typeof(object); + } + + fixtureType = fixtureType.MakeGenericType(args); + } +#endif + + var flags = AllMembers | (inherit ? BindingFlags.FlattenHierarchy : BindingFlags.DeclaredOnly); + foreach (MethodInfo method in fixtureType.GetMethods(flags)) + { + if (method.IsDefined(attributeType, inherit)) + list.Add(method); + } + + list.Sort(new BaseTypesFirstComparer()); + + return list.ToArray(); + } + + private class BaseTypesFirstComparer : IComparer + { + public int Compare(MethodInfo m1, MethodInfo m2) + { + if (m1 == null || m2 == null) return 0; + + Type m1Type = m1.DeclaringType; + Type m2Type = m2.DeclaringType; + + if ( m1Type == m2Type ) return 0; + if ( m1Type.IsAssignableFrom(m2Type) ) return -1; + + return 1; + } + } + + /// + /// Examine a fixture type and return true if it has a method with + /// a particular attribute. + /// + /// The type to examine + /// The attribute Type to look for + /// True if found, otherwise false + public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType) + { +#if PORTABLE + return fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy) + .Any(m => m.GetCustomAttributes(false).Any(a => attributeType.IsAssignableFrom(a.GetType()))); +#else + +#if NETCF + if (fixtureType.ContainsGenericParameters) + return false; +#endif + foreach (MethodInfo method in fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy)) + { + if (method.IsDefined(attributeType, false)) + return true; + } + return false; +#endif + } + + #endregion + + #region Invoke Constructors + + /// + /// Invoke the default constructor on a Type + /// + /// The Type to be constructed + /// An instance of the Type + public static object Construct(Type type) + { + ConstructorInfo ctor = type.GetConstructor(EmptyTypes); + if (ctor == null) + throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor"); + + return ctor.Invoke(null); + } + + /// + /// Invoke a constructor on a Type with arguments + /// + /// The Type to be constructed + /// Arguments to the constructor + /// An instance of the Type + public static object Construct(Type type, object[] arguments) + { + if (arguments == null) return Construct(type); + + Type[] argTypes = GetTypeArray(arguments); + ITypeInfo typeInfo = new TypeWrapper(type); + ConstructorInfo ctor = typeInfo.GetConstructor(argTypes); + if (ctor == null) + throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor"); + + return ctor.Invoke(arguments); + } + + /// + /// Returns an array of types from an array of objects. + /// Used because the compact framework doesn't support + /// Type.GetTypeArray() + /// + /// An array of objects + /// An array of Types + internal static Type[] GetTypeArray(object[] objects) + { + Type[] types = new Type[objects.Length]; + int index = 0; + foreach (object o in objects) + { + // NUnitNullType is a marker to indicate null since we can't do typeof(null) or null.GetType() + types[index++] = o == null ? typeof(NUnitNullType) : o.GetType(); + } + return types; + } + + #endregion + + #region Invoke Methods + + /// + /// Invoke a parameterless method returning void on an object. + /// + /// A MethodInfo for the method to be invoked + /// The object on which to invoke the method + public static object InvokeMethod( MethodInfo method, object fixture ) + { + return InvokeMethod(method, fixture, null); + } + + /// + /// Invoke a method, converting any TargetInvocationException to an NUnitException. + /// + /// A MethodInfo for the method to be invoked + /// The object on which to invoke the method + /// The argument list for the method + /// The return value from the invoked method + public static object InvokeMethod( MethodInfo method, object fixture, params object[] args ) + { + if(method != null) + { + try + { + return method.Invoke(fixture, args); + } +#if !PORTABLE + catch (System.Threading.ThreadAbortException) + { + // No need to wrap or rethrow ThreadAbortException + return null; + } +#endif + catch (TargetInvocationException e) + { + throw new NUnitException("Rethrown", e.InnerException); + } + catch (Exception e) + { + throw new NUnitException("Rethrown", e); + } + } + + return null; + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestCaseResult.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestCaseResult.cs new file mode 100644 index 000000000..7315a22a1 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestCaseResult.cs @@ -0,0 +1,100 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +#if PARALLEL +using System.Collections.Concurrent; +#endif +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// Represents the result of running a single test case. + /// + public class TestCaseResult : TestResult + { + /// + /// Construct a TestCaseResult based on a TestMethod + /// + /// A TestMethod to which the result applies. + public TestCaseResult(TestMethod test) : base(test) { } + + #region Overrides + + /// + /// Gets the number of test cases that failed + /// when running the test and all its children. + /// + public override int FailCount + { + get { return ResultState.Status == TestStatus.Failed ? 1 : 0; } + } + + /// + /// Gets the number of test cases that passed + /// when running the test and all its children. + /// + public override int PassCount + { + get { return ResultState.Status == TestStatus.Passed ? 1 : 0; } + } + + /// + /// Gets the number of test cases that were skipped + /// when running the test and all its children. + /// + public override int SkipCount + { + get { return ResultState.Status == TestStatus.Skipped ? 1 : 0; } + } + + /// + /// Gets the number of test cases that were inconclusive + /// when running the test and all its children. + /// + public override int InconclusiveCount + { + get { return ResultState.Status == TestStatus.Inconclusive ? 1 : 0; } + } + + /// + /// Indicates whether this result has any child results. + /// + public override bool HasChildren + { + get { return false; } + } + + /// + /// Gets the collection of child results. + /// + public override IEnumerable Children + { + get { return new ITestResult[0]; } + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestResult.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestResult.cs new file mode 100644 index 000000000..35da0d9ea --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestResult.cs @@ -0,0 +1,581 @@ +// *********************************************************************** +// Copyright (c) 2010-2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +#if PARALLEL +using System.Collections.Concurrent; +#endif +using System.Globalization; +using System.IO; +using System.Text; +#if NETCF || NET_2_0 +using NUnit.Compatibility; +#endif +using System.Threading; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// The TestResult class represents the result of a test. + /// + public abstract class TestResult : ITestResult + { + #region Fields + + /// + /// Error message for when child tests have errors + /// + internal static readonly string CHILD_ERRORS_MESSAGE = "One or more child tests had errors"; + + /// + /// Error message for when child tests are ignored + /// + internal static readonly string CHILD_IGNORE_MESSAGE = "One or more child tests were ignored"; + + /// + /// The minimum duration for tests + /// + internal const double MIN_DURATION = 0.000001d; + + // static Logger log = InternalTrace.GetLogger("TestResult"); + + private StringBuilder _output = new StringBuilder(); + private double _duration; + + /// + /// Aggregate assertion count + /// + protected int InternalAssertCount; + + private ResultState _resultState; + private string _message; + private string _stackTrace; + +#if PARALLEL + /// + /// ReaderWriterLock + /// +#if NET_2_0 + protected ReaderWriterLock RwLock = new ReaderWriterLock(); +#elif NETCF + protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(); +#else + protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); +#endif +#endif + + #endregion + + #region Constructor + + /// + /// Construct a test result given a Test + /// + /// The test to be used + public TestResult(ITest test) + { + Test = test; + ResultState = ResultState.Inconclusive; + +#if PORTABLE || SILVERLIGHT + OutWriter = new StringWriter(_output); +#else + OutWriter = TextWriter.Synchronized(new StringWriter(_output)); +#endif + } + + #endregion + + #region ITestResult Members + + /// + /// Gets the test with which this result is associated. + /// + public ITest Test { get; private set; } + + /// + /// Gets the ResultState of the test result, which + /// indicates the success or failure of the test. + /// + public ResultState ResultState + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _resultState; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + } + private set { _resultState = value; } + } + + /// + /// Gets the name of the test result + /// + public virtual string Name + { + get { return Test.Name; } + } + + /// + /// Gets the full name of the test result + /// + public virtual string FullName + { + get { return Test.FullName; } + } + + /// + /// Gets or sets the elapsed time for running the test in seconds + /// + public double Duration + { + get { return _duration; } + set { _duration = value >= MIN_DURATION ? value : MIN_DURATION; } + } + + /// + /// Gets or sets the time the test started running. + /// + public DateTime StartTime { get; set; } + + /// + /// Gets or sets the time the test finished running. + /// + public DateTime EndTime { get; set; } + + /// + /// Gets the message associated with a test + /// failure or with not running the test + /// + public string Message + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _message; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + + } + private set + { + _message = value; + } + } + + /// + /// Gets any stacktrace associated with an + /// error or failure. + /// + public virtual string StackTrace + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _stackTrace; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + } + + private set + { + _stackTrace = value; + } + } + + /// + /// Gets or sets the count of asserts executed + /// when running the test. + /// + public int AssertCount + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return InternalAssertCount; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock (); +#endif + } + } + + internal set + { + InternalAssertCount = value; + } + } + + /// + /// Gets the number of test cases that failed + /// when running the test and all its children. + /// + public abstract int FailCount { get; } + + /// + /// Gets the number of test cases that passed + /// when running the test and all its children. + /// + public abstract int PassCount { get; } + + /// + /// Gets the number of test cases that were skipped + /// when running the test and all its children. + /// + public abstract int SkipCount { get; } + + /// + /// Gets the number of test cases that were inconclusive + /// when running the test and all its children. + /// + public abstract int InconclusiveCount { get; } + + /// + /// Indicates whether this result has any child results. + /// + public abstract bool HasChildren { get; } + + /// + /// Gets the collection of child results. + /// + public abstract IEnumerable Children { get; } + + /// + /// Gets a TextWriter, which will write output to be included in the result. + /// + public TextWriter OutWriter { get; private set; } + + /// + /// Gets any text output written to this result. + /// + public string Output + { + get { return _output.ToString(); } + } + + #endregion + + #region IXmlNodeBuilder Members + + /// + /// Returns the Xml representation of the result. + /// + /// If true, descendant results are included + /// An XmlNode representing the result + public TNode ToXml(bool recursive) + { + return AddToXml(new TNode("dummy"), recursive); + } + + /// + /// Adds the XML representation of the result as a child of the + /// supplied parent node.. + /// + /// The parent node. + /// If true, descendant results are included + /// + public virtual TNode AddToXml(TNode parentNode, bool recursive) + { + // A result node looks like a test node with extra info added + TNode thisNode = Test.AddToXml(parentNode, false); + + thisNode.AddAttribute("result", ResultState.Status.ToString()); + if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString()) + thisNode.AddAttribute("label", ResultState.Label); + if (ResultState.Site != FailureSite.Test) + thisNode.AddAttribute("site", ResultState.Site.ToString()); + + thisNode.AddAttribute("start-time", StartTime.ToString("u")); + thisNode.AddAttribute("end-time", EndTime.ToString("u")); + thisNode.AddAttribute("duration", Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo)); + + if (Test is TestSuite) + { + thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString()); + thisNode.AddAttribute("passed", PassCount.ToString()); + thisNode.AddAttribute("failed", FailCount.ToString()); + thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString()); + thisNode.AddAttribute("skipped", SkipCount.ToString()); + } + + thisNode.AddAttribute("asserts", AssertCount.ToString()); + + switch (ResultState.Status) + { + case TestStatus.Failed: + AddFailureElement(thisNode); + break; + case TestStatus.Skipped: + case TestStatus.Passed: + case TestStatus.Inconclusive: + if (Message != null) + AddReasonElement(thisNode); + break; + } + + if (Output.Length > 0) + AddOutputElement(thisNode); + + + if (recursive && HasChildren) + foreach (TestResult child in Children) + child.AddToXml(thisNode, recursive); + + return thisNode; + } + + #endregion + + #region Other Public Methods + + /// + /// Set the result of the test + /// + /// The ResultState to use in the result + public void SetResult(ResultState resultState) + { + SetResult(resultState, null, null); + } + + /// + /// Set the result of the test + /// + /// The ResultState to use in the result + /// A message associated with the result state + public void SetResult(ResultState resultState, string message) + { + SetResult(resultState, message, null); + } + + /// + /// Set the result of the test + /// + /// The ResultState to use in the result + /// A message associated with the result state + /// Stack trace giving the location of the command + public void SetResult(ResultState resultState, string message, string stackTrace) + { +#if PARALLEL + RwLock.EnterWriteLock(); +#endif + try + { + ResultState = resultState; + Message = message; + StackTrace = stackTrace; + } + finally + { +#if PARALLEL + RwLock.ExitWriteLock(); +#endif + } + + // Set pseudo-counts for a test case + //if (IsTestCase(test)) + //{ + // passCount = 0; + // failCount = 0; + // skipCount = 0; + // inconclusiveCount = 0; + + // switch (ResultState.Status) + // { + // case TestStatus.Passed: + // passCount++; + // break; + // case TestStatus.Failed: + // failCount++; + // break; + // case TestStatus.Skipped: + // skipCount++; + // break; + // default: + // case TestStatus.Inconclusive: + // inconclusiveCount++; + // break; + // } + //} + } + + /// + /// Set the test result based on the type of exception thrown + /// + /// The exception that was thrown + public void RecordException(Exception ex) + { + if (ex is NUnitException) + ex = ex.InnerException; + + if (ex is ResultStateException) + SetResult(((ResultStateException)ex).ResultState, + ex.Message, + StackFilter.Filter(ex.StackTrace)); +#if !PORTABLE + else if (ex is System.Threading.ThreadAbortException) + SetResult(ResultState.Cancelled, + "Test cancelled by user", + ex.StackTrace); +#endif + else + SetResult(ResultState.Error, + ExceptionHelper.BuildMessage(ex), + ExceptionHelper.BuildStackTrace(ex)); + } + + /// + /// Set the test result based on the type of exception thrown + /// + /// The exception that was thrown + /// THe FailureSite to use in the result + public void RecordException(Exception ex, FailureSite site) + { + if (ex is NUnitException) + ex = ex.InnerException; + + if (ex is ResultStateException) + SetResult(((ResultStateException)ex).ResultState.WithSite(site), + ex.Message, + StackFilter.Filter(ex.StackTrace)); +#if !PORTABLE + else if (ex is System.Threading.ThreadAbortException) + SetResult(ResultState.Cancelled.WithSite(site), + "Test cancelled by user", + ex.StackTrace); +#endif + else + SetResult(ResultState.Error.WithSite(site), + ExceptionHelper.BuildMessage(ex), + ExceptionHelper.BuildStackTrace(ex)); + } + + /// + /// RecordTearDownException appends the message and stacktrace + /// from an exception arising during teardown of the test + /// to any previously recorded information, so that any + /// earlier failure information is not lost. Note that + /// calling Assert.Ignore, Assert.Inconclusive, etc. during + /// teardown is treated as an error. If the current result + /// represents a suite, it may show a teardown error even + /// though all contained tests passed. + /// + /// The Exception to be recorded + public void RecordTearDownException(Exception ex) + { + if (ex is NUnitException) + ex = ex.InnerException; + + ResultState resultState = ResultState == ResultState.Cancelled + ? ResultState.Cancelled + : ResultState.Error; + if (Test.IsSuite) + resultState = resultState.WithSite(FailureSite.TearDown); + + string message = "TearDown : " + ExceptionHelper.BuildMessage(ex); + if (Message != null) + message = Message + NUnit.Env.NewLine + message; + + string stackTrace = "--TearDown" + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex); + if (StackTrace != null) + stackTrace = StackTrace + NUnit.Env.NewLine + stackTrace; + + SetResult(resultState, message, stackTrace); + } + + #endregion + + #region Helper Methods + + /// + /// Adds a reason element to a node and returns it. + /// + /// The target node. + /// The new reason element. + private TNode AddReasonElement(TNode targetNode) + { + TNode reasonNode = targetNode.AddElement("reason"); + return reasonNode.AddElementWithCDATA("message", Message); + } + + /// + /// Adds a failure element to a node and returns it. + /// + /// The target node. + /// The new failure element. + private TNode AddFailureElement(TNode targetNode) + { + TNode failureNode = targetNode.AddElement("failure"); + + if (Message != null) + failureNode.AddElementWithCDATA("message", Message); + + if (StackTrace != null) + failureNode.AddElementWithCDATA("stack-trace", StackTrace); + + return failureNode; + } + + private TNode AddOutputElement(TNode targetNode) + { + return targetNode.AddElementWithCDATA("output", Output); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs new file mode 100644 index 000000000..6308c10cf --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs @@ -0,0 +1,263 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +#if PARALLEL +using System.Collections.Concurrent; +#endif +using NUnit.Framework.Interfaces; +using System.Threading; +#if NETCF || NET_2_0 +using NUnit.Compatibility; +#endif + +namespace NUnit.Framework.Internal +{ + /// + /// Represents the result of running a test suite + /// + public class TestSuiteResult : TestResult + { + private int _passCount = 0; + private int _failCount = 0; + private int _skipCount = 0; + private int _inconclusiveCount = 0; +#if PARALLEL + private ConcurrentQueue _children; +#else + private List _children; +#endif + + /// + /// Construct a TestSuiteResult base on a TestSuite + /// + /// The TestSuite to which the result applies + public TestSuiteResult(TestSuite suite) : base(suite) + { +#if PARALLEL + _children = new ConcurrentQueue(); +#else + _children = new List(); +#endif + } + +#region Overrides + + /// + /// Gets the number of test cases that failed + /// when running the test and all its children. + /// + public override int FailCount + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _failCount; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + } + } + + /// + /// Gets the number of test cases that passed + /// when running the test and all its children. + /// + public override int PassCount + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _passCount; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + } + } + + /// + /// Gets the number of test cases that were skipped + /// when running the test and all its children. + /// + public override int SkipCount + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _skipCount; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + } + } + + /// + /// Gets the number of test cases that were inconclusive + /// when running the test and all its children. + /// + public override int InconclusiveCount + { + get + { +#if PARALLEL + RwLock.EnterReadLock(); +#endif + try + { + return _inconclusiveCount; + } + finally + { +#if PARALLEL + RwLock.ExitReadLock(); +#endif + } + } + } + + /// + /// Indicates whether this result has any child results. + /// + public override bool HasChildren + { + get + { +#if PARALLEL + return !_children.IsEmpty; +#else + return _children.Count != 0; +#endif + } + } + + /// + /// Gets the collection of child results. + /// + public override IEnumerable Children + { + get { return _children; } + } + + #endregion + + #region AddResult Method + + /// + /// Adds a child result to this result, setting this result's + /// ResultState to Failure if the child result failed. + /// + /// The result to be added + public virtual void AddResult(ITestResult result) + { +#if PARALLEL + var childrenAsConcurrentQueue = Children as ConcurrentQueue; + if (childrenAsConcurrentQueue != null) + childrenAsConcurrentQueue.Enqueue(result); + else +#endif + { + var childrenAsIList = Children as IList; + if (childrenAsIList != null) + childrenAsIList.Add(result); + else + throw new NotSupportedException("cannot add results to Children"); + + } + +#if PARALLEL + RwLock.EnterWriteLock(); +#endif + try + { + // If this result is marked cancelled, don't change it + if (ResultState != ResultState.Cancelled) + { + switch (result.ResultState.Status) + { + case TestStatus.Passed: + + if (ResultState.Status == TestStatus.Inconclusive) + SetResult(ResultState.Success); + + break; + + case TestStatus.Failed: + + + if (ResultState.Status != TestStatus.Failed) + SetResult(ResultState.ChildFailure, CHILD_ERRORS_MESSAGE); + + break; + + case TestStatus.Skipped: + + if (result.ResultState.Label == "Ignored") + if (ResultState.Status == TestStatus.Inconclusive || ResultState.Status == TestStatus.Passed) + SetResult(ResultState.Ignored, CHILD_IGNORE_MESSAGE); + + break; + } + } + + InternalAssertCount += result.AssertCount; + _passCount += result.PassCount; + _failCount += result.FailCount; + _skipCount += result.SkipCount; + _inconclusiveCount += result.InconclusiveCount; + } + finally + { +#if PARALLEL + RwLock.ExitWriteLock(); +#endif + } + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/RuntimeFramework.cs b/test/NUnitLite/NUnitFramework/framework/Internal/RuntimeFramework.cs new file mode 100644 index 000000000..f81935ea8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/RuntimeFramework.cs @@ -0,0 +1,424 @@ +// *********************************************************************** +// Copyright (c) 2007-2016 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if !PORTABLE +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using Microsoft.Win32; + +namespace NUnit.Framework.Internal +{ + /// + /// Enumeration identifying a common language + /// runtime implementation. + /// + public enum RuntimeType + { + /// Any supported runtime framework + Any, + /// Microsoft .NET Framework + Net, + /// Microsoft .NET Compact Framework + NetCF, + /// Microsoft Shared Source CLI + SSCLI, + /// Mono + Mono, + /// Silverlight + Silverlight, + /// MonoTouch + MonoTouch + } + + /// + /// RuntimeFramework represents a particular version + /// of a common language runtime implementation. + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public sealed class RuntimeFramework + { + // NOTE: This version of RuntimeFramework is for use + // within the NUnit framework assembly. It is simpler + // than the version in the test engine because it does + // not need to know what frameworks are available, + // only what framework is currently running. +#region Static and Instance Fields + + /// + /// DefaultVersion is an empty Version, used to indicate that + /// NUnit should select the CLR version to use for the test. + /// + public static readonly Version DefaultVersion = new Version(0,0); + + private static readonly Lazy currentFramework = new Lazy(() => + { +#if SILVERLIGHT + var currentFramework = new RuntimeFramework( + RuntimeType.Silverlight, + new Version(Environment.Version.Major, Environment.Version.Minor)); +#else + Type monoRuntimeType = Type.GetType("Mono.Runtime", false); + Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch"); + bool isMonoTouch = monoTouchType != null; + bool isMono = monoRuntimeType != null; + + RuntimeType runtime = isMonoTouch + ? RuntimeType.MonoTouch + : isMono + ? RuntimeType.Mono + : Environment.OSVersion.Platform == PlatformID.WinCE + ? RuntimeType.NetCF + : RuntimeType.Net; + + int major = Environment.Version.Major; + int minor = Environment.Version.Minor; + + if (isMono) + { + switch (major) + { + case 1: + minor = 0; + break; + case 2: + major = 3; + minor = 5; + break; + } + } + else /* It's windows */ + if (major == 2) + { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework")) + { + if (key != null) + { + string installRoot = key.GetValue("InstallRoot") as string; + if (installRoot != null) + { + if (Directory.Exists(Path.Combine(installRoot, "v3.5"))) + { + major = 3; + minor = 5; + } + else if (Directory.Exists(Path.Combine(installRoot, "v3.0"))) + { + major = 3; + minor = 0; + } + } + } + } + } + else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null) + { + minor = 5; + } + + var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) ) + { + ClrVersion = Environment.Version + }; + + if (isMono) + { + MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod( + "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding); + if (getDisplayNameMethod != null) + currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]); + } +#endif + return currentFramework; + }); + +#endregion + +#region Constructor + + /// + /// Construct from a runtime type and version. If the version has + /// two parts, it is taken as a framework version. If it has three + /// or more, it is taken as a CLR version. In either case, the other + /// version is deduced based on the runtime type and provided version. + /// + /// The runtime type of the framework + /// The version of the framework + public RuntimeFramework( RuntimeType runtime, Version version) + { + Runtime = runtime; + + if (version.Build < 0) + InitFromFrameworkVersion(version); + else + InitFromClrVersion(version); + + DisplayName = GetDefaultDisplayName(runtime, version); + } + + private void InitFromFrameworkVersion(Version version) + { + FrameworkVersion = ClrVersion = version; + + if (version.Major > 0) // 0 means any version + switch (Runtime) + { + case RuntimeType.Net: + case RuntimeType.Mono: + case RuntimeType.Any: + switch (version.Major) + { + case 1: + switch (version.Minor) + { + case 0: + ClrVersion = Runtime == RuntimeType.Mono + ? new Version(1, 1, 4322) + : new Version(1, 0, 3705); + break; + case 1: + if (Runtime == RuntimeType.Mono) + FrameworkVersion = new Version(1, 0); + ClrVersion = new Version(1, 1, 4322); + break; + default: + ThrowInvalidFrameworkVersion(version); + break; + } + break; + case 2: + case 3: + ClrVersion = new Version(2, 0, 50727); + break; + case 4: + ClrVersion = new Version(4, 0, 30319); + break; + default: + ThrowInvalidFrameworkVersion(version); + break; + } + break; + + case RuntimeType.Silverlight: + ClrVersion = version.Major >= 4 + ? new Version(4, 0, 60310) + : new Version(2, 0, 50727); + break; + + case RuntimeType.NetCF: + switch (version.Major) + { + case 3: + switch (version.Minor) + { + case 5: + ClrVersion = new Version(3, 5, 7283); + break; + } + break; + } + break; + } + } + + private static void ThrowInvalidFrameworkVersion(Version version) + { + throw new ArgumentException("Unknown framework version " + version, "version"); + } + + private void InitFromClrVersion(Version version) + { + FrameworkVersion = new Version(version.Major, version.Minor); + ClrVersion = version; + if (Runtime == RuntimeType.Mono && version.Major == 1) + FrameworkVersion = new Version(1, 0); + } + +#endregion + +#region Properties + /// + /// Static method to return a RuntimeFramework object + /// for the framework that is currently in use. + /// + public static RuntimeFramework CurrentFramework + { + get + { + return currentFramework.Value; + } + } + + /// + /// The type of this runtime framework + /// + public RuntimeType Runtime { get; private set; } + + /// + /// The framework version for this runtime framework + /// + public Version FrameworkVersion { get; private set; } + + /// + /// The CLR version for this runtime framework + /// + public Version ClrVersion { get; private set; } + + /// + /// Return true if any CLR version may be used in + /// matching this RuntimeFramework object. + /// + public bool AllowAnyVersion + { + get { return ClrVersion == DefaultVersion; } + } + + /// + /// Returns the Display name for this framework + /// + public string DisplayName { get; private set; } + +#endregion + +#region Public Methods + + /// + /// Parses a string representing a RuntimeFramework. + /// The string may be just a RuntimeType name or just + /// a Version or a hyphenated RuntimeType-Version or + /// a Version prefixed by 'versionString'. + /// + /// + /// + public static RuntimeFramework Parse(string s) + { + RuntimeType runtime = RuntimeType.Any; + Version version = DefaultVersion; + + string[] parts = s.Split('-'); + if (parts.Length == 2) + { + runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), parts[0], true); + string vstring = parts[1]; + if (vstring != "") + version = new Version(vstring); + } + else if (char.ToLower(s[0]) == 'v') + { + version = new Version(s.Substring(1)); + } + else if (IsRuntimeTypeName(s)) + { + runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true); + } + else + { + version = new Version(s); + } + + return new RuntimeFramework(runtime, version); + } + + /// + /// Overridden to return the short name of the framework + /// + /// + public override string ToString() + { + if (AllowAnyVersion) + { + return Runtime.ToString().ToLower(); + } + else + { + string vstring = FrameworkVersion.ToString(); + if (Runtime == RuntimeType.Any) + return "v" + vstring; + else + return Runtime.ToString().ToLower() + "-" + vstring; + } + } + + /// + /// Returns true if the current framework matches the + /// one supplied as an argument. Two frameworks match + /// if their runtime types are the same or either one + /// is RuntimeType.Any and all specified version components + /// are equal. Negative (i.e. unspecified) version + /// components are ignored. + /// + /// The RuntimeFramework to be matched. + /// True on match, otherwise false + public bool Supports(RuntimeFramework target) + { + if (Runtime != RuntimeType.Any + && target.Runtime != RuntimeType.Any + && Runtime != target.Runtime) + return false; + + if (AllowAnyVersion || target.AllowAnyVersion) + return true; + + if (!VersionsMatch(ClrVersion, target.ClrVersion)) + return false; + + return Runtime == RuntimeType.Silverlight + ? FrameworkVersion.Major == target.FrameworkVersion.Major && FrameworkVersion.Minor == target.FrameworkVersion.Minor + : FrameworkVersion.Major >= target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor; + } + +#endregion + +#region Helper Methods + + private static bool IsRuntimeTypeName(string name) + { + return TypeHelper.GetEnumNames( typeof(RuntimeType)).Any( item => item.ToLower() == name.ToLower() ); + } + + private static string GetDefaultDisplayName(RuntimeType runtime, Version version) + { + if (version == DefaultVersion) + return runtime.ToString(); + else if (runtime == RuntimeType.Any) + return "v" + version; + else + return runtime + " " + version; + } + + private static bool VersionsMatch(Version v1, Version v2) + { + return v1.Major == v2.Major && + v1.Minor == v2.Minor && + (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) && + (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision); + } + +#endregion + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/StackFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/StackFilter.cs new file mode 100644 index 000000000..c94aeaf13 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/StackFilter.cs @@ -0,0 +1,78 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.IO; +using System.Text.RegularExpressions; + +namespace NUnit.Framework.Internal +{ + /// + /// StackFilter class is used to remove internal NUnit + /// entries from a stack trace so that the resulting + /// trace provides better information about the test. + /// + public static class StackFilter + { + private static readonly Regex assertOrAssumeRegex = new Regex( + @" NUnit\.Framework\.Ass(ert|ume)\."); + + /// + /// Filters a raw stack trace and returns the result. + /// + /// The original stack trace + /// A filtered stack trace + public static string Filter(string rawTrace) + { + if (rawTrace == null) return null; + + StringReader sr = new StringReader(rawTrace); + StringWriter sw = new StringWriter(); + + try + { + string line; + // Skip past any Assert or Assume lines + while ((line = sr.ReadLine()) != null && assertOrAssumeRegex.IsMatch(line)) + /*Skip*/ + ; + + // Copy lines down to the line that invoked the failing method. + // This is actually only needed for the compact framework, but + // we do it on all platforms for simplicity. Desktop platforms + // won't have any System.Reflection lines. + while (line != null && line.IndexOf(" System.Reflection.") < 0) + { + sw.WriteLine(line.Trim()); + line = sr.ReadLine(); + } + } + catch (Exception) + { + return rawTrace; + } + + return sw.ToString(); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/StringUtil.cs b/test/NUnitLite/NUnitFramework/framework/Internal/StringUtil.cs new file mode 100644 index 000000000..8e65638a3 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/StringUtil.cs @@ -0,0 +1,64 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Globalization; + +namespace NUnit.Framework.Internal +{ + /// + /// Provides methods to support legacy string comparison methods. + /// + public class StringUtil + { + /// + /// Compares two strings for equality, ignoring case if requested. + /// + /// The first string. + /// The second string.. + /// if set to true, the case of the letters in the strings is ignored. + /// Zero if the strings are equivalent, a negative number if strA is sorted first, a positive number if + /// strB is sorted first + public static int Compare(string strA, string strB, bool ignoreCase) + { +#if NETCF + return string.Compare(strA, strB, ignoreCase); +#else + var comparison = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; + return string.Compare(strA, strB, comparison); +#endif + } + + /// + /// Compares two strings for equality, ignoring case if requested. + /// + /// The first string. + /// The second string.. + /// if set to true, the case of the letters in the strings is ignored. + /// True if the strings are equivalent, false if not. + public static bool StringsEqual(string strA, string strB, bool ignoreCase) + { + return Compare(strA, strB, ignoreCase) == 0; + } + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestCaseParameters.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestCaseParameters.cs new file mode 100644 index 000000000..f03b21ec2 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestCaseParameters.cs @@ -0,0 +1,99 @@ +// *********************************************************************** +// Copyright (c) 2008-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// The TestCaseParameters class encapsulates method arguments and + /// other selected parameters needed for constructing + /// a parameterized test case. + /// + public class TestCaseParameters : TestParameters, ITestCaseData, IApplyToTest + { + #region Instance Fields + + /// + /// The expected result to be returned + /// + private object _expectedResult; + + #endregion + + #region Constructors + + /// + /// Default Constructor creates an empty parameter set + /// + public TestCaseParameters() { } + + /// + /// Construct a non-runnable ParameterSet, specifying + /// the provider exception that made it invalid. + /// + public TestCaseParameters(Exception exception) : base(exception) { } + + /// + /// Construct a parameter set with a list of arguments + /// + /// + public TestCaseParameters(object[] args) : base(args) { } + + /// + /// Construct a ParameterSet from an object implementing ITestCaseData + /// + /// + public TestCaseParameters(ITestCaseData data) : base(data) + { + if (data.HasExpectedResult) + ExpectedResult = data.ExpectedResult; + } + + #endregion + + #region ITestCaseData Members + + /// + /// The expected result of the test, which + /// must match the method return type. + /// + public object ExpectedResult + { + get { return _expectedResult; } + set + { + _expectedResult = value; + HasExpectedResult = true; + } + } + + /// + /// Gets a value indicating whether an expected result was specified. + /// + public bool HasExpectedResult { get; set; } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestExecutionContext.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestExecutionContext.cs new file mode 100644 index 000000000..aa3d9d476 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestExecutionContext.cs @@ -0,0 +1,576 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Diagnostics; +using System.IO; +using System.Threading; +using NUnit.Framework.Constraints; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Execution; + +#if !SILVERLIGHT && !NETCF && !PORTABLE +using System.Runtime.Remoting.Messaging; +using System.Security; +using System.Security.Principal; +using NUnit.Compatibility; +#endif + +namespace NUnit.Framework.Internal +{ + /// + /// Helper class used to save and restore certain static or + /// singleton settings in the environment that affect tests + /// or which might be changed by the user tests. + /// + /// An internal class is used to hold settings and a stack + /// of these objects is pushed and popped as Save and Restore + /// are called. + /// + public class TestExecutionContext +#if !SILVERLIGHT && !NETCF && !PORTABLE + : LongLivedMarshalByRefObject, ILogicalThreadAffinative +#endif + { + // NOTE: Be very careful when modifying this class. It uses + // conditional compilation extensively and you must give + // thought to whether any new features will be supported + // on each platform. In particular, instance fields, + // properties, initialization and restoration must all + // use the same conditions for each feature. + + #region Instance Fields + + /// + /// Link to a prior saved context + /// + private TestExecutionContext _priorContext; + + /// + /// Indicates that a stop has been requested + /// + private TestExecutionStatus _executionStatus; + + /// + /// The event listener currently receiving notifications + /// + private ITestListener _listener = TestListener.NULL; + + /// + /// The number of assertions for the current test + /// + private int _assertCount; + + private Randomizer _randomGenerator; + + /// + /// The current culture + /// + private CultureInfo _currentCulture; + + /// + /// The current UI culture + /// + private CultureInfo _currentUICulture; + + /// + /// The current test result + /// + private TestResult _currentResult; + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// The current Principal. + /// + private IPrincipal _currentPrincipal; +#endif + + #endregion + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + public TestExecutionContext() + { + _priorContext = null; + TestCaseTimeout = 0; + UpstreamActions = new List(); + + _currentCulture = CultureInfo.CurrentCulture; + _currentUICulture = CultureInfo.CurrentUICulture; + +#if !NETCF && !SILVERLIGHT && !PORTABLE + _currentPrincipal = Thread.CurrentPrincipal; +#endif + + CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val); + IsSingleThreaded = false; + } + + /// + /// Initializes a new instance of the class. + /// + /// An existing instance of TestExecutionContext. + public TestExecutionContext(TestExecutionContext other) + { + _priorContext = other; + + CurrentTest = other.CurrentTest; + CurrentResult = other.CurrentResult; + TestObject = other.TestObject; + WorkDirectory = other.WorkDirectory; + _listener = other._listener; + StopOnError = other.StopOnError; + TestCaseTimeout = other.TestCaseTimeout; + UpstreamActions = new List(other.UpstreamActions); + + _currentCulture = other.CurrentCulture; + _currentUICulture = other.CurrentUICulture; + +#if !NETCF && !SILVERLIGHT && !PORTABLE + _currentPrincipal = other.CurrentPrincipal; +#endif + + CurrentValueFormatter = other.CurrentValueFormatter; + + Dispatcher = other.Dispatcher; + ParallelScope = other.ParallelScope; + IsSingleThreaded = other.IsSingleThreaded; + } + + #endregion + + #region Static Singleton Instance + + // NOTE: We use different implementations for various platforms + + // If a user creates a thread then the current context + // will be null. This also happens when the compiler + // automatically creates threads for async methods. + // We create a new context, which is automatically + // populated with values taken from the current thread. + +#if SILVERLIGHT || PORTABLE + // In the Silverlight and portable builds, we use a ThreadStatic + // field to hold the current TestExecutionContext. + + [ThreadStatic] + private static TestExecutionContext _currentContext; + + /// + /// Gets and sets the current context. + /// + public static TestExecutionContext CurrentContext + { + get + { + if (_currentContext == null) + _currentContext = new TestExecutionContext(); + + return _currentContext; + } + private set + { + _currentContext = value; + } + } +#elif NETCF + // In the compact framework build, we use a LocalStoreDataSlot + + private static LocalDataStoreSlot contextSlot = Thread.AllocateDataSlot(); + + /// + /// Gets and sets the current context. + /// + public static TestExecutionContext CurrentContext + { + get + { + var current = GetTestExecutionContext(); + if (current == null) + { + current = new TestExecutionContext(); + Thread.SetData(contextSlot, current); + } + + return current; + } + private set + { + Thread.SetData(contextSlot, value); + } + } + + /// + /// Get the current context or return null if none is found. + /// + public static TestExecutionContext GetTestExecutionContext() + { + return (TestExecutionContext)Thread.GetData(contextSlot); + } +#else + // In all other builds, we use the CallContext + + private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext"; + + /// + /// Gets and sets the current context. + /// + public static TestExecutionContext CurrentContext + { + // This getter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class. + // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' + // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. + [SecuritySafeCritical] + get + { + var context = GetTestExecutionContext(); + if (context == null) // This can happen on Mono + { + context = new TestExecutionContext(); + CallContext.SetData(CONTEXT_KEY, context); + } + + return context; + } + // This setter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class. + // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' + // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. + [SecuritySafeCritical] + private set + { + if (value == null) + CallContext.FreeNamedDataSlot(CONTEXT_KEY); + else + CallContext.SetData(CONTEXT_KEY, value); + } + } + + /// + /// Get the current context or return null if none is found. + /// + /// + // This setter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class. + // Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute' + // rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers. + [SecuritySafeCritical] + public static TestExecutionContext GetTestExecutionContext() + { + return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext; + } +#endif + + /// + /// Clear the current context. This is provided to + /// prevent "leakage" of the CallContext containing + /// the current context back to any runners. + /// + public static void ClearCurrentContext() + { + CurrentContext = null; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the current test + /// + public Test CurrentTest { get; set; } + + /// + /// The time the current test started execution + /// + public DateTime StartTime { get; set; } + + /// + /// The time the current test started in Ticks + /// + public long StartTicks { get; set; } + + /// + /// Gets or sets the current test result + /// + public TestResult CurrentResult + { + get { return _currentResult; } + set + { + _currentResult = value; + if (value != null) + OutWriter = value.OutWriter; + } + } + + /// + /// Gets a TextWriter that will send output to the current test result. + /// + public TextWriter OutWriter { get; private set; } + + /// + /// The current test object - that is the user fixture + /// object on which tests are being executed. + /// + public object TestObject { get; set; } + + /// + /// Get or set the working directory + /// + public string WorkDirectory { get; set; } + + /// + /// Get or set indicator that run should stop on the first error + /// + public bool StopOnError { get; set; } + + /// + /// Gets an enum indicating whether a stop has been requested. + /// + public TestExecutionStatus ExecutionStatus + { + get + { + // ExecutionStatus may have been set to StopRequested or AbortRequested + // in a prior context. If so, reflect the same setting in this context. + if (_executionStatus == TestExecutionStatus.Running && _priorContext != null) + _executionStatus = _priorContext.ExecutionStatus; + + return _executionStatus; + } + set + { + _executionStatus = value; + + // Push the same setting up to all prior contexts + if (_priorContext != null) + _priorContext.ExecutionStatus = value; + } + } + + /// + /// The current test event listener + /// + internal ITestListener Listener + { + get { return _listener; } + set { _listener = value; } + } + + /// + /// The current WorkItemDispatcher. Made public for + /// use by nunitlite.tests + /// + public IWorkItemDispatcher Dispatcher { get; set; } + + /// + /// The ParallelScope to be used by tests running in this context. + /// For builds with out the parallel feature, it has no effect. + /// + public ParallelScope ParallelScope { get; set; } + + /// + /// The unique name of the worker that spawned the context. + /// For builds with out the parallel feature, it is null. + /// + public string WorkerId {get; internal set;} + + /// + /// Gets the RandomGenerator specific to this Test + /// + public Randomizer RandomGenerator + { + get + { + if (_randomGenerator == null) + _randomGenerator = new Randomizer(CurrentTest.Seed); + return _randomGenerator; + } + } + + /// + /// Gets the assert count. + /// + /// The assert count. + internal int AssertCount + { + get { return _assertCount; } + } + + /// + /// Gets or sets the test case timeout value + /// + public int TestCaseTimeout { get; set; } + + /// + /// Gets a list of ITestActions set by upstream tests + /// + public List UpstreamActions { get; private set; } + + // TODO: Put in checks on all of these settings + // with side effects so we only change them + // if the value is different + + /// + /// Saves or restores the CurrentCulture + /// + public CultureInfo CurrentCulture + { + get { return _currentCulture; } + set + { + _currentCulture = value; +#if !NETCF && !PORTABLE + Thread.CurrentThread.CurrentCulture = _currentCulture; +#endif + } + } + + /// + /// Saves or restores the CurrentUICulture + /// + public CultureInfo CurrentUICulture + { + get { return _currentUICulture; } + set + { + _currentUICulture = value; +#if !NETCF && !PORTABLE + Thread.CurrentThread.CurrentUICulture = _currentUICulture; +#endif + } + } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// Gets or sets the current for the Thread. + /// + public IPrincipal CurrentPrincipal + { + get { return _currentPrincipal; } + set + { + _currentPrincipal = value; + Thread.CurrentPrincipal = _currentPrincipal; + } + } +#endif + + /// + /// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter + /// + public ValueFormatter CurrentValueFormatter { get; private set; } + + /// + /// If true, all tests must run on the same thread. No new thread may be spawned. + /// + public bool IsSingleThreaded { get; set; } + + #endregion + + #region Instance Methods + + /// + /// Record any changes in the environment made by + /// the test code in the execution context so it + /// will be passed on to lower level tests. + /// + public void UpdateContextFromEnvironment() + { + _currentCulture = CultureInfo.CurrentCulture; + _currentUICulture = CultureInfo.CurrentUICulture; + +#if !NETCF && !SILVERLIGHT && !PORTABLE + _currentPrincipal = Thread.CurrentPrincipal; +#endif + } + + /// + /// Set up the execution environment to match a context. + /// Note that we may be running on the same thread where the + /// context was initially created or on a different thread. + /// + public void EstablishExecutionEnvironment() + { +#if !NETCF && !PORTABLE + Thread.CurrentThread.CurrentCulture = _currentCulture; + Thread.CurrentThread.CurrentUICulture = _currentUICulture; +#endif + +#if !NETCF && !SILVERLIGHT && !PORTABLE + Thread.CurrentPrincipal = _currentPrincipal; +#endif + + CurrentContext = this; + } + + /// + /// Increments the assert count by one. + /// + public void IncrementAssertCount() + { + Interlocked.Increment(ref _assertCount); + } + + /// + /// Increments the assert count by a specified amount. + /// + public void IncrementAssertCount(int count) + { + // TODO: Temporary implementation + while (count-- > 0) + Interlocked.Increment(ref _assertCount); + } + + /// + /// Adds a new ValueFormatterFactory to the chain of formatters + /// + /// The new factory + public void AddFormatter(ValueFormatterFactory formatterFactory) + { + CurrentValueFormatter = formatterFactory(CurrentValueFormatter); + } + + #endregion + + #region InitializeLifetimeService + +#if !SILVERLIGHT && !NETCF && !PORTABLE + /// + /// Obtain lifetime service object + /// + /// + [SecurityCritical] // Override of security critical method must be security critical itself + public override object InitializeLifetimeService() + { + return null; + } +#endif + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestExecutionStatus.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestExecutionStatus.cs new file mode 100644 index 000000000..bf2289436 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestExecutionStatus.cs @@ -0,0 +1,47 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Internal +{ + /// + /// Enumeration indicating whether the tests are + /// running normally or being cancelled. + /// + public enum TestExecutionStatus + { + /// + /// Running normally with no stop requested + /// + Running, + + /// + /// A graceful stop has been requested + /// + StopRequested, + + /// + /// A forced stop has been requested + /// + AbortRequested + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestFilter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestFilter.cs new file mode 100644 index 000000000..a6138d3ca --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestFilter.cs @@ -0,0 +1,251 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Xml; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Filters; + +namespace NUnit.Framework.Internal +{ + /// + /// Interface to be implemented by filters applied to tests. + /// The filter applies when running the test, after it has been + /// loaded, since this is the only time an ITest exists. + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + public abstract class TestFilter : ITestFilter + { + /// + /// Unique Empty filter. + /// + public readonly static TestFilter Empty = new EmptyFilter(); + + /// + /// Indicates whether this is the EmptyFilter + /// + public bool IsEmpty + { + get { return this is TestFilter.EmptyFilter; } + } + + /// + /// Indicates whether this is a top-level filter, + /// not contained in any other filter. + /// + public bool TopLevel { get; set; } + + /// + /// Determine if a particular test passes the filter criteria. The default + /// implementation checks the test itself, its parents and any descendants. + /// + /// Derived classes may override this method or any of the Match methods + /// to change the behavior of the filter. + /// + /// The test to which the filter is applied + /// True if the test passes the filter, otherwise false + public virtual bool Pass(ITest test) + { + return Match(test) || MatchParent(test) || MatchDescendant(test); + } + + /// + /// Determine if a test matches the filter expicitly. That is, it must + /// be a direct match of the test itself or one of it's children. + /// + /// The test to which the filter is applied + /// True if the test matches the filter explicityly, otherwise false + public virtual bool IsExplicitMatch(ITest test) + { + return Match(test) || MatchDescendant(test); + } + + /// + /// Determine whether the test itself matches the filter criteria, without + /// examining either parents or descendants. This is overridden by each + /// different type of filter to perform the necessary tests. + /// + /// The test to which the filter is applied + /// True if the filter matches the any parent of the test + public abstract bool Match(ITest test); + + /// + /// Determine whether any ancestor of the test matches the filter criteria + /// + /// The test to which the filter is applied + /// True if the filter matches the an ancestor of the test + public bool MatchParent(ITest test) + { + return test.Parent != null && (Match(test.Parent) || MatchParent(test.Parent)); + } + + /// + /// Determine whether any descendant of the test matches the filter criteria. + /// + /// The test to be matched + /// True if at least one descendant matches the filter criteria + protected virtual bool MatchDescendant(ITest test) + { + if (test.Tests == null) + return false; + + foreach (ITest child in test.Tests) + { + if (Match(child) || MatchDescendant(child)) + return true; + } + + return false; + } + + /// + /// Create a TestFilter instance from an xml representation. + /// + public static TestFilter FromXml(string xmlText) + { + TNode topNode = TNode.FromXml(xmlText); + + if (topNode.Name != "filter") + throw new Exception("Expected filter element at top level"); + + int count = topNode.ChildNodes.Count; + + TestFilter filter = count == 0 + ? TestFilter.Empty + : count == 1 + ? FromXml(topNode.FirstChild) + : FromXml(topNode); + + filter.TopLevel = true; + + return filter; + } + + /// + /// Create a TestFilter from it's TNode representation + /// + public static TestFilter FromXml(TNode node) + { + bool isRegex = node.Attributes["re"] == "1"; + + switch (node.Name) + { + case "filter": + case "and": + var andFilter = new AndFilter(); + foreach (var childNode in node.ChildNodes) + andFilter.Add(FromXml(childNode)); + return andFilter; + + case "or": + var orFilter = new OrFilter(); + foreach (var childNode in node.ChildNodes) + orFilter.Add(FromXml(childNode)); + return orFilter; + + case "not": + return new NotFilter(FromXml(node.FirstChild)); + + case "id": + return new IdFilter(node.Value); + + case "test": + return new FullNameFilter(node.Value) { IsRegex = isRegex }; + + case "name": + return new TestNameFilter(node.Value) { IsRegex = isRegex }; + + case "method": + return new MethodNameFilter(node.Value) { IsRegex = isRegex }; + + case "class": + return new ClassNameFilter(node.Value) { IsRegex = isRegex }; + + case "cat": + return new CategoryFilter(node.Value) { IsRegex = isRegex }; + + case "prop": + string name = node.Attributes["name"]; + if (name != null) + return new PropertyFilter(name, node.Value) { IsRegex = isRegex }; + break; + } + + throw new ArgumentException("Invalid filter element: " + node.Name, "xmlNode"); + } + + /// + /// Nested class provides an empty filter - one that always + /// returns true when called. It never matches explicitly. + /// +#if !PORTABLE && !SILVERLIGHT + [Serializable] +#endif + private class EmptyFilter : TestFilter + { + public override bool Match( ITest test ) + { + return true; + } + + public override bool Pass( ITest test ) + { + return true; + } + + public override bool IsExplicitMatch( ITest test ) + { + return false; + } + + public override TNode AddToXml(TNode parentNode, bool recursive) + { + return parentNode.AddElement("filter"); + } + } + +#region IXmlNodeBuilder Implementation + + /// + /// Adds an XML node + /// + /// True if recursive + /// The added XML node + public TNode ToXml(bool recursive) + { + return AddToXml(new TNode("dummy"), recursive); + } + + /// + /// Adds an XML node + /// + /// Parent node + /// True if recursive + /// The added XML node + public abstract TNode AddToXml(TNode parentNode, bool recursive); + +#endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestFixtureParameters.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestFixtureParameters.cs new file mode 100644 index 000000000..677aa01bc --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestFixtureParameters.cs @@ -0,0 +1,75 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// The TestCaseParameters class encapsulates method arguments and + /// other selected parameters needed for constructing + /// a parameterized test case. + /// + public class TestFixtureParameters : TestParameters, ITestFixtureData + { + #region Constructors + + /// + /// Default Constructor creates an empty parameter set + /// + public TestFixtureParameters() { } + + /// + /// Construct a non-runnable ParameterSet, specifying + /// the provider exception that made it invalid. + /// + public TestFixtureParameters(Exception exception) : base(exception) { } + + /// + /// Construct a parameter set with a list of arguments + /// + /// + public TestFixtureParameters(params object[] args) : base(args) { } + + /// + /// Construct a ParameterSet from an object implementing ITestCaseData + /// + /// + public TestFixtureParameters(ITestFixtureData data) : base(data) + { + TypeArgs = data.TypeArgs; + } + + #endregion + + #region ITestFixtureData Members + + /// + /// Type arguments used to create a generic fixture instance + /// + public Type[] TypeArgs { get; internal set; } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestListener.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestListener.cs new file mode 100644 index 000000000..05c46614e --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestListener.cs @@ -0,0 +1,66 @@ +// *********************************************************************** +// Copyright (c) 2009 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// TestListener provides an implementation of ITestListener that + /// does nothing. It is used only through its NULL property. + /// + public class TestListener : ITestListener + { + /// + /// Called when a test has just started + /// + /// The test that is starting + public void TestStarted(ITest test){} + + /// + /// Called when a test case has finished + /// + /// The result of the test + public void TestFinished(ITestResult result){} + + /// + /// Called when a test produces output for immediate display + /// + /// A TestOutput object containing the text to display + public void TestOutput(TestOutput output) { } + + /// + /// Construct a new TestListener - private so it may not be used. + /// + private TestListener() { } + + /// + /// Get a listener that does nothing + /// + public static ITestListener NULL + { + get { return new TestListener();} + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestNameGenerator.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestNameGenerator.cs new file mode 100644 index 000000000..10507f116 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestNameGenerator.cs @@ -0,0 +1,560 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace NUnit.Framework.Internal +{ + /// + /// TestNameGenerator is able to create test names according to + /// a coded pattern. + /// + public class TestNameGenerator + { + // TODO: Using a static here is not good it's the easiest + // way to get a temporary implementation without passing the + // pattern all the way down the test builder hierarchy + + /// + /// Default pattern used to generate names + /// + public static string DefaultTestNamePattern = "{m}{a}"; + + // The name pattern used by this TestNameGenerator + private string _pattern; + + // The list of NameFragments used to generate names + private List _fragments; + + /// + /// Construct a TestNameGenerator + /// + public TestNameGenerator() + { + _pattern = DefaultTestNamePattern; + } + + /// + /// Construct a TestNameGenerator + /// + /// The pattern used by this generator. + public TestNameGenerator(string pattern) + { + _pattern = pattern; + } + + /// + /// Get the display name for a TestMethod and it's arguments + /// + /// A TestMethod + /// The display name + public string GetDisplayName(TestMethod testMethod) + { + return GetDisplayName(testMethod, null); + } + + /// + /// Get the display name for a TestMethod and it's arguments + /// + /// A TestMethod + /// Arguments to be used + /// The display name + public string GetDisplayName(TestMethod testMethod, object[] args) + { + if (_fragments == null) + _fragments = BuildFragmentList(_pattern); + + var result = new StringBuilder(); + + foreach (var fragment in _fragments) + result.Append(fragment.GetText(testMethod, args)); + + return result.ToString(); + } + + #region Helper Methods + + private static List BuildFragmentList(string pattern) + { + var fragments = new List(); + + // Build a list of actions so this generator can be applied to + // multiple types and methods. + + int start = 0; + while (start < pattern.Length) + { + int lcurly = pattern.IndexOf('{', start); + if (lcurly < 0) // No more substitutions in pattern + break; + + int rcurly = pattern.IndexOf('}', lcurly); + if (rcurly < 0) + break; + + if (lcurly > start) // Handle fixedixed text before curly brace + fragments.Add(new FixedTextFragment(pattern.Substring(start, lcurly - start))); + + string token = pattern.Substring(lcurly, rcurly - lcurly + 1); + + switch (token) + { + case "{m}": + fragments.Add(new MethodNameFragment()); + break; + case "{i}": + fragments.Add(new TestIDFragment()); + break; + case "{n}": + fragments.Add(new NamespaceFragment()); + break; + case "{c}": + fragments.Add(new ClassNameFragment()); + break; + case "{C}": + fragments.Add(new ClassFullNameFragment()); + break; + case "{M}": + fragments.Add(new MethodFullNameFragment()); + break; + case "{a}": + fragments.Add(new ArgListFragment(0)); + break; + case "{0}": + case "{1}": + case "{2}": + case "{3}": + case "{4}": + case "{5}": + case "{6}": + case "{7}": + case "{8}": + case "{9}": + int index = token[1] - '0'; + fragments.Add(new ArgumentFragment(index, 40)); + break; + default: + char c = token[1]; + if (token.Length >= 5 && token[2] == ':' && (c == 'a' || char.IsDigit(c))) + { + int length; + + // NOTE: The code would be much simpler using TryParse. However, + // that method doesn't exist in the Compact Framework. + try + { + length = int.Parse(token.Substring(3, token.Length - 4)); + } + catch + { + length = -1; + } + if (length > 0) + { + if (c == 'a') + fragments.Add(new ArgListFragment(length)); + else // It's a digit + fragments.Add(new ArgumentFragment(c - '0', length)); + break; + } + } + + // Output the erroneous token to aid user in debugging + fragments.Add(new FixedTextFragment(token)); + break; + } + + start = rcurly + 1; + } + + + // Output any trailing plain text + if (start < pattern.Length) + fragments.Add(new FixedTextFragment(pattern.Substring(start))); + + return fragments; + } + + #endregion + + #region Nested Classes Representing Name Fragments + + private abstract class NameFragment + { + private const string THREE_DOTS = "..."; + + public virtual string GetText(TestMethod testMethod, object[] args) + { + return GetText(testMethod.Method.MethodInfo, args); + } + + public abstract string GetText(MethodInfo method, object[] args); + + protected static void AppendGenericTypeNames(StringBuilder sb, MethodInfo method) + { + sb.Append("<"); + int cnt = 0; + foreach (Type t in method.GetGenericArguments()) + { + if (cnt++ > 0) sb.Append(","); + sb.Append(t.Name); + } + sb.Append(">"); + } + + protected static string GetDisplayString(object arg, int stringMax) + { + string display = arg == null + ? "null" + : Convert.ToString(arg, System.Globalization.CultureInfo.InvariantCulture); + + if (arg is double) + { + double d = (double)arg; + + if (double.IsNaN(d)) + display = "double.NaN"; + else if (double.IsPositiveInfinity(d)) + display = "double.PositiveInfinity"; + else if (double.IsNegativeInfinity(d)) + display = "double.NegativeInfinity"; + else if (d == double.MaxValue) + display = "double.MaxValue"; + else if (d == double.MinValue) + display = "double.MinValue"; + else + { + if (display.IndexOf('.') == -1) + display += ".0"; + display += "d"; + } + } + else if (arg is float) + { + float f = (float)arg; + + if (float.IsNaN(f)) + display = "float.NaN"; + else if (float.IsPositiveInfinity(f)) + display = "float.PositiveInfinity"; + else if (float.IsNegativeInfinity(f)) + display = "float.NegativeInfinity"; + else if (f == float.MaxValue) + display = "float.MaxValue"; + else if (f == float.MinValue) + display = "float.MinValue"; + else + { + if (display.IndexOf('.') == -1) + display += ".0"; + display += "f"; + } + } + else if (arg is decimal) + { + decimal d = (decimal)arg; + if (d == decimal.MinValue) + display = "decimal.MinValue"; + else if (d == decimal.MaxValue) + display = "decimal.MaxValue"; + else + display += "m"; + } + else if (arg is long) + { + if (arg.Equals(long.MinValue)) + display = "long.MinValue"; + else if (arg.Equals(long.MaxValue)) + display = "long.MaxValue"; + else + display += "L"; + } + else if (arg is ulong) + { + ulong ul = (ulong)arg; + if (ul == ulong.MinValue) + display = "ulong.MinValue"; + else if (ul == ulong.MaxValue) + display = "ulong.MaxValue"; + else + display += "UL"; + } + else if (arg is string) + { + var str = (string)arg; + bool tooLong = stringMax > 0 && str.Length > stringMax; + int limit = tooLong ? stringMax - THREE_DOTS.Length : 0; + + StringBuilder sb = new StringBuilder(); + sb.Append("\""); + foreach (char c in str) + { + sb.Append(EscapeCharInString(c)); + if (tooLong && sb.Length > limit) + { + sb.Append(THREE_DOTS); + break; + } + } + sb.Append("\""); + display = sb.ToString(); + } + else if (arg is char) + { + display = "\'" + EscapeSingleChar((char)arg) + "\'"; + } + else if (arg is int) + { + if (arg.Equals(int.MaxValue)) + display = "int.MaxValue"; + else if (arg.Equals(int.MinValue)) + display = "int.MinValue"; + } + else if (arg is uint) + { + if (arg.Equals(uint.MaxValue)) + display = "uint.MaxValue"; + else if (arg.Equals(uint.MinValue)) + display = "uint.MinValue"; + } + else if (arg is short) + { + if (arg.Equals(short.MaxValue)) + display = "short.MaxValue"; + else if (arg.Equals(short.MinValue)) + display = "short.MinValue"; + } + else if (arg is ushort) + { + if (arg.Equals(ushort.MaxValue)) + display = "ushort.MaxValue"; + else if (arg.Equals(ushort.MinValue)) + display = "ushort.MinValue"; + } + else if (arg is byte) + { + if (arg.Equals(byte.MaxValue)) + display = "byte.MaxValue"; + else if (arg.Equals(byte.MinValue)) + display = "byte.MinValue"; + } + else if (arg is sbyte) + { + if (arg.Equals(sbyte.MaxValue)) + display = "sbyte.MaxValue"; + else if (arg.Equals(sbyte.MinValue)) + display = "sbyte.MinValue"; + } + + return display; + } + + private static string EscapeSingleChar(char c) + { + if (c == '\'') + return "\\\'"; + + return EscapeControlChar(c); + } + + private static string EscapeCharInString(char c) + { + if (c == '"') + return "\\\""; + + return EscapeControlChar(c); + } + + private static string EscapeControlChar(char c) + { + switch (c) + { + case '\\': + return "\\\\"; + case '\0': + return "\\0"; + case '\a': + return "\\a"; + case '\b': + return "\\b"; + case '\f': + return "\\f"; + case '\n': + return "\\n"; + case '\r': + return "\\r"; + case '\t': + return "\\t"; + case '\v': + return "\\v"; + + case '\x0085': + case '\x2028': + case '\x2029': + return string.Format("\\x{0:X4}", (int)c); + + default: + return c.ToString(); + } + } + } + + private class TestIDFragment : NameFragment + { + public override string GetText(MethodInfo method, object[] args) + { + return "{i}"; // No id available using MethodInfo + } + + public override string GetText(TestMethod testMethod, object[] args) + { + return testMethod.Id; + } + } + + private class FixedTextFragment : NameFragment + { + private string _text; + + public FixedTextFragment(string text) + { + _text = text; + } + + public override string GetText(MethodInfo method, object[] args) + { + return _text; + } + } + + private class MethodNameFragment : NameFragment + { + public override string GetText(MethodInfo method, object[] args) + { + var sb = new StringBuilder(); + + sb.Append(method.Name); + + if (method.IsGenericMethod) + AppendGenericTypeNames(sb, method); + + return sb.ToString(); + } + } + + private class NamespaceFragment : NameFragment + { + public override string GetText(MethodInfo method, object[] args) + { + return method.DeclaringType.Namespace; + } + } + + private class MethodFullNameFragment : NameFragment + { + public override string GetText(MethodInfo method, object[] args) + { + var sb = new StringBuilder(); + + sb.Append(method.DeclaringType.FullName); + sb.Append('.'); + sb.Append(method.Name); + + if (method.IsGenericMethod) + AppendGenericTypeNames(sb, method); + + return sb.ToString(); + } + } + + private class ClassNameFragment : NameFragment + { + public override string GetText(MethodInfo method, object[] args) + { + return method.DeclaringType.Name; + } + } + + private class ClassFullNameFragment : NameFragment + { + public override string GetText(MethodInfo method, object[] args) + { + return method.DeclaringType.FullName; + } + } + + private class ArgListFragment : NameFragment + { + private int _maxStringLength; + + public ArgListFragment(int maxStringLength) + { + _maxStringLength = maxStringLength; + } + + public override string GetText(MethodInfo method, object[] arglist) + { + var sb = new StringBuilder(); + + if (arglist != null) + { + sb.Append('('); + + for (int i = 0; i < arglist.Length; i++) + { + if (i > 0) sb.Append(","); + sb.Append(GetDisplayString(arglist[i], _maxStringLength)); + } + + sb.Append(')'); + } + + return sb.ToString(); + } + } + + private class ArgumentFragment : NameFragment + { + private int _index; + private int _maxStringLength; + + public ArgumentFragment(int index, int maxStringLength) + { + _index = index; + _maxStringLength = maxStringLength; + } + + public override string GetText(MethodInfo method, object[] args) + { + return _index < args.Length + ? GetDisplayString(args[_index], _maxStringLength) + : string.Empty; + } + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestParameters.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestParameters.cs new file mode 100644 index 000000000..704d6ed8f --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestParameters.cs @@ -0,0 +1,154 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// TestParameters is the abstract base class for all classes + /// that know how to provide data for constructing a test. + /// + public abstract class TestParameters : ITestData, IApplyToTest + { + #region Constructors + + /// + /// Default Constructor creates an empty parameter set + /// + public TestParameters() + { + RunState = RunState.Runnable; + Properties = new PropertyBag(); + } + + /// + /// Construct a parameter set with a list of arguments + /// + /// + public TestParameters(object[] args) + { + RunState = RunState.Runnable; + InitializeAguments(args); + Properties = new PropertyBag(); + } + + /// + /// Construct a non-runnable ParameterSet, specifying + /// the provider exception that made it invalid. + /// + public TestParameters(Exception exception) + { + RunState = RunState.NotRunnable; + Properties = new PropertyBag(); + + Properties.Set(PropertyNames.SkipReason, ExceptionHelper.BuildMessage(exception)); + Properties.Set(PropertyNames.ProviderStackTrace, ExceptionHelper.BuildStackTrace(exception)); + } + + /// + /// Construct a ParameterSet from an object implementing ITestData + /// + /// + public TestParameters(ITestData data) + { + RunState = data.RunState; + Properties = new PropertyBag(); + + TestName = data.TestName; + + InitializeAguments(data.Arguments); + + foreach (string key in data.Properties.Keys) + this.Properties[key] = data.Properties[key]; + } + + private void InitializeAguments(object[] args) + { + OriginalArguments = args; + + // We need to copy args, since we may change them + var numArgs = args.Length; + Arguments = new object[numArgs]; + Array.Copy(args, Arguments, numArgs); + } + + #endregion + + #region ITestData Members + + /// + /// The RunState for this set of parameters. + /// + public RunState RunState { get; set; } + + /// + /// The arguments to be used in running the test, + /// which must match the method signature. + /// + public object[] Arguments { get; internal set; } + + /// + /// A name to be used for this test case in lieu + /// of the standard generated name containing + /// the argument list. + /// + public string TestName { get; set; } + + /// + /// Gets the property dictionary for this test + /// + public IPropertyBag Properties { get; private set; } + + #endregion + + #region IApplyToTest Members + + /// + /// Applies ParameterSet _values to the test itself. + /// + /// A test. + public void ApplyToTest(Test test) + { + if (this.RunState != RunState.Runnable) + test.RunState = this.RunState; + + foreach (string key in Properties.Keys) + foreach (object value in Properties[key]) + test.Properties.Add(key, value); + } + + #endregion + + #region Other Public Properties + + /// + /// The original arguments provided by the user, + /// used for display purposes. + /// + public object[] OriginalArguments { get; private set; } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TestProgressReporter.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TestProgressReporter.cs new file mode 100644 index 000000000..819f06bc8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TestProgressReporter.cs @@ -0,0 +1,157 @@ +// *********************************************************************** +// Copyright (c) 2010 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +#if SILVERLIGHT +using System.Web.UI; +#endif // SILVERLIGHT +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// TestProgressReporter translates ITestListener events into + /// the async callbacks that are used to inform the client + /// software about the progress of a test run. + /// + public class TestProgressReporter : ITestListener + { + static Logger log = InternalTrace.GetLogger("TestProgressReporter"); + + private ICallbackEventHandler handler; + + /// + /// Initializes a new instance of the class. + /// + /// The callback handler to be used for reporting progress. + public TestProgressReporter(ICallbackEventHandler handler) + { + this.handler = handler; + } + + #region ITestListener Members + + /// + /// Called when a test has just started + /// + /// The test that is starting + public void TestStarted(ITest test) + { + string startElement = test is TestSuite + ? "start-suite" + : "start-test"; + + var parent = GetParent(test); + try + { + string report = string.Format( + "<{0} id=\"{1}\" parentId=\"{2}\" name=\"{3}\" fullname=\"{4}\"/>", + startElement, + test.Id, + parent != null ? parent.Id : string.Empty, + FormatAttributeValue(test.Name), + FormatAttributeValue(test.FullName)); + + handler.RaiseCallbackEvent(report); + } + catch (Exception ex) + { + log.Error("Exception processing " + test.FullName + NUnit.Env.NewLine + ex.ToString()); + } + } + + /// + /// Called when a test has finished. Sends a result summary to the callback. + /// to + /// + /// The result of the test + public void TestFinished(ITestResult result) + { + try + { + var node = result.ToXml(false); + var parent = GetParent(result.Test); + node.Attributes.Add("parentId", parent != null ? parent.Id : string.Empty); + handler.RaiseCallbackEvent(node.OuterXml); + } + catch (Exception ex) + { + log.Error("Exception processing " + result.FullName + NUnit.Env.NewLine + ex.ToString()); + } + } + + /// + /// Called when a test produces output for immediate display + /// + /// A TestOutput object containing the text to display + public void TestOutput(TestOutput output) + { + try + { + handler.RaiseCallbackEvent(output.ToXml()); + } + catch (Exception ex) + { + log.Error("Exception processing TestOutput event" + NUnit.Env.NewLine + ex.ToString()); + } + } + + #endregion + + #region Helper Methods + + /// + /// Returns the parent test item for the targer test item if it exists + /// + /// + /// parent test item + private static ITest GetParent(ITest test) + { + if (test == null || test.Parent == null) + { + return null; + } + + return test.Parent.IsSuite ? test.Parent : GetParent(test.Parent); + } + + /// + /// Makes a string safe for use as an attribute, replacing + /// characters characters that can't be used with their + /// corresponding xml representations. + /// + /// The string to be used + /// A new string with the _values replaced + private static string FormatAttributeValue(string original) + { + return original + .Replace("&", "&") + .Replace("\"", """) + .Replace("'", "'") + .Replace("<", "<") + .Replace(">", ">"); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs new file mode 100644 index 000000000..9b7a24aff --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs @@ -0,0 +1,60 @@ +// *********************************************************************** +// Copyright (c) 2010 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// ParameterizedFixtureSuite serves as a container for the set of test + /// fixtures created from a given Type using various parameters. + /// + public class ParameterizedFixtureSuite : TestSuite + { + private bool _genericFixture; + + /// + /// Initializes a new instance of the class. + /// + /// The ITypeInfo for the type that represents the suite. + public ParameterizedFixtureSuite(ITypeInfo typeInfo) : base(typeInfo.Namespace, typeInfo.GetDisplayName()) + { + _genericFixture = typeInfo.ContainsGenericParameters; + } + + /// + /// Gets a string representing the type of test + /// + /// + public override string TestType + { + get + { + return _genericFixture + ? "GenericFixture" + : "ParameterizedFixture"; + } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs new file mode 100644 index 000000000..e19924b34 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs @@ -0,0 +1,71 @@ +// *********************************************************************** +// Copyright (c) 2008 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Commands; + +namespace NUnit.Framework.Internal +{ + /// + /// ParameterizedMethodSuite holds a collection of individual + /// TestMethods with their arguments applied. + /// + public class ParameterizedMethodSuite : TestSuite + { + private bool _isTheory; + + /// + /// Construct from a MethodInfo + /// + /// + public ParameterizedMethodSuite(IMethodInfo method) + : base(method.TypeInfo.FullName, method.Name) + { + Method = method; +#if PORTABLE + _isTheory = false; +#else + _isTheory = method.IsDefined(true); +#endif + this.MaintainTestOrder = true; + } + + /// + /// Gets a string representing the type of test + /// + /// + public override string TestType + { + get + { + if (_isTheory) + return "Theory"; + + if (this.Method.ContainsGenericParameters) + return "GenericMethod"; + + return "ParameterizedMethod"; + } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs new file mode 100644 index 000000000..cb091270e --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs @@ -0,0 +1,55 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// SetUpFixture extends TestSuite and supports + /// Setup and TearDown methods. + /// + public class SetUpFixture : TestSuite, IDisposableFixture + { + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// The type. + public SetUpFixture( ITypeInfo type ) : base( type ) + { + this.Name = type.Namespace; + if (this.Name == null) + this.Name = "[default namespace]"; + int index = this.Name.LastIndexOf('.'); + if (index > 0) + this.Name = this.Name.Substring(index + 1); + + CheckSetUpTearDownMethods(typeof(OneTimeSetUpAttribute)); + CheckSetUpTearDownMethods(typeof(OneTimeTearDownAttribute)); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/Test.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/Test.cs new file mode 100644 index 000000000..f0318a379 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/Test.cs @@ -0,0 +1,421 @@ +// *********************************************************************** +// Copyright (c) 2012-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Reflection; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// The Test abstract class represents a test within the framework. + /// + public abstract class Test : ITest, IComparable + { + #region Fields + + /// + /// Static value to seed ids. It's started at 1000 so any + /// uninitialized ids will stand out. + /// + private static int _nextID = 1000; + + /// + /// The SetUp methods. + /// + protected MethodInfo[] setUpMethods; + + /// + /// The teardown methods + /// + protected MethodInfo[] tearDownMethods; + + /// + /// Used to cache the declaring type for this MethodInfo + /// + protected ITypeInfo DeclaringTypeInfo; + + /// + /// Method property backing field + /// + private IMethodInfo _method; + + #endregion + + #region Construction + + /// + /// Constructs a test given its name + /// + /// The name of the test + protected Test( string name ) + { + Guard.ArgumentNotNullOrEmpty(name, "name"); + + Initialize(name); + } + + /// + /// Constructs a test given the path through the + /// test hierarchy to its parent and a name. + /// + /// The parent tests full name + /// The name of the test + protected Test( string pathName, string name ) + { + Guard.ArgumentNotNullOrEmpty(pathName, "pathName"); + + Initialize(name); + + FullName = pathName + "." + name; + } + + /// + /// TODO: Documentation needed for constructor + /// + /// + protected Test(ITypeInfo typeInfo) + { + Initialize(typeInfo.GetDisplayName()); + + string nspace = typeInfo.Namespace; + if (nspace != null && nspace != "") + FullName = nspace + "." + Name; + TypeInfo = typeInfo; + } + + /// + /// Construct a test from a MethodInfo + /// + /// + protected Test(IMethodInfo method) + { + Initialize(method.Name); + + Method = method; + TypeInfo = method.TypeInfo; + FullName = method.TypeInfo.FullName + "." + Name; + } + + private void Initialize(string name) + { + FullName = Name = name; + Id = GetNextId(); + Properties = new PropertyBag(); + RunState = RunState.Runnable; + } + + private static string GetNextId() + { + return IdPrefix + unchecked(_nextID++); + } + + #endregion + + #region ITest Members + + /// + /// Gets or sets the id of the test + /// + /// + public string Id { get; set; } + + /// + /// Gets or sets the name of the test + /// + public string Name { get; set; } + + /// + /// Gets or sets the fully qualified name of the test + /// + /// + public string FullName { get; set; } + + /// + /// Gets the name of the class where this test was declared. + /// Returns null if the test is not associated with a class. + /// + public string ClassName + { + get + { + ITypeInfo typeInfo = TypeInfo; + + if (Method != null) + { + if (DeclaringTypeInfo == null) + DeclaringTypeInfo = new TypeWrapper(Method.MethodInfo.DeclaringType); + + typeInfo = DeclaringTypeInfo; + } + + if (typeInfo == null) + return null; + + return typeInfo.IsGenericType + ? typeInfo.GetGenericTypeDefinition().FullName + : typeInfo.FullName; + } + } + + /// + /// Gets the name of the method implementing this test. + /// Returns null if the test is not implemented as a method. + /// + public virtual string MethodName + { + get { return null; } + } + + /// + /// Gets the TypeInfo of the fixture used in running this test + /// or null if no fixture type is associated with it. + /// + public ITypeInfo TypeInfo { get; private set; } + + /// + /// Gets a MethodInfo for the method implementing this test. + /// Returns null if the test is not implemented as a method. + /// + public IMethodInfo Method + { + get { return _method; } + set + { + DeclaringTypeInfo = null; + _method = value; + } + } // public setter needed by NUnitTestCaseBuilder + + /// + /// Whether or not the test should be run + /// + public RunState RunState { get; set; } + + /// + /// Gets the name used for the top-level element in the + /// XML representation of this test + /// + public abstract string XmlElementName { get; } + + /// + /// Gets a string representing the type of test. Used as an attribute + /// value in the XML representation of a test and has no other + /// function in the framework. + /// + public virtual string TestType + { + get { return this.GetType().Name; } + } + + /// + /// Gets a count of test cases represented by + /// or contained under this test. + /// + public virtual int TestCaseCount + { + get { return 1; } + } + + /// + /// Gets the properties for this test + /// + public IPropertyBag Properties { get; private set; } + + /// + /// Returns true if this is a TestSuite + /// + public bool IsSuite + { + get { return this is TestSuite; } + } + + /// + /// Gets a bool indicating whether the current test + /// has any descendant tests. + /// + public abstract bool HasChildren { get; } + + /// + /// Gets the parent as a Test object. + /// Used by the core to set the parent. + /// + public ITest Parent { get; set; } + + /// + /// Gets this test's child tests + /// + /// A list of child tests + public abstract System.Collections.Generic.IList Tests { get; } + + /// + /// Gets or sets a fixture object for running this test. + /// + public virtual object Fixture { get; set; } + + #endregion + + #region Other Public Properties + + /// + /// Static prefix used for ids in this AppDomain. + /// Set by FrameworkController. + /// + public static string IdPrefix { get; set; } + + /// + /// Gets or Sets the Int value representing the seed for the RandomGenerator + /// + /// + public int Seed { get; set; } + + #endregion + + #region Internal Properties + + internal bool RequiresThread { get; set; } + + #endregion + + #region Other Public Methods + + /// + /// Creates a TestResult for this test. + /// + /// A TestResult suitable for this type of test. + public abstract TestResult MakeTestResult(); + +#if PORTABLE + /// + /// Modify a newly constructed test by applying any of NUnit's common + /// attributes, based on a supplied ICustomAttributeProvider, which is + /// usually the reflection element from which the test was constructed, + /// but may not be in some instances. The attributes retrieved are + /// saved for use in subsequent operations. + /// + /// An object deriving from MemberInfo + public void ApplyAttributesToTest(MemberInfo provider) + { + foreach (IApplyToTest iApply in provider.GetAttributes(true)) + iApply.ApplyToTest(this); + } + + /// + /// Modify a newly constructed test by applying any of NUnit's common + /// attributes, based on a supplied ICustomAttributeProvider, which is + /// usually the reflection element from which the test was constructed, + /// but may not be in some instances. The attributes retrieved are + /// saved for use in subsequent operations. + /// + /// An object deriving from MemberInfo + public void ApplyAttributesToTest(Assembly provider) + { + foreach (IApplyToTest iApply in provider.GetAttributes()) + iApply.ApplyToTest(this); + } +#else + /// + /// Modify a newly constructed test by applying any of NUnit's common + /// attributes, based on a supplied ICustomAttributeProvider, which is + /// usually the reflection element from which the test was constructed, + /// but may not be in some instances. The attributes retrieved are + /// saved for use in subsequent operations. + /// + /// An object implementing ICustomAttributeProvider + public void ApplyAttributesToTest(ICustomAttributeProvider provider) + { + foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true)) + iApply.ApplyToTest(this); + } +#endif + + #endregion + + #region Protected Methods + + /// + /// Add standard attributes and members to a test node. + /// + /// + /// + protected void PopulateTestNode(TNode thisNode, bool recursive) + { + thisNode.AddAttribute("id", this.Id.ToString()); + thisNode.AddAttribute("name", this.Name); + thisNode.AddAttribute("fullname", this.FullName); + if (this.MethodName != null) + thisNode.AddAttribute("methodname", this.MethodName); + if (this.ClassName != null) + thisNode.AddAttribute("classname", this.ClassName); + thisNode.AddAttribute("runstate", this.RunState.ToString()); + + if (Properties.Keys.Count > 0) + Properties.AddToXml(thisNode, recursive); + } + + #endregion + + #region IXmlNodeBuilder Members + + /// + /// Returns the Xml representation of the test + /// + /// If true, include child tests recursively + /// + public TNode ToXml(bool recursive) + { + return AddToXml(new TNode("dummy"), recursive); + } + + /// + /// Returns an XmlNode representing the current result after + /// adding it as a child of the supplied parent node. + /// + /// The parent node. + /// If true, descendant results are included + /// + public abstract TNode AddToXml(TNode parentNode, bool recursive); + + #endregion + + #region IComparable Members + + /// + /// Compares this test to another test for sorting purposes + /// + /// The other test + /// Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test + public int CompareTo(object obj) + { + Test other = obj as Test; + + if (other == null) + return -1; + + return this.FullName.CompareTo(other.FullName); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestAssembly.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestAssembly.cs new file mode 100644 index 000000000..4da338ae2 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestAssembly.cs @@ -0,0 +1,75 @@ +// *********************************************************************** +// Copyright (c) 2010 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.IO; +using System.Reflection; + +namespace NUnit.Framework.Internal +{ + /// + /// TestAssembly is a TestSuite that represents the execution + /// of tests in a managed assembly. + /// + public class TestAssembly : TestSuite + { + /// + /// Initializes a new instance of the class + /// specifying the Assembly and the path from which it was loaded. + /// + /// The assembly this test represents. + /// The path used to load the assembly. + public TestAssembly(Assembly assembly, string path) + : base(path) + { + this.Assembly = assembly; + this.Name = Path.GetFileName(path); + } + + /// + /// Initializes a new instance of the class + /// for a path which could not be loaded. + /// + /// The path used to load the assembly. + public TestAssembly(string path) : base(path) + { + this.Name = Path.GetFileName(path); + } + + /// + /// Gets the Assembly represented by this instance. + /// + public Assembly Assembly { get; private set; } + + /// + /// Gets the name used for the top-level element in the + /// XML representation of this test + /// + public override string TestType + { + get + { + return "Assembly"; + } + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestFixture.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestFixture.cs new file mode 100644 index 000000000..69c8d01b1 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestFixture.cs @@ -0,0 +1,50 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// TestFixture is a surrogate for a user test fixture class, + /// containing one or more tests. + /// + public class TestFixture : TestSuite, IDisposableFixture + { + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// Type of the fixture. + public TestFixture(ITypeInfo fixtureType) : base(fixtureType) + { + CheckSetUpTearDownMethods(typeof(OneTimeSetUpAttribute)); + CheckSetUpTearDownMethods(typeof(OneTimeTearDownAttribute)); + CheckSetUpTearDownMethods(typeof(SetUpAttribute)); + CheckSetUpTearDownMethods(typeof(TearDownAttribute)); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestMethod.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestMethod.cs new file mode 100644 index 000000000..295bdf03b --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestMethod.cs @@ -0,0 +1,153 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; + +namespace NUnit.Framework.Internal +{ + /// + /// The TestMethod class represents a Test implemented as a method. + /// + public class TestMethod : Test + { + #region Fields + + /// + /// The ParameterSet used to create this test method + /// + internal TestCaseParameters parms; + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// The method to be used as a test. + public TestMethod(IMethodInfo method) : base (method) { } + + /// + /// Initializes a new instance of the class. + /// + /// The method to be used as a test. + /// The suite or fixture to which the new test will be added + public TestMethod(IMethodInfo method, Test parentSuite) : base(method ) + { + // Needed to give proper fullname to test in a parameterized fixture. + // Without this, the arguments to the fixture are not included. + if (parentSuite != null) + FullName = parentSuite.FullName + "." + Name; + } + + #endregion + + #region Properties + + internal bool HasExpectedResult + { + get { return parms != null && parms.HasExpectedResult; } + } + + internal object ExpectedResult + { + get { return parms != null ? parms.ExpectedResult : null; } + } + + internal object[] Arguments + { + get { return parms != null ? parms.Arguments : null; } + } + + #endregion + + #region Test Overrides + + /// + /// Overridden to return a TestCaseResult. + /// + /// A TestResult for this test. + public override TestResult MakeTestResult() + { + return new TestCaseResult(this); + } + + /// + /// Gets a bool indicating whether the current test + /// has any descendant tests. + /// + public override bool HasChildren + { + get { return false; } + } + + /// + /// Returns a TNode representing the current result after + /// adding it as a child of the supplied parent node. + /// + /// The parent node. + /// If true, descendant results are included + /// + public override TNode AddToXml(TNode parentNode, bool recursive) + { + TNode thisNode = parentNode.AddElement(XmlElementName); + + PopulateTestNode(thisNode, recursive); + + thisNode.AddAttribute("seed", this.Seed.ToString()); + + return thisNode; + } + + /// + /// Gets this test's child tests + /// + /// A list of child tests + public override IList Tests + { + get { return new ITest[0]; } + } + + /// + /// Gets the name used for the top-level element in the + /// XML representation of this test + /// + public override string XmlElementName + { + get { return "test-case"; } + } + + /// + /// Returns the name of the method + /// + public override string MethodName + { + get { return Method.Name; } + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestSuite.cs b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestSuite.cs new file mode 100644 index 000000000..8e5b0088d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/Tests/TestSuite.cs @@ -0,0 +1,273 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal.Commands; + +#if NET_4_0 || NET_4_5 || PORTABLE +using System.Threading.Tasks; +#endif + +namespace NUnit.Framework.Internal +{ + /// + /// TestSuite represents a composite test, which contains other tests. + /// + public class TestSuite : Test + { + #region Fields + + /// + /// Our collection of child tests + /// + private List tests = new List(); + + #endregion + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The name of the suite. + public TestSuite(string name) : base(name) + { + Arguments = new object[0]; + } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the parent suite. + /// The name of the suite. + public TestSuite(string parentSuiteName, string name) + : base(parentSuiteName, name) + { + Arguments = new object[0]; + } + + /// + /// Initializes a new instance of the class. + /// + /// Type of the fixture. + public TestSuite(ITypeInfo fixtureType) + : base(fixtureType) + { + Arguments = new object[0]; + } + + /// + /// Initializes a new instance of the class. + /// + /// Type of the fixture. + public TestSuite(Type fixtureType) + : base(new TypeWrapper(fixtureType)) + { + Arguments = new object[0]; + } + + #endregion + + #region Public Methods + + /// + /// Sorts tests under this suite. + /// + public void Sort() + { + if (!MaintainTestOrder) + { + this.tests.Sort(); + + foreach (Test test in Tests) + { + TestSuite suite = test as TestSuite; + if (suite != null) + suite.Sort(); + } + } + } + +#if false + /// + /// Sorts tests under this suite using the specified comparer. + /// + /// The comparer. + public void Sort(IComparer comparer) + { + this.tests.Sort(comparer); + + foreach( Test test in Tests ) + { + TestSuite suite = test as TestSuite; + if ( suite != null ) + suite.Sort(comparer); + } + } +#endif + + /// + /// Adds a test to the suite. + /// + /// The test. + public void Add(Test test) + { + test.Parent = this; + tests.Add(test); + } + + #endregion + + #region Properties + + /// + /// Gets this test's child tests + /// + /// The list of child tests + public override IList Tests + { + get { return tests; } + } + + /// + /// Gets a count of test cases represented by + /// or contained under this test. + /// + /// + public override int TestCaseCount + { + get + { + int count = 0; + + foreach (Test test in Tests) + { + count += test.TestCaseCount; + } + return count; + } + } + + /// + /// The arguments to use in creating the fixture + /// + public object[] Arguments { get; internal set; } + + /// + /// Set to true to suppress sorting this suite's contents + /// + protected bool MaintainTestOrder { get; set; } + + #endregion + + #region Test Overrides + + /// + /// Overridden to return a TestSuiteResult. + /// + /// A TestResult for this test. + public override TestResult MakeTestResult() + { + return new TestSuiteResult(this); + } + + /// + /// Gets a bool indicating whether the current test + /// has any descendant tests. + /// + public override bool HasChildren + { + get + { + return tests.Count > 0; + } + } + + /// + /// Gets the name used for the top-level element in the + /// XML representation of this test + /// + public override string XmlElementName + { + get { return "test-suite"; } + } + + /// + /// Returns an XmlNode representing the current result after + /// adding it as a child of the supplied parent node. + /// + /// The parent node. + /// If true, descendant results are included + /// + public override TNode AddToXml(TNode parentNode, bool recursive) + { + TNode thisNode = parentNode.AddElement("test-suite"); + thisNode.AddAttribute("type", this.TestType); + + PopulateTestNode(thisNode, recursive); + thisNode.AddAttribute("testcasecount", this.TestCaseCount.ToString()); + + + if (recursive) + foreach (Test test in this.Tests) + test.AddToXml(thisNode, recursive); + + return thisNode; + } + + #endregion + + #region Helper Methods + + /// + /// Check that setup and teardown methods marked by certain attributes + /// meet NUnit's requirements and mark the tests not runnable otherwise. + /// + /// The attribute type to check for + protected void CheckSetUpTearDownMethods(Type attrType) + { + foreach (MethodInfo method in Reflect.GetMethodsWithAttribute(TypeInfo.Type, attrType, true)) + if (method.IsAbstract || + !method.IsPublic && !method.IsFamily || + method.GetParameters().Length > 0 || + method.ReturnType != typeof(void) +#if NET_4_0 || NET_4_5 || PORTABLE + && + method.ReturnType != typeof(Task) +#endif + ) + { + this.Properties.Set( + PropertyNames.SkipReason, + string.Format("Invalid signature for SetUp or TearDown method: {0}", method.Name)); + this.RunState = RunState.NotRunnable; + break; + } + } + + #endregion + } +} diff --git a/test/NUnitLite/src/framework/Internal/ThreadUtility.cs b/test/NUnitLite/NUnitFramework/framework/Internal/ThreadUtility.cs similarity index 85% rename from test/NUnitLite/src/framework/Internal/ThreadUtility.cs rename to test/NUnitLite/NUnitFramework/framework/Internal/ThreadUtility.cs index f5262475b..4624ba968 100644 --- a/test/NUnitLite/src/framework/Internal/ThreadUtility.cs +++ b/test/NUnitLite/NUnitFramework/framework/Internal/ThreadUtility.cs @@ -21,17 +21,17 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if (CLR_2_0 || CLR_4_0) && !NETCF && !SILVERLIGHT +#if !PORTABLE using System; using System.Threading; namespace NUnit.Framework.Internal { /// - /// The ThreadUtility class encapsulates several static methods - /// useful when working with threads. + /// ThreadUtility provides a set of static methods convenient + /// for working with threads. /// - public class ThreadUtility + public static class ThreadUtility { /// /// Do our best to Kill a thread @@ -39,9 +39,14 @@ public class ThreadUtility /// The thread to kill public static void Kill(Thread thread) { +#if SILVERLIGHT + thread.Abort(); +#else Kill(thread, null); +#endif } +#if !SILVERLIGHT /// /// Do our best to kill a thread, passing state info /// @@ -58,17 +63,21 @@ public static void Kill(Thread thread, object stateInfo) } catch (ThreadStateException) { +#if !NETCF // Although obsolete, this use of Resume() takes care of - // the odd case where a ThreadStateException is received - // so we continue to use it. + // the odd case where a ThreadStateException is received. +#pragma warning disable 0618,0612 // Thread.Resume has been deprecated thread.Resume(); +#pragma warning restore 0618,0612 // Thread.Resume has been deprecated +#endif } +#if !NETCF if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 ) thread.Interrupt(); +#endif } - - private ThreadUtility() { } +#endif } } #endif diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TypeHelper.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TypeHelper.cs new file mode 100644 index 000000000..30cb452cb --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TypeHelper.cs @@ -0,0 +1,393 @@ +// *********************************************************************** +// Copyright (c) 2008-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +#if NETCF || PORTABLE +using System.Linq; +#endif +using System.Reflection; +using System.Text; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// TypeHelper provides static methods that operate on Types. + /// + public class TypeHelper + { + private const int STRING_MAX = 40; + private const int STRING_LIMIT = STRING_MAX - 3; + private const string THREE_DOTS = "..."; + + internal sealed class NonmatchingTypeClass + { + } + + /// + /// A special value, which is used to indicate that BestCommonType() method + /// was unable to find a common type for the specified arguments. + /// + public static readonly Type NonmatchingType = typeof( NonmatchingTypeClass ); + + /// + /// Gets the display name for a Type as used by NUnit. + /// + /// The Type for which a display name is needed. + /// The display name for the Type + public static string GetDisplayName(Type type) + { + if (type.IsGenericParameter) + return type.Name; + + if (type.GetTypeInfo().IsGenericType) + { + string name = type.FullName; + int index = name.IndexOf('['); + if (index >= 0) name = name.Substring(0, index); + + index = name.LastIndexOf('.'); + if (index >= 0) name = name.Substring(index+1); + + var genericArguments = type.GetGenericArguments(); + var currentArgument = 0; + + StringBuilder sb = new StringBuilder(); + + bool firstClassSeen = false; + foreach (string nestedClass in name.Split('+')) + { + if (firstClassSeen) + sb.Append("+"); + + firstClassSeen = true; + + index = nestedClass.IndexOf('`'); + if (index >= 0) + { + var nestedClassName = nestedClass.Substring(0, index); + sb.Append(nestedClassName); + sb.Append("<"); + + var argumentCount = Int32.Parse(nestedClass.Substring(index + 1)); + for (int i = 0; i < argumentCount; i++) + { + if (i > 0) + sb.Append(","); + + sb.Append(GetDisplayName(genericArguments[currentArgument++])); + } + sb.Append(">"); + } + else + sb.Append(nestedClass); + } + + return sb.ToString(); + } + + int lastdot = type.FullName.LastIndexOf('.'); + return lastdot >= 0 + ? type.FullName.Substring(lastdot+1) + : type.FullName; + } + + /// + /// Gets the display name for a Type as used by NUnit. + /// + /// The Type for which a display name is needed. + /// The arglist provided. + /// The display name for the Type + public static string GetDisplayName(Type type, object[] arglist) + { + string baseName = GetDisplayName(type); + if (arglist == null || arglist.Length == 0) + return baseName; + + StringBuilder sb = new StringBuilder( baseName ); + + sb.Append("("); + for (int i = 0; i < arglist.Length; i++) + { + if (i > 0) sb.Append(","); + + object arg = arglist[i]; + string display = arg == null ? "null" : arg.ToString(); + + if (arg is double || arg is float) + { + if (display.IndexOf('.') == -1) + display += ".0"; + display += arg is double ? "d" : "f"; + } + else if (arg is decimal) display += "m"; + else if (arg is long) display += "L"; + else if (arg is ulong) display += "UL"; + else if (arg is string) + { + if (display.Length > STRING_MAX) + display = display.Substring(0, STRING_LIMIT) + THREE_DOTS; + display = "\"" + display + "\""; + } + + sb.Append(display); + } + sb.Append(")"); + + return sb.ToString(); + } + + /// + /// Returns the best fit for a common type to be used in + /// matching actual arguments to a methods Type parameters. + /// + /// The first type. + /// The second type. + /// Either type1 or type2, depending on which is more general. + public static Type BestCommonType(Type type1, Type type2) + { + if ( type1 == TypeHelper.NonmatchingType ) return TypeHelper.NonmatchingType; + if ( type2 == TypeHelper.NonmatchingType ) return TypeHelper.NonmatchingType; + + if (type1 == type2) return type1; + if (type1 == null) return type2; + if (type2 == null) return type1; + + if (TypeHelper.IsNumeric(type1) && TypeHelper.IsNumeric(type2)) + { + if (type1 == typeof(double)) return type1; + if (type2 == typeof(double)) return type2; + + if (type1 == typeof(float)) return type1; + if (type2 == typeof(float)) return type2; + + if (type1 == typeof(decimal)) return type1; + if (type2 == typeof(decimal)) return type2; + + if (type1 == typeof(UInt64)) return type1; + if (type2 == typeof(UInt64)) return type2; + + if (type1 == typeof(Int64)) return type1; + if (type2 == typeof(Int64)) return type2; + + if (type1 == typeof(UInt32)) return type1; + if (type2 == typeof(UInt32)) return type2; + + if (type1 == typeof(Int32)) return type1; + if (type2 == typeof(Int32)) return type2; + + if (type1 == typeof(UInt16)) return type1; + if (type2 == typeof(UInt16)) return type2; + + if (type1 == typeof(Int16)) return type1; + if (type2 == typeof(Int16)) return type2; + + if (type1 == typeof(byte)) return type1; + if (type2 == typeof(byte)) return type2; + + if (type1 == typeof(sbyte)) return type1; + if (type2 == typeof(sbyte)) return type2; + } + + if ( type1.IsAssignableFrom( type2 ) ) return type1; + if ( type2.IsAssignableFrom( type1 ) ) return type2; + + return TypeHelper.NonmatchingType; + } + + /// + /// Determines whether the specified type is numeric. + /// + /// The type to be examined. + /// + /// true if the specified type is numeric; otherwise, false. + /// + public static bool IsNumeric(Type type) + { + return type == typeof(double) || + type == typeof(float) || + type == typeof(decimal) || + type == typeof(Int64) || + type == typeof(Int32) || + type == typeof(Int16) || + type == typeof(UInt64) || + type == typeof(UInt32) || + type == typeof(UInt16) || + type == typeof(byte) || + type == typeof(sbyte); + } + + /// + /// Convert an argument list to the required parameter types. + /// Currently, only widening numeric conversions are performed. + /// + /// An array of args to be converted + /// A ParameterInfo[] whose types will be used as targets + public static void ConvertArgumentList(object[] arglist, IParameterInfo[] parameters) + { + System.Diagnostics.Debug.Assert(arglist.Length <= parameters.Length); + + for (int i = 0; i < arglist.Length; i++) + { + object arg = arglist[i]; + +#if PORTABLE + if (arg != null) +#else + if (arg != null && arg is IConvertible) +#endif + { + Type argType = arg.GetType(); + Type targetType = parameters[i].ParameterType; + bool convert = false; + + if (argType != targetType && !argType.IsAssignableFrom(targetType)) + { + if (IsNumeric(argType) && IsNumeric(targetType)) + { + if (targetType == typeof(double) || targetType == typeof(float)) + convert = arg is int || arg is long || arg is short || arg is byte || arg is sbyte; + else + if (targetType == typeof(long)) + convert = arg is int || arg is short || arg is byte || arg is sbyte; + else + if (targetType == typeof(short)) + convert = arg is byte || arg is sbyte; + } + } + + if (convert) + arglist[i] = Convert.ChangeType(arg, targetType, + System.Globalization.CultureInfo.InvariantCulture); + } + } + } + + /// + /// Determines whether this instance can deduce type args for a generic type from the supplied arguments. + /// + /// The type to be examined. + /// The arglist. + /// The type args to be used. + /// + /// true if this the provided args give sufficient information to determine the type args to be used; otherwise, false. + /// + public static bool CanDeduceTypeArgsFromArgs(Type type, object[] arglist, ref Type[] typeArgsOut) + { + Type[] typeParameters = type.GetGenericArguments(); + +#if NETCF || PORTABLE + Type[] argTypes = arglist.Select(a => a == null ? typeof(object) : a.GetType()).ToArray(); + if (argTypes.Length != typeParameters.Length || argTypes.Any(at => at.GetTypeInfo().IsGenericType)) + return false; + try + { + type = type.MakeGenericType(argTypes); + } + catch (Exception) + { + return false; + } +#endif + + foreach (ConstructorInfo ctor in type.GetConstructors()) + { + ParameterInfo[] parameters = ctor.GetParameters(); + if (parameters.Length != arglist.Length) + continue; + + Type[] typeArgs = new Type[typeParameters.Length]; + for (int i = 0; i < typeArgs.Length; i++) + { + for (int j = 0; j < arglist.Length; j++) + { + if (typeParameters[i].IsGenericParameter || parameters[j].ParameterType.Equals(typeParameters[i])) + typeArgs[i] = TypeHelper.BestCommonType( + typeArgs[i], + arglist[j].GetType()); + } + + if (typeArgs[i] == null) + { + typeArgs = null; + break; + } + } + + if (typeArgs != null) + { + typeArgsOut = typeArgs; + return true; + } + } + + return false; + } + + /// + /// Gets the _values for an enumeration, using Enum.GetTypes + /// where available, otherwise through reflection. + /// + /// + /// + public static Array GetEnumValues(Type enumType) + { +#if NETCF || SILVERLIGHT + FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); + + Array enumValues = Array.CreateInstance(enumType, fields.Length); + + for (int index = 0; index < fields.Length; index++) + enumValues.SetValue(fields[index].GetValue(enumType), index); + + return enumValues; +#else + return Enum.GetValues(enumType); +#endif + } + + /// + /// Gets the ids of the _values for an enumeration, + /// using Enum.GetNames where available, otherwise + /// through reflection. + /// + /// + /// + public static string[] GetEnumNames(Type enumType) + { +#if NETCF || SILVERLIGHT + FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); + + string[] names = new string[fields.Length]; + + for (int index = 0; index < fields.Length; index++) + names[index] = fields[index].Name; + + return names; +#else + return Enum.GetNames(enumType); +#endif + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Internal/TypeWrapper.cs b/test/NUnitLite/NUnitFramework/framework/Internal/TypeWrapper.cs new file mode 100644 index 000000000..3ea9ccec8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Internal/TypeWrapper.cs @@ -0,0 +1,275 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal +{ + /// + /// The TypeWrapper class wraps a Type so it may be used in + /// a platform-independent manner. + /// + public class TypeWrapper : ITypeInfo + { + /// + /// Construct a TypeWrapper for a specified Type. + /// + public TypeWrapper(Type type) + { + Guard.ArgumentNotNull(type, "Type"); + + Type = type; + } + + /// + /// Gets the underlying Type on which this TypeWrapper is based. + /// + public Type Type { get; private set; } + + /// + /// Gets the base type of this type as an ITypeInfo + /// + public ITypeInfo BaseType + { + get + { + var baseType = Type.GetTypeInfo().BaseType; + + return baseType != null + ? new TypeWrapper(baseType) + : null; + } + } + + /// + /// Gets the Name of the Type + /// + public string Name + { + get { return Type.Name; } + } + + /// + /// Gets the FullName of the Type + /// + public string FullName + { + get { return Type.FullName; } + } + + /// + /// Gets the assembly in which the type is declared + /// + public Assembly Assembly + { + get { return Type.GetTypeInfo().Assembly; } + } + + /// + /// Gets the namespace of the Type + /// + public string Namespace + { + get { return Type.Namespace; } + } + + /// + /// Gets a value indicating whether the type is abstract. + /// + public bool IsAbstract + { + get { return Type.GetTypeInfo().IsAbstract; } + } + + /// + /// Gets a value indicating whether the Type is a generic Type + /// + public bool IsGenericType + { + get { return Type.GetTypeInfo().IsGenericType; } + } + + /// + /// Returns true if the Type wrapped is T + /// + public bool IsType(Type type) + { + return Type == type; + } + + /// + /// Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types. + /// + public bool ContainsGenericParameters + { + get { return Type.GetTypeInfo().ContainsGenericParameters; } + } + + /// + /// Gets a value indicating whether the Type is a generic Type definition + /// + public bool IsGenericTypeDefinition + { + get { return Type.GetTypeInfo().IsGenericTypeDefinition; } + } + + /// + /// Gets a value indicating whether the type is sealed. + /// + public bool IsSealed + { + get { return Type.GetTypeInfo().IsSealed; } + } + + /// + /// Gets a value indicating whether this type represents a static class. + /// + public bool IsStaticClass + { + get { return Type.GetTypeInfo().IsSealed && Type.GetTypeInfo().IsAbstract; } + } + + /// + /// Get the display name for this type + /// + public string GetDisplayName() + { + return TypeHelper.GetDisplayName(Type); + } + + /// + /// Get the display name for an object of this type, constructed with the specified args. + /// + public string GetDisplayName(object[] args) + { + return TypeHelper.GetDisplayName(Type, args); + } + + /// + /// Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments + /// + public ITypeInfo MakeGenericType(Type[] typeArgs) + { + return new TypeWrapper(Type.MakeGenericType(typeArgs)); + } + + /// + /// Returns a Type representing a generic type definition from which this Type can be constructed. + /// + public Type GetGenericTypeDefinition() + { + return Type.GetGenericTypeDefinition(); + } + + /// + /// Returns an array of custom attributes of the specified type applied to this type + /// + public T[] GetCustomAttributes(bool inherit) where T : class + { +#if PORTABLE + return Type.GetTypeInfo().GetAttributes(inherit).ToArray(); +#else + return (T[])Type.GetCustomAttributes(typeof(T), inherit); +#endif + } + + /// + /// Returns a value indicating whether the type has an attribute of the specified type. + /// + /// + /// + /// + public bool IsDefined(bool inherit) + { +#if PORTABLE + return Type.GetTypeInfo().GetCustomAttributes(inherit).Any(a => typeof(T).IsAssignableFrom(a.GetType())); +#else + return Type.GetTypeInfo().IsDefined(typeof(T), inherit); +#endif + } + + /// + /// Returns a flag indicating whether this type has a method with an attribute of the specified type. + /// + /// + /// + public bool HasMethodWithAttribute(Type attributeType) + { + return Reflect.HasMethodWithAttribute(Type, attributeType); + } + + /// + /// Returns an array of IMethodInfos for methods of this Type + /// that match the specified flags. + /// + public IMethodInfo[] GetMethods(BindingFlags flags) + { + var methods = Type.GetMethods(flags); + var result = new MethodWrapper[methods.Length]; + + for (int i = 0; i < methods.Length; i++) + result[i] = new MethodWrapper(Type, methods[i]); + + return result; + } + + /// + /// Gets the public constructor taking the specified argument Types + /// + public ConstructorInfo GetConstructor(Type[] argTypes) + { + return Type.GetConstructors() + .Where(c => c.GetParameters().ParametersMatch(argTypes)) + .FirstOrDefault(); + } + + /// + /// Returns a value indicating whether this Type has a public constructor taking the specified argument Types. + /// + public bool HasConstructor(Type[] argTypes) + { + return GetConstructor(argTypes) != null; + } + + /// + /// Construct an object of this Type, using the specified arguments. + /// + public object Construct(object[] args) + { + return Reflect.Construct(Type, args); + } + + /// + /// Override ToString() so that error messages in NUnit's own tests make sense + /// + public override string ToString() + { + return Type.ToString(); + } + } +} diff --git a/test/NUnitLite/src/framework/Is.cs b/test/NUnitLite/NUnitFramework/framework/Is.cs similarity index 84% rename from test/NUnitLite/src/framework/Is.cs rename to test/NUnitLite/NUnitFramework/framework/Is.cs index fe32db8e4..1923ef079 100644 --- a/test/NUnitLite/src/framework/Is.cs +++ b/test/NUnitLite/NUnitFramework/framework/Is.cs @@ -117,7 +117,19 @@ public static LessThanConstraint Negative { get { return new LessThanConstraint(0); } } - + + #endregion + + #region Zero + + /// + /// Returns a constraint that tests for equality with zero + /// + public static EqualConstraint Zero + { + get { return new EqualConstraint(0); } + } + #endregion #region NaN @@ -159,7 +171,7 @@ public static UniqueItemsConstraint Unique #region BinarySerializable -#if !NETCF && !SILVERLIGHT +#if !NETCF && !SILVERLIGHT && !PORTABLE /// /// Returns a constraint that tests whether an object graph is serializable in binary format. /// @@ -173,7 +185,7 @@ public static BinarySerializableConstraint BinarySerializable #region XmlSerializable -#if !SILVERLIGHT +#if !SILVERLIGHT && !PORTABLE /// /// Returns a constraint that tests whether an object graph is serializable in xml format. /// @@ -213,7 +225,7 @@ public static SameAsConstraint SameAs(object expected) /// /// Returns a constraint that tests whether the - /// actual value is greater than the suppled argument + /// actual value is greater than the supplied argument /// public static GreaterThanConstraint GreaterThan(object expected) { @@ -226,7 +238,7 @@ public static GreaterThanConstraint GreaterThan(object expected) /// /// Returns a constraint that tests whether the - /// actual value is greater than or equal to the suppled argument + /// actual value is greater than or equal to the supplied argument /// public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { @@ -235,7 +247,7 @@ public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) /// /// Returns a constraint that tests whether the - /// actual value is greater than or equal to the suppled argument + /// actual value is greater than or equal to the supplied argument /// public static GreaterThanOrEqualConstraint AtLeast(object expected) { @@ -248,7 +260,7 @@ public static GreaterThanOrEqualConstraint AtLeast(object expected) /// /// Returns a constraint that tests whether the - /// actual value is less than the suppled argument + /// actual value is less than the supplied argument /// public static LessThanConstraint LessThan(object expected) { @@ -261,7 +273,7 @@ public static LessThanConstraint LessThan(object expected) /// /// Returns a constraint that tests whether the - /// actual value is less than or equal to the suppled argument + /// actual value is less than or equal to the supplied argument /// public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { @@ -270,7 +282,7 @@ public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected) /// /// Returns a constraint that tests whether the - /// actual value is less than or equal to the suppled argument + /// actual value is less than or equal to the supplied argument /// public static LessThanOrEqualConstraint AtMost(object expected) { @@ -290,16 +302,14 @@ public static ExactTypeConstraint TypeOf(Type expectedType) return new ExactTypeConstraint(expectedType); } -#if CLR_2_0 || CLR_4_0 /// /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// - public static ExactTypeConstraint TypeOf() + public static ExactTypeConstraint TypeOf() { - return new ExactTypeConstraint(typeof(T)); + return new ExactTypeConstraint(typeof(TExpected)); } -#endif #endregion @@ -314,16 +324,14 @@ public static InstanceOfTypeConstraint InstanceOf(Type expectedType) return new InstanceOfTypeConstraint(expectedType); } -#if CLR_2_0 || CLR_4_0 /// /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// - public static InstanceOfTypeConstraint InstanceOf() + public static InstanceOfTypeConstraint InstanceOf() { - return new InstanceOfTypeConstraint(typeof(T)); + return new InstanceOfTypeConstraint(typeof(TExpected)); } -#endif #endregion @@ -338,16 +346,14 @@ public static AssignableFromConstraint AssignableFrom(Type expectedType) return new AssignableFromConstraint(expectedType); } -#if CLR_2_0 || CLR_4_0 /// /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// - public static AssignableFromConstraint AssignableFrom() + public static AssignableFromConstraint AssignableFrom() { - return new AssignableFromConstraint(typeof(T)); + return new AssignableFromConstraint(typeof(TExpected)); } -#endif #endregion @@ -355,23 +361,21 @@ public static AssignableFromConstraint AssignableFrom() /// /// Returns a constraint that tests whether the actual value - /// is assignable from the type supplied as an argument. + /// is assignable to the type supplied as an argument. /// public static AssignableToConstraint AssignableTo(Type expectedType) { return new AssignableToConstraint(expectedType); } -#if CLR_2_0 || CLR_4_0 /// /// Returns a constraint that tests whether the actual value - /// is assignable from the type supplied as an argument. + /// is assignable to the type supplied as an argument. /// - public static AssignableToConstraint AssignableTo() + public static AssignableToConstraint AssignableTo() { - return new AssignableToConstraint(typeof(T)); + return new AssignableToConstraint(typeof(TExpected)); } -#endif #endregion @@ -402,6 +406,19 @@ public static CollectionSubsetConstraint SubsetOf(IEnumerable expected) #endregion + #region SupersetOf + + /// + /// Returns a constraint that tests whether the actual value + /// is a superset of the collection supplied as an argument. + /// + public static CollectionSupersetConstraint SupersetOf(IEnumerable expected) + { + return new CollectionSupersetConstraint(expected); + } + + #endregion + #region Ordered /// @@ -420,6 +437,7 @@ public static CollectionOrderedConstraint Ordered /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// + [Obsolete("Deprecated, use Does.Contain")] public static SubstringConstraint StringContaining(string expected) { return new SubstringConstraint(expected); @@ -433,6 +451,7 @@ public static SubstringConstraint StringContaining(string expected) /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// + [Obsolete("Deprecated, use Does.StartWith")] public static StartsWithConstraint StringStarting(string expected) { return new StartsWithConstraint(expected); @@ -446,6 +465,7 @@ public static StartsWithConstraint StringStarting(string expected) /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// + [Obsolete("Deprecated, use Does.EndWith")] public static EndsWithConstraint StringEnding(string expected) { return new EndsWithConstraint(expected); @@ -455,19 +475,19 @@ public static EndsWithConstraint StringEnding(string expected) #region StringMatching -#if !NETCF /// /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// + [Obsolete("Deprecated, use Does.Match")] public static RegexConstraint StringMatching(string pattern) { return new RegexConstraint(pattern); } -#endif #endregion - + +#if !PORTABLE #region SamePath /// @@ -485,9 +505,9 @@ public static SamePathConstraint SamePath(string expected) /// /// Returns a constraint that tests whether the path provided - /// is under an expected path after canonicalization. + /// is a subpath of the expected path after canonicalization. /// - public static SubPathConstraint SubPath(string expected) + public static SubPathConstraint SubPathOf(string expected) { return new SubPathConstraint(expected); } @@ -506,28 +526,22 @@ public static SamePathOrUnderConstraint SamePathOrUnder(string expected) } #endregion +#endif #region InRange -#if CLR_2_0 || CLR_4_0 - /// - /// Returns a constraint that tests whether the actual value falls - /// within a specified range. - /// - public static RangeConstraint InRange(T from, T to) where T : IComparable - { - return new RangeConstraint(from, to); - } -#else /// - /// Returns a constraint that tests whether the actual value falls - /// within a specified range. + /// Returns a constraint that tests whether the actual value falls + /// inclusively within a specified range. /// + /// from must be less than or equal to true + /// Inclusive beginning of the range. Must be less than or equal to to. + /// Inclusive end of the range. Must be greater than or equal to from. + /// public static RangeConstraint InRange(IComparable from, IComparable to) { return new RangeConstraint(from, to); } -#endif #endregion diff --git a/test/NUnitLite/src/framework/Iz.cs b/test/NUnitLite/NUnitFramework/framework/Iz.cs similarity index 100% rename from test/NUnitLite/src/framework/Iz.cs rename to test/NUnitLite/NUnitFramework/framework/Iz.cs diff --git a/test/NUnitLite/NUnitFramework/framework/List.cs b/test/NUnitLite/NUnitFramework/framework/List.cs new file mode 100644 index 000000000..c487321d8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/List.cs @@ -0,0 +1,45 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Collections; + +namespace NUnit.Framework +{ + /// + /// The List class is a helper class with properties and methods + /// that supply a number of constraints used with lists and collections. + /// + public class List + { + /// + /// List.Map returns a ListMapper, which can be used to map + /// the original collection to another collection. + /// + /// + /// + public static ListMapper Map( ICollection actual ) + { + return new ListMapper( actual ); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/ListMapper.cs b/test/NUnitLite/NUnitFramework/framework/ListMapper.cs new file mode 100644 index 000000000..c55ef0551 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/ListMapper.cs @@ -0,0 +1,71 @@ +// *********************************************************************** +// Copyright (c) 2008 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using NUnit.Compatibility; + +namespace NUnit.Framework +{ + /// + /// ListMapper is used to transform a collection used as an actual argument + /// producing another collection to be used in the assertion. + /// + public class ListMapper + { + ICollection original; + + /// + /// Construct a ListMapper based on a collection + /// + /// The collection to be transformed + public ListMapper( ICollection original ) + { + this.original = original; + } + + /// + /// Produces a collection containing all the _values of a property + /// + /// The collection of property _values + /// + public ICollection Property( string name ) + { + var propList = new List(); + foreach( object item in original ) + { + PropertyInfo property = item.GetType().GetProperty( name, + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ); + if ( property == null ) + throw new ArgumentException( string.Format( + "{0} does not have a {1} property", item, name ) ); + + propList.Add( property.GetValue( item, null ) ); + } + + return propList; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/Properties/AssemblyInfo.cs b/test/NUnitLite/NUnitFramework/framework/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..1f5db84cf --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/Properties/AssemblyInfo.cs @@ -0,0 +1,59 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; + +[assembly: InternalsVisibleTo("nunit.framework.tests, PublicKey=002400000480000094" + + "000000060200000024000052534131000400000100010031eea" + + "370b1984bfa6d1ea760e1ca6065cee41a1a279ca234933fe977" + + "a096222c0e14f9e5a17d5689305c6d7f1206a85a53c48ca0100" + + "80799d6eeef61c98abd18767827dc05daea6b6fbd2e868410d9" + + "bee5e972a004ddd692dec8fa404ba4591e847a8cf35de21c2d3" + + "723bc8d775a66b594adeb967537729fe2a446b548cd57a6")] + +#if NET_4_5 +[assembly: AssemblyTitle("NUnit Framework .NET 4.5")] +#elif NET_4_0 +[assembly: AssemblyTitle("NUnit Framework .NET 4.0")] +#elif NET_2_0 +[assembly: AssemblyTitle("NUnit Framework .NET 2.0")] +#elif SL_5_0 +[assembly: AssemblyTitle("NUnit Framework Silverlight 5.0")] +#elif NETCF_3_5 +[assembly: AssemblyTitle("NUnit Framework CF 3.5")] +#elif PORTABLE +[assembly: AssemblyTitle("NUnit Framework Portable")] +#else +[assembly: AssemblyTitle("NUnit Framework")] +#endif + +[assembly: AssemblyDescription("")] +[assembly: AssemblyCulture("")] +[assembly: CLSCompliant(true)] + +#if !SILVERLIGHT && !NETCF && !PORTABLE +[assembly: AllowPartiallyTrustedCallers] +#endif \ No newline at end of file diff --git a/test/NUnitLite/src/framework/SpecialValue.cs b/test/NUnitLite/NUnitFramework/framework/SpecialValue.cs similarity index 94% rename from test/NUnitLite/src/framework/SpecialValue.cs rename to test/NUnitLite/NUnitFramework/framework/SpecialValue.cs index 15eb1c657..60923bcb8 100644 --- a/test/NUnitLite/src/framework/SpecialValue.cs +++ b/test/NUnitLite/NUnitFramework/framework/SpecialValue.cs @@ -29,12 +29,12 @@ namespace NUnit.Framework /// The SpecialValue enum is used to represent TestCase arguments /// that cannot be used as arguments to an Attribute. /// - public enum SpecialValue - { + public enum SpecialValue + { /// /// Null represents a null value, which cannot be used as an - /// argument to an attribute under .NET 1.x + /// argument to an attriute under .NET 1.x /// Null - } + } } diff --git a/test/NUnitLite/NUnitFramework/framework/StringAssert.cs b/test/NUnitLite/NUnitFramework/framework/StringAssert.cs new file mode 100644 index 000000000..77c92ef00 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/StringAssert.cs @@ -0,0 +1,315 @@ +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.ComponentModel; +using NUnit.Framework.Constraints; + +namespace NUnit.Framework +{ + /// + /// Basic Asserts on strings. + /// + public class StringAssert + { + #region Equals and ReferenceEquals + + /// + /// The Equals method throws an InvalidOperationException. This is done + /// to make sure there is no mistake by calling this function. + /// + /// + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public static new bool Equals(object a, object b) + { + throw new InvalidOperationException("StringAssert.Equals should not be used for Assertions"); + } + + /// + /// override the default ReferenceEquals to throw an InvalidOperationException. This + /// implementation makes sure there is no mistake in calling this function + /// as part of Assert. + /// + /// + /// + public static new void ReferenceEquals(object a, object b) + { + throw new InvalidOperationException("StringAssert.ReferenceEquals should not be used for Assertions"); + } + + #endregion + + #region Contains + + /// + /// Asserts that a string is found within another string. + /// + /// The expected string + /// The string to be examined + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void Contains(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Does.Contain(expected), message, args); + } + + /// + /// Asserts that a string is found within another string. + /// + /// The expected string + /// The string to be examined + static public void Contains(string expected, string actual) + { + Contains(expected, actual, string.Empty, null); + } + + #endregion + + #region DoesNotContain + + /// + /// Asserts that a string is not found within another string. + /// + /// The expected string + /// The string to be examined + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void DoesNotContain(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Does.Not.Contain(expected), message, args ); + } + + /// + /// Asserts that a string is found within another string. + /// + /// The expected string + /// The string to be examined + static public void DoesNotContain(string expected, string actual) + { + DoesNotContain(expected, actual, string.Empty, null); + } + + #endregion + + #region StartsWith + + /// + /// Asserts that a string starts with another string. + /// + /// The expected string + /// The string to be examined + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void StartsWith(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Does.StartWith(expected), message, args); + } + + /// + /// Asserts that a string starts with another string. + /// + /// The expected string + /// The string to be examined + static public void StartsWith(string expected, string actual) + { + StartsWith(expected, actual, string.Empty, null); + } + + #endregion + + #region DoesNotStartWith + + /// + /// Asserts that a string does not start with another string. + /// + /// The expected string + /// The string to be examined + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void DoesNotStartWith(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Does.Not.StartWith(expected), message, args); + } + + /// + /// Asserts that a string does not start with another string. + /// + /// The expected string + /// The string to be examined + static public void DoesNotStartWith(string expected, string actual) + { + DoesNotStartWith(expected, actual, string.Empty, null); + } + + #endregion + + #region EndsWith + + /// + /// Asserts that a string ends with another string. + /// + /// The expected string + /// The string to be examined + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void EndsWith(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Does.EndWith(expected), message, args); + } + + /// + /// Asserts that a string ends with another string. + /// + /// The expected string + /// The string to be examined + static public void EndsWith(string expected, string actual) + { + EndsWith(expected, actual, string.Empty, null); + } + + #endregion + + #region DoesNotEndWith + + /// + /// Asserts that a string does not end with another string. + /// + /// The expected string + /// The string to be examined + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void DoesNotEndWith(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Does.Not.EndWith(expected), message, args); + } + + /// + /// Asserts that a string does not end with another string. + /// + /// The expected string + /// The string to be examined + static public void DoesNotEndWith(string expected, string actual) + { + DoesNotEndWith(expected, actual, string.Empty, null); + } + + #endregion + + #region AreEqualIgnoringCase + /// + /// Asserts that two strings are equal, without regard to case. + /// + /// The expected string + /// The actual string + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void AreEqualIgnoringCase(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Is.EqualTo(expected).IgnoreCase, message, args); + } + + /// + /// Asserts that two strings are equal, without regard to case. + /// + /// The expected string + /// The actual string + static public void AreEqualIgnoringCase(string expected, string actual) + { + AreEqualIgnoringCase(expected, actual, string.Empty, null); + } + #endregion + + #region AreNotEqualIgnoringCase + /// + /// Asserts that two strings are not equal, without regard to case. + /// + /// The expected string + /// The actual string + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void AreNotEqualIgnoringCase(string expected, string actual, string message, params object[] args) + { + Assert.That(actual, Is.Not.EqualTo(expected).IgnoreCase, message, args); + } + + /// + /// Asserts that two strings are not equal, without regard to case. + /// + /// The expected string + /// The actual string + static public void AreNotEqualIgnoringCase(string expected, string actual) + { + AreNotEqualIgnoringCase(expected, actual, string.Empty, null); + } + #endregion + + #region IsMatch + /// + /// Asserts that a string matches an expected regular expression pattern. + /// + /// The regex pattern to be matched + /// The actual string + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void IsMatch(string pattern, string actual, string message, params object[] args) + { + Assert.That(actual, Does.Match(pattern), message, args); + } + + /// + /// Asserts that a string matches an expected regular expression pattern. + /// + /// The regex pattern to be matched + /// The actual string + static public void IsMatch(string pattern, string actual) + { + IsMatch(pattern, actual, string.Empty, null); + } + #endregion + + #region DoesNotMatch + /// + /// Asserts that a string does not match an expected regular expression pattern. + /// + /// The regex pattern to be used + /// The actual string + /// The message to display in case of failure + /// Arguments used in formatting the message + static public void DoesNotMatch(string pattern, string actual, string message, params object[] args) + { + Assert.That(actual, Does.Not.Match(pattern), message, args); + } + + /// + /// Asserts that a string does not match an expected regular expression pattern. + /// + /// The regex pattern to be used + /// The actual string + static public void DoesNotMatch(string pattern, string actual) + { + DoesNotMatch(pattern, actual, string.Empty, null); + } + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/TestCaseData.cs b/test/NUnitLite/NUnitFramework/framework/TestCaseData.cs new file mode 100644 index 000000000..ae4b3a88c --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/TestCaseData.cs @@ -0,0 +1,196 @@ +// *********************************************************************** +// Copyright (c) 2008 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnit.Framework +{ + /// + /// The TestCaseData class represents a set of arguments + /// and other parameter info to be used for a parameterized + /// test case. It is derived from TestCaseParameters and adds a + /// fluent syntax for use in initializing the test case. + /// + public class TestCaseData : TestCaseParameters + { + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The arguments. + public TestCaseData(params object[] args) + : base(args == null ? new object[] { null } : args) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The argument. + public TestCaseData(object arg) + : base(new object[] { arg }) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The first argument. + /// The second argument. + public TestCaseData(object arg1, object arg2) + : base(new object[] { arg1, arg2 }) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The first argument. + /// The second argument. + /// The third argument. + public TestCaseData(object arg1, object arg2, object arg3) + : base( new object[] { arg1, arg2, arg3 }) + { + } + + #endregion + + #region Fluent Instance Modifiers + + /// + /// Sets the expected result for the test + /// + /// The expected result + /// A modified TestCaseData + public TestCaseData Returns(object result) + { + this.ExpectedResult = result; + return this; + } + + /// + /// Sets the name of the test case + /// + /// The modified TestCaseData instance + public TestCaseData SetName(string name) + { + this.TestName = name; + return this; + } + + /// + /// Sets the description for the test case + /// being constructed. + /// + /// The description. + /// The modified TestCaseData instance. + public TestCaseData SetDescription(string description) + { + this.Properties.Set(PropertyNames.Description, description); + return this; + } + + /// + /// Applies a category to the test + /// + /// + /// + public TestCaseData SetCategory(string category) + { + this.Properties.Add(PropertyNames.Category, category); + return this; + } + + /// + /// Applies a named property to the test + /// + /// + /// + /// + public TestCaseData SetProperty(string propName, string propValue) + { + this.Properties.Add(propName, propValue); + return this; + } + + /// + /// Applies a named property to the test + /// + /// + /// + /// + public TestCaseData SetProperty(string propName, int propValue) + { + this.Properties.Add(propName, propValue); + return this; + } + + /// + /// Applies a named property to the test + /// + /// + /// + /// + public TestCaseData SetProperty(string propName, double propValue) + { + this.Properties.Add(propName, propValue); + return this; + } + + /// + /// Marks the test case as explicit. + /// + public TestCaseData Explicit() { + this.RunState = RunState.Explicit; + return this; + } + + /// + /// Marks the test case as explicit, specifying the reason. + /// + public TestCaseData Explicit(string reason) + { + this.RunState = RunState.Explicit; + this.Properties.Set(PropertyNames.SkipReason, reason); + return this; + } + + /// + /// Ignores this TestCase, specifying the reason. + /// + /// The reason. + /// + public TestCaseData Ignore(string reason) + { + this.RunState = RunState.Ignored; + this.Properties.Set(PropertyNames.SkipReason, reason); + return this; + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/TestContext.cs b/test/NUnitLite/NUnitFramework/framework/TestContext.cs new file mode 100644 index 000000000..ac41c0779 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/TestContext.cs @@ -0,0 +1,470 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using NUnit.Framework.Constraints; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Execution; + +namespace NUnit.Framework +{ + /// + /// Provide the context information of the current test. + /// This is an adapter for the internal ExecutionContext + /// class, hiding the internals from the user test. + /// + public class TestContext + { + private readonly TestExecutionContext _testExecutionContext; + private TestAdapter _test; + private ResultAdapter _result; + + #region Constructor + + /// + /// Construct a TestContext for an ExecutionContext + /// + /// The ExecutionContext to adapt + public TestContext(TestExecutionContext testExecutionContext) + { + _testExecutionContext = testExecutionContext; + } + + #endregion + + #region Properties + + /// + /// Get the current test context. This is created + /// as needed. The user may save the context for + /// use within a test, but it should not be used + /// outside the test for which it is created. + /// + public static TestContext CurrentContext + { + get { return new TestContext(TestExecutionContext.CurrentContext); } + } + + /// + /// Gets a TextWriter that will send output to the current test result. + /// + public static TextWriter Out + { + get { return TestExecutionContext.CurrentContext.OutWriter; } + } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// Gets a TextWriter that will send output directly to Console.Error + /// + public static TextWriter Error = new EventListenerTextWriter("Error", Console.Error); + + /// + /// Gets a TextWriter for use in displaying immediate progress messages + /// + public static readonly TextWriter Progress = new EventListenerTextWriter("Progress", Console.Error); +#endif + + /// + /// TestParameters object holds parameters for the test run, if any are specified + /// + public static readonly TestParameters Parameters = new TestParameters(); + + /// + /// Get a representation of the current test. + /// + public TestAdapter Test + { + get { return _test ?? (_test = new TestAdapter(_testExecutionContext.CurrentTest)); } + } + + /// + /// Gets a Representation of the TestResult for the current test. + /// + public ResultAdapter Result + { + get { return _result ?? (_result = new ResultAdapter(_testExecutionContext.CurrentResult)); } + } + + /// + /// Gets the unique name of the Worker that is executing this test. + /// + public string WorkerId + { + get { return _testExecutionContext.WorkerId; } + } + +#if !SILVERLIGHT && !PORTABLE + /// + /// Gets the directory containing the current test assembly. + /// + public string TestDirectory + { + get + { + Test test = _testExecutionContext.CurrentTest; + if (test != null) + return AssemblyHelper.GetDirectoryName(test.TypeInfo.Assembly); + + // Test is null, we may be loading tests rather than executing. + // Assume that calling assembly is the test assembly. + return AssemblyHelper.GetDirectoryName(Assembly.GetCallingAssembly()); + } + } +#endif + + /// + /// Gets the directory to be used for outputting files created + /// by this test run. + /// + public string WorkDirectory + { + get { return _testExecutionContext.WorkDirectory; } + } + + /// + /// Gets the random generator. + /// + /// + /// The random generator. + /// + public Randomizer Random + { + get { return _testExecutionContext.RandomGenerator; } + } + + #endregion + + #region Static Methods + + /// Write the string representation of a boolean value to the current result + public static void Write(bool value) { Out.Write(value); } + + /// Write a char to the current result + public static void Write(char value) { Out.Write(value); } + + /// Write a char array to the current result + public static void Write(char[] value) { Out.Write(value); } + + /// Write the string representation of a double to the current result + public static void Write(double value) { Out.Write(value); } + + /// Write the string representation of an Int32 value to the current result + public static void Write(Int32 value) { Out.Write(value); } + + /// Write the string representation of an Int64 value to the current result + public static void Write(Int64 value) { Out.Write(value); } + + /// Write the string representation of a decimal value to the current result + public static void Write(decimal value) { Out.Write(value); } + + /// Write the string representation of an object to the current result + public static void Write(object value) { Out.Write(value); } + + /// Write the string representation of a Single value to the current result + public static void Write(Single value) { Out.Write(value); } + + /// Write a string to the current result + public static void Write(string value) { Out.Write(value); } + + /// Write the string representation of a UInt32 value to the current result + [CLSCompliant(false)] + public static void Write(UInt32 value) { Out.Write(value); } + + /// Write the string representation of a UInt64 value to the current result + [CLSCompliant(false)] + public static void Write(UInt64 value) { Out.Write(value); } + + /// Write a formatted string to the current result + public static void Write(string format, object arg1) { Out.Write(format, arg1); } + + /// Write a formatted string to the current result + public static void Write(string format, object arg1, object arg2) { Out.Write(format, arg1, arg2); } + + /// Write a formatted string to the current result + public static void Write(string format, object arg1, object arg2, object arg3) { Out.Write(format, arg1, arg2, arg3); } + + /// Write a formatted string to the current result + public static void Write(string format, params object[] args) { Out.Write(format, args); } + + /// Write a line terminator to the current result + public static void WriteLine() { Out.WriteLine(); } + + /// Write the string representation of a boolean value to the current result followed by a line terminator + public static void WriteLine(bool value) { Out.WriteLine(value); } + + /// Write a char to the current result followed by a line terminator + public static void WriteLine(char value) { Out.WriteLine(value); } + + /// Write a char array to the current result followed by a line terminator + public static void WriteLine(char[] value) { Out.WriteLine(value); } + + /// Write the string representation of a double to the current result followed by a line terminator + public static void WriteLine(double value) { Out.WriteLine(value); } + + /// Write the string representation of an Int32 value to the current result followed by a line terminator + public static void WriteLine(Int32 value) { Out.WriteLine(value); } + + /// Write the string representation of an Int64 value to the current result followed by a line terminator + public static void WriteLine(Int64 value) { Out.WriteLine(value); } + + /// Write the string representation of a decimal value to the current result followed by a line terminator + public static void WriteLine(decimal value) { Out.WriteLine(value); } + + /// Write the string representation of an object to the current result followed by a line terminator + public static void WriteLine(object value) { Out.WriteLine(value); } + + /// Write the string representation of a Single value to the current result followed by a line terminator + public static void WriteLine(Single value) { Out.WriteLine(value); } + + /// Write a string to the current result followed by a line terminator + public static void WriteLine(string value) { Out.WriteLine(value); } + + /// Write the string representation of a UInt32 value to the current result followed by a line terminator + [CLSCompliant(false)] + public static void WriteLine(UInt32 value) { Out.WriteLine(value); } + + /// Write the string representation of a UInt64 value to the current result followed by a line terminator + [CLSCompliant(false)] + public static void WriteLine(UInt64 value) { Out.WriteLine(value); } + + /// Write a formatted string to the current result followed by a line terminator + public static void WriteLine(string format, object arg1) { Out.WriteLine(format, arg1); } + + /// Write a formatted string to the current result followed by a line terminator + public static void WriteLine(string format, object arg1, object arg2) { Out.WriteLine(format, arg1, arg2); } + + /// Write a formatted string to the current result followed by a line terminator + public static void WriteLine(string format, object arg1, object arg2, object arg3) { Out.WriteLine(format, arg1, arg2, arg3); } + + /// Write a formatted string to the current result followed by a line terminator + public static void WriteLine(string format, params object[] args) { Out.WriteLine(format, args); } + + /// + /// This method adds the a new ValueFormatterFactory to the + /// chain of responsibility used for fomatting values in messages. + /// The scope of the change is the current TestContext. + /// + /// The factory delegate + public static void AddFormatter(ValueFormatterFactory formatterFactory) + { + TestExecutionContext.CurrentContext.AddFormatter(formatterFactory); + } + + /// + /// This method provides a simplified way to add a ValueFormatter + /// delegate to the chain of responsibility, creating the factory + /// delegate internally. It is useful when the Type of the object + /// is the only criterion for selection of the formatter, since + /// it can be used without getting involved with a compould function. + /// + /// The type supported by this formatter + /// The ValueFormatter delegate + public static void AddFormatter(ValueFormatter formatter) + { + AddFormatter(next => val => (val is TSUPPORTED) ? formatter(val) : next(val)); + } + + #endregion + + #region Nested TestAdapter Class + + /// + /// TestAdapter adapts a Test for consumption by + /// the user test code. + /// + public class TestAdapter + { + private readonly Test _test; + + #region Constructor + + /// + /// Construct a TestAdapter for a Test + /// + /// The Test to be adapted + public TestAdapter(Test test) + { + _test = test; + } + + #endregion + + #region Properties + + /// + /// Gets the unique Id of a test + /// + public String ID + { + get { return _test.Id; } + } + + /// + /// The name of the test, which may or may not be + /// the same as the method name. + /// + public string Name + { + get { return _test.Name; } + } + + /// + /// The name of the method representing the test. + /// + public string MethodName + { + get + { + return _test is TestMethod + ? _test.Method.Name + : null; + } + } + + /// + /// The FullName of the test + /// + public string FullName + { + get { return _test.FullName; } + } + + /// + /// The ClassName of the test + /// + public string ClassName + { + get { return _test.ClassName; } + } + + /// + /// The properties of the test. + /// + public IPropertyBag Properties + { + get { return _test.Properties; } + } + + #endregion + } + + #endregion + + #region Nested ResultAdapter Class + + /// + /// ResultAdapter adapts a TestResult for consumption by + /// the user test code. + /// + public class ResultAdapter + { + private readonly TestResult _result; + + #region Constructor + + /// + /// Construct a ResultAdapter for a TestResult + /// + /// The TestResult to be adapted + public ResultAdapter(TestResult result) + { + _result = result; + } + + #endregion + + #region Properties + + /// + /// Gets a ResultState representing the outcome of the test. + /// + public ResultState Outcome + { + get { return _result.ResultState; } + } + + /// + /// Gets the message associated with a test + /// failure or with not running the test + /// + public string Message + { + get { return _result.Message; } + } + + /// + /// Gets any stacktrace associated with an + /// error or failure. + /// + public virtual string StackTrace + { + get { return _result.StackTrace; } + } + + /// + /// Gets the number of test cases that failed + /// when running the test and all its children. + /// + public int FailCount + { + get { return _result.FailCount; } + } + + /// + /// Gets the number of test cases that passed + /// when running the test and all its children. + /// + public int PassCount + { + get { return _result.PassCount; } + } + + /// + /// Gets the number of test cases that were skipped + /// when running the test and all its children. + /// + public int SkipCount + { + get { return _result.SkipCount; } + } + + /// + /// Gets the number of test cases that were inconclusive + /// when running the test and all its children. + /// + public int InconclusiveCount + { + get { return _result.InconclusiveCount; } + } + + #endregion + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/TestFixtureData.cs b/test/NUnitLite/NUnitFramework/framework/TestFixtureData.cs new file mode 100644 index 000000000..b45e01e4c --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/TestFixtureData.cs @@ -0,0 +1,116 @@ +// *********************************************************************** +// Copyright (c) 2008 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnit.Framework +{ + /// + /// The TestFixtureData class represents a set of arguments + /// and other parameter info to be used for a parameterized + /// fixture. It is derived from TestFixtureParameters and adds a + /// fluent syntax for use in initializing the fixture. + /// + public class TestFixtureData : TestFixtureParameters + { + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The arguments. + public TestFixtureData(params object[] args) + : base(args == null ? new object[] { null } : args) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The argument. + public TestFixtureData(object arg) + : base(new object[] { arg }) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The first argument. + /// The second argument. + public TestFixtureData(object arg1, object arg2) + : base(new object[] { arg1, arg2 }) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The first argument. + /// The second argument. + /// The third argument. + public TestFixtureData(object arg1, object arg2, object arg3) + : base( new object[] { arg1, arg2, arg3 }) + { + } + + #endregion + + #region Fluent Instance Modifiers + + /// + /// Marks the test fixture as explicit. + /// + public TestFixtureData Explicit() { + this.RunState = RunState.Explicit; + return this; + } + + /// + /// Marks the test fixture as explicit, specifying the reason. + /// + public TestFixtureData Explicit(string reason) + { + this.RunState = RunState.Explicit; + this.Properties.Set(PropertyNames.SkipReason, reason); + return this; + } + + /// + /// Ignores this TestFixture, specifying the reason. + /// + /// The reason. + /// + public TestFixtureData Ignore(string reason) + { + this.RunState = RunState.Ignored; + this.Properties.Set(PropertyNames.SkipReason, reason); + return this; + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/framework/TestParameters.cs b/test/NUnitLite/NUnitFramework/framework/TestParameters.cs new file mode 100644 index 000000000..376fe8383 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/TestParameters.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace NUnit.Framework +{ + /// + /// TestParameters class holds any named parameters supplied to the test run + /// + public class TestParameters + { + private static readonly IFormatProvider MODIFIED_INVARIANT_CULTURE = CreateModifiedInvariantCulture(); + + private readonly Dictionary _parameters = new Dictionary(); + + /// + /// Gets the number of test parameters + /// + public int Count + { + get { return _parameters.Count; } + } + + /// + /// Gets a collection of the test parameter names + /// + public ICollection Names + { + get { return _parameters.Keys; } + } + + /// + /// Gets a flag indicating whether a parameter with the specified name exists.N + /// + /// Name of the parameter + /// True if it exists, otherwise false + public bool Exists(string name) + { + return _parameters.ContainsKey(name); + } + + /// + /// Indexer provides access to the internal dictionary + /// + /// Name of the parameter + /// Value of the parameter or null if not present + public string this[string name] + { + get { return Get(name); } + } + + /// + /// Get method is a simple alternative to the indexer + /// + /// Name of the paramter + /// Value of the parameter or null if not present + public string Get(string name) + { + return Exists(name) ? _parameters[name] : null; + } + + /// + /// Get the value of a parameter or a default string + /// + /// Name of the parameter + /// Default value of the parameter + /// Value of the parameter or default value if not present + public string Get(string name, string defaultValue) + { + return Get(name) ?? defaultValue; + } + + /// + /// Get the value of a parameter or return a default + /// + /// The return Type + /// Name of the parameter + /// Default value of the parameter + /// Value of the parameter or default value if not present + public T Get(string name, T defaultValue) + { + string val = Get(name); + return val != null ? (T)Convert.ChangeType(val, typeof(T), MODIFIED_INVARIANT_CULTURE) : defaultValue; + } + + /// + /// Adds a parameter to the list + /// + /// Name of the parameter + /// Value of the parameter + internal void Add(string name, string value) + { + _parameters[name] = value; + } + + private static IFormatProvider CreateModifiedInvariantCulture() + { + var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + + // Remove comma (,) as group separator since it may confuse developers in cultures + // where comma is a decimal separator + culture.NumberFormat.CurrencyGroupSeparator = string.Empty; + culture.NumberFormat.NumberGroupSeparator = string.Empty; + culture.NumberFormat.PercentGroupSeparator = string.Empty; + + return culture; + } + } +} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Throws.cs b/test/NUnitLite/NUnitFramework/framework/Throws.cs similarity index 85% rename from test/NUnitLite/src/framework/Throws.cs rename to test/NUnitLite/NUnitFramework/framework/Throws.cs index eee90b3ad..20c2b153b 100644 --- a/test/NUnitLite/src/framework/Throws.cs +++ b/test/NUnitLite/NUnitFramework/framework/Throws.cs @@ -72,7 +72,7 @@ public static ExactTypeConstraint TargetInvocationException #region ArgumentException /// - /// Creates a constraint specifying an expected TargetInvocationException + /// Creates a constraint specifying an expected ArgumentException /// public static ExactTypeConstraint ArgumentException { @@ -81,10 +81,22 @@ public static ExactTypeConstraint ArgumentException #endregion + #region ArgumentNullException + + /// + /// Creates a constraint specifying an expected ArgumentNUllException + /// + public static ExactTypeConstraint ArgumentNullException + { + get { return TypeOf(typeof (System.ArgumentNullException)); } + } + + #endregion + #region InvalidOperationException /// - /// Creates a constraint specifying an expected TargetInvocationException + /// Creates a constraint specifying an expected InvalidOperationException /// public static ExactTypeConstraint InvalidOperationException { @@ -115,15 +127,13 @@ public static ExactTypeConstraint TypeOf(Type expectedType) return Exception.TypeOf(expectedType); } -#if CLR_2_0 || CLR_4_0 /// /// Creates a constraint specifying the exact type of exception expected /// - public static ExactTypeConstraint TypeOf() + public static ExactTypeConstraint TypeOf() { - return TypeOf(typeof(T)); + return TypeOf(typeof(TExpected)); } -#endif #endregion @@ -137,15 +147,13 @@ public static InstanceOfTypeConstraint InstanceOf(Type expectedType) return Exception.InstanceOf(expectedType); } -#if CLR_2_0 || CLR_4_0 /// /// Creates a constraint specifying the type of exception expected /// - public static InstanceOfTypeConstraint InstanceOf() + public static InstanceOfTypeConstraint InstanceOf() { - return InstanceOf(typeof(T)); + return InstanceOf(typeof(TExpected)); } -#endif #endregion diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-2.0.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-2.0.csproj new file mode 100644 index 000000000..b86aeca88 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-2.0.csproj @@ -0,0 +1,440 @@ + + + + Debug + AnyCPU + {12B66B03-90F1-4992-BD33-BDF3C69AE49E} + Library + Properties + NUnit.Framework + nunit.framework + v2.0 + 512 + true + ..\..\nunit.snk + + + 3.5 + + obj\$(Configuration)\net-2.0\ + + + true + full + false + ..\..\..\bin\Debug\net-2.0\ + TRACE;DEBUG;NUNIT_FRAMEWORK;NET_2_0;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + true + + + pdbonly + true + ..\..\..\bin\Release\net-2.0\ + TRACE;NUNIT_FRAMEWORK;NET_2_0;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + true + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + Code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ..\..\..\packages\NUnit.System.Linq.0.6.0\lib\net20\NUnit.System.Linq.dll + True + + + + + + + + + + + + + + nunit.snk + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-3.5.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-3.5.csproj new file mode 100644 index 000000000..fdbfd9ca7 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-3.5.csproj @@ -0,0 +1,433 @@ + + + + Debug + AnyCPU + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3} + Library + Properties + NUnit.Framework + nunit.framework + v3.5 + 512 + true + ..\..\nunit.snk + + + 3.5 + + obj\$(Configuration)\net-3.5\ + + + true + full + false + ..\..\..\bin\Debug\net-3.5\ + TRACE;DEBUG;NUNIT_FRAMEWORK;NET_3_5;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + true + + + pdbonly + true + ..\..\..\bin\Release\net-3.5\ + TRACE;NUNIT_FRAMEWORK;NET_3_5;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + true + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + + Code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + nunit.snk + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-4.0.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-4.0.csproj new file mode 100644 index 000000000..901cd2916 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-4.0.csproj @@ -0,0 +1,425 @@ + + + + Debug + AnyCPU + {6A281C98-B74D-403B-8536-966871B992E3} + Library + Properties + NUnit.Framework + nunit.framework + 512 + true + ..\..\nunit.snk + + + 3.5 + + obj\$(Configuration)\net-4.0\ + + + true + full + false + ..\..\..\bin\Debug\net-4.0\ + TRACE;DEBUG;NUNIT_FRAMEWORK;NET_4_0;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + true + + + pdbonly + true + ..\..\..\bin\Release\net-4.0\ + TRACE;NUNIT_FRAMEWORK;NET_4_0;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + true + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + Assert.cs + + + Assert.cs + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + nunit.snk + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-4.5.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-4.5.csproj new file mode 100644 index 000000000..dc78ff096 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-4.5.csproj @@ -0,0 +1,429 @@ + + + + Debug + AnyCPU + {D209C368-1277-4EA6-A887-AA6EBA51AB99} + Library + Properties + NUnit.Framework + nunit.framework + 512 + true + ..\..\nunit.snk + + + 3.5 + obj\$(Configuration)\net-4.5\ + + v4.5 + + + + true + full + false + ..\..\..\bin\Debug\net-4.5\ + TRACE;DEBUG;NUNIT_FRAMEWORK;NET_4_5;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + false + true + + + pdbonly + true + ..\..\..\bin\Release\net-4.5\ + TRACE;NUNIT_FRAMEWORK;NET_4_5;PARALLEL + prompt + 4 + $(OutputPath)\nunit.framework.xml + false + true + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + Assert.cs + + + Assert.cs + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + nunit.snk + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-netcf-3.5.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-netcf-3.5.csproj new file mode 100644 index 000000000..52969e18a --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-netcf-3.5.csproj @@ -0,0 +1,457 @@ + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {B41DB8FB-0D2F-45CE-9345-AF469FC05EE8} + Library + Properties + NUnit.Framework + nunit.framework + {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + WindowsCE + E2BECB1F-8C8C-41ba-B736-9BE7D946A398 + 5.0 + nunitlite_netcf_3._5 + v3.5 + Windows CE + + + obj\$(Configuration)\netcf-3.5\ + + + true + full + false + ..\..\..\bin\Debug\netcf-3.5\ + TRACE;DEBUG;NUNIT_FRAMEWORK;WindowsCE;NETCF;NETCF_3_5;PARALLEL + true + true + prompt + 512 + 4 + Off + ..\..\..\bin\Debug\netcf-3.5\nunit.framework.xml + true + + + pdbonly + true + ..\..\..\bin\Release\netcf-3.5\ + TRACE;NUNIT_FRAMEWORK;WindowsCE;NETCF;NETCF_3_5;PARALLEL + true + true + prompt + 512 + 4 + Off + ..\..\..\bin\Release\netcf-3.5\nunit.framework.xml + true + + + true + + + ..\..\nunit.snk + + + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + Code + + + Assert.cs + + + Assert.cs + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + nunit.snk + + + + + + + + + + + + + + + diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-portable.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-portable.csproj new file mode 100644 index 000000000..e9d0ee2c8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-portable.csproj @@ -0,0 +1,427 @@ + + + + + Debug + AnyCPU + {D6FBBB3A-F6B8-45BB-B657-A7226AB96624} + Library + Properties + NUnit.Framework + nunit.framework + en-US + 512 + {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Profile259 + v4.5 + obj\$(Configuration)\portable\ + + + true + full + false + ..\..\..\bin\Debug\portable\ + TRACE;DEBUG;NUNIT_FRAMEWORK;PORTABLE + prompt + 4 + true + ..\..\..\bin\Debug\portable\nunit.framework.xml + + + pdbonly + true + ..\..\..\bin\Release\portable\ + TRACE;NUNIT_FRAMEWORK;PORTABLE + prompt + 4 + true + ..\..\..\bin\Release\portable\nunit.framework.xml + + + true + + + ..\..\nunit.snk + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + Assert.cs + + + Assert.cs + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + nunit.snk + + + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/framework/nunit.framework-sl-5.0.csproj b/test/NUnitLite/NUnitFramework/framework/nunit.framework-sl-5.0.csproj new file mode 100644 index 000000000..5466beb9f --- /dev/null +++ b/test/NUnitLite/NUnitFramework/framework/nunit.framework-sl-5.0.csproj @@ -0,0 +1,454 @@ + + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {3DEB15F9-E7DA-403F-B6D3-A8499310397F} + {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + NUnit.Framework + nunit.framework + Silverlight + v5.0 + $(TargetFrameworkVersion) + false + true + true + obj\$(Configuration)\sl-5.0\ + + + + v3.5 + + + true + full + false + ..\..\..\bin\Debug\sl-5.0\ + TRACE;DEBUG;NUNIT_FRAMEWORK;SILVERLIGHT;SL_5_0 + true + true + prompt + 4 + true + ..\..\..\bin\Debug\sl-5.0\nunit.framework.xml + + + full + true + ..\..\..\bin\Release\sl-5.0\ + TRACE;NUNIT_FRAMEWORK;SILVERLIGHT;SL_5_0 + true + true + prompt + 4 + true + true + ..\..\..\bin\Release\sl-5.0\nunit.framework.xml + + + true + + + ..\..\nunit.snk + + + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + Assert.cs + + + Assert.cs + + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + Assert.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + nunit.snk + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/AutoRun.cs b/test/NUnitLite/NUnitFramework/nunitlite/AutoRun.cs new file mode 100644 index 000000000..24fa0ea25 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/AutoRun.cs @@ -0,0 +1,101 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if !SILVERLIGHT +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using NUnit.Common; +using NUnit.Framework.Internal; + +namespace NUnitLite +{ + /// + /// The AutoRun class is used by executable test + /// assemblies to control their own execution. + /// + /// Call it from your executable test like this: + /// new AutoRun().Execute(args); + /// The arguments can be those passed into your exe + /// or constructed for the purpose in your code. + /// + /// If the tests are in a dll, you can write a stub + /// executable that runs them like this: + /// new Autorun().Execute(testAssembly, args); + /// + /// When running tests compiled against the portable + /// framework, the methods above are not available. + /// Run your tests like this: + /// new AutoRun().Execute(testAssembly, args, output, input); + /// Where output is an ExtendedTextWriter (normally a + /// ColorConsoleWriter) and input is usually Console.In + /// and is used by the --wait option. + /// + public class AutoRun + { + private Assembly _testAssembly; + + /// + /// Constructor for use where GetCallingAssembly is not + /// available, requiring the assembly to be passed. + /// + /// The test assembly + public AutoRun(Assembly testAssembly) + { + _testAssembly = testAssembly; + } + +#if !PORTABLE + /// + /// Default Constructor, only used where GetCallingAssembly is available + /// + public AutoRun() : this(Assembly.GetCallingAssembly()) { } + + /// + /// Execute the tests in the assembly, passing in + /// a list of arguments. + /// + /// arguments for NUnitLite to use + public int Execute(string[] args) + { + return new TextRunner(_testAssembly).Execute(args); + } +#endif + + /// + /// Execute the tests in the assembly, passing in + /// a list of arguments, a test assembly a writer + /// and a reader. For use in builds for runtimes + /// that don't support Assembly.GetCallingAssembly(). + /// + /// Arguments passed to NUnitLite + /// An ExtendedTextWriter to which output will be written + /// A TextReader used when waiting for input + public int Execute(string[] args, ExtendedTextWriter writer, TextReader reader) + { + return new TextRunner(_testAssembly).Execute(writer, reader, args); + } + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/nunitlite/ColorConsole.cs b/test/NUnitLite/NUnitFramework/nunitlite/ColorConsole.cs new file mode 100644 index 000000000..3eb751ab8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/ColorConsole.cs @@ -0,0 +1,183 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; + +namespace NUnit.Common +{ + /// + /// Sets the console color in the constructor and resets it in the dispose + /// + public class ColorConsole : IDisposable + { +#if !SILVERLIGHT && !NETCF + private ConsoleColor _originalColor; +#endif + + /// + /// Initializes a new instance of the class. + /// + /// The color style to use. + public ColorConsole(ColorStyle style) + { +#if !SILVERLIGHT && !NETCF + _originalColor = Console.ForegroundColor; + Console.ForegroundColor = GetColor(style); +#endif + } + +#if !SILVERLIGHT && !NETCF + /// + /// By using styles, we can keep everything consistent + /// + /// + /// + public static ConsoleColor GetColor(ColorStyle style) + { + ConsoleColor color = GetColorForStyle(style); + ConsoleColor bg = Console.BackgroundColor; + + if (color == bg || color == ConsoleColor.Red && bg == ConsoleColor.Magenta) + return bg == ConsoleColor.Black + ? ConsoleColor.White + : ConsoleColor.Black; + + return color; + } + + private static ConsoleColor GetColorForStyle(ColorStyle style) + { + switch (Console.BackgroundColor) + { + case ConsoleColor.White: + switch (style) + { + case ColorStyle.Header: + return ConsoleColor.Black; + case ColorStyle.SubHeader: + return ConsoleColor.Black; + case ColorStyle.SectionHeader: + return ConsoleColor.Blue; + case ColorStyle.Label: + return ConsoleColor.Black; + case ColorStyle.Value: + return ConsoleColor.Blue; + case ColorStyle.Pass: + return ConsoleColor.Green; + case ColorStyle.Failure: + return ConsoleColor.Red; + case ColorStyle.Warning: + return ConsoleColor.Black; + case ColorStyle.Error: + return ConsoleColor.Red; + case ColorStyle.Output: + return ConsoleColor.Black; + case ColorStyle.Help: + return ConsoleColor.Black; + case ColorStyle.Default: + default: + return ConsoleColor.Black; + } + + case ConsoleColor.Cyan: + case ConsoleColor.Green: + case ConsoleColor.Red: + case ConsoleColor.Magenta: + case ConsoleColor.Yellow: + switch (style) + { + case ColorStyle.Header: + return ConsoleColor.Black; + case ColorStyle.SubHeader: + return ConsoleColor.Black; + case ColorStyle.SectionHeader: + return ConsoleColor.Blue; + case ColorStyle.Label: + return ConsoleColor.Black; + case ColorStyle.Value: + return ConsoleColor.Black; + case ColorStyle.Pass: + return ConsoleColor.Black; + case ColorStyle.Failure: + return ConsoleColor.Red; + case ColorStyle.Warning: + return ConsoleColor.Yellow; + case ColorStyle.Error: + return ConsoleColor.Red; + case ColorStyle.Output: + return ConsoleColor.Black; + case ColorStyle.Help: + return ConsoleColor.Black; + case ColorStyle.Default: + default: + return ConsoleColor.Black; + } + + default: + switch (style) + { + case ColorStyle.Header: + return ConsoleColor.White; + case ColorStyle.SubHeader: + return ConsoleColor.Gray; + case ColorStyle.SectionHeader: + return ConsoleColor.Cyan; + case ColorStyle.Label: + return ConsoleColor.Green; + case ColorStyle.Value: + return ConsoleColor.White; + case ColorStyle.Pass: + return ConsoleColor.Green; + case ColorStyle.Failure: + return ConsoleColor.Red; + case ColorStyle.Warning: + return ConsoleColor.Yellow; + case ColorStyle.Error: + return ConsoleColor.Red; + case ColorStyle.Output: + return ConsoleColor.Gray; + case ColorStyle.Help: + return ConsoleColor.Green; + case ColorStyle.Default: + default: + return ConsoleColor.Green; + } + } + } +#endif + + #region Implementation of IDisposable + + /// + /// If color is enabled, restores the console colors to their defaults + /// + public void Dispose() + { +#if !SILVERLIGHT && !NETCF + Console.ForegroundColor = _originalColor; +#endif + } + + #endregion + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/ColorConsoleWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/ColorConsoleWriter.cs new file mode 100644 index 000000000..2dee44d44 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/ColorConsoleWriter.cs @@ -0,0 +1,128 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.IO; +using System.Text; + +namespace NUnit.Common +{ + public class ColorConsoleWriter : ExtendedTextWrapper + { + public bool _colorEnabled; + + /// + /// Construct a ColorConsoleWriter. + /// + public ColorConsoleWriter() : this(true) { } + + /// + /// Construct a ColorConsoleWriter. + /// + /// Flag indicating whether color should be enabled + public ColorConsoleWriter(bool colorEnabled) + : base(Console.Out) + { + _colorEnabled = colorEnabled; + } + + #region Extended Methods + /// + /// Writes the value with the specified style. + /// + /// The style. + /// The value. + public override void Write(ColorStyle style, string value) + { + if (_colorEnabled) + using (new ColorConsole(style)) + { + Write(value); + } + else + Write(value); + } + + /// + /// Writes the value with the specified style. + /// + /// The style. + /// The value. + public override void WriteLine(ColorStyle style, string value) + { + if (_colorEnabled) + using (new ColorConsole(style)) + { + WriteLine(value); + } + else + WriteLine(value); + } + + /// + /// Writes the label and the option that goes with it. + /// + /// The label. + /// The option. + public override void WriteLabel(string label, object option) + { + WriteLabel(label, option, ColorStyle.Value); + } + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + public override void WriteLabelLine(string label, object option) + { + WriteLabelLine(label, option, ColorStyle.Value); + } + + /// + /// Writes the label and the option that goes with it and optionally writes a new line. + /// + /// The label. + /// The option. + /// The color to display the value with + public override void WriteLabel(string label, object option, ColorStyle valueStyle) + { + Write(ColorStyle.Label, label); + Write(valueStyle, option.ToString()); + } + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + /// The color to display the value with + public override void WriteLabelLine(string label, object option, ColorStyle valueStyle) + { + WriteLabel(label, option, valueStyle); + WriteLine(); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/ColorStyle.cs b/test/NUnitLite/NUnitFramework/nunitlite/ColorStyle.cs new file mode 100644 index 000000000..79c11da77 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/ColorStyle.cs @@ -0,0 +1,80 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Common +{ + /// + /// ColorStyle enumerates the various styles used in the console display + /// + public enum ColorStyle + { + /// + /// Color for headers + /// + Header, + /// + /// Color for sub-headers + /// + SubHeader, + /// + /// Color for each of the section headers + /// + SectionHeader, + /// + /// The default color for items that don't fit into the other categories + /// + Default, + /// + /// Test output + /// + Output, + /// + /// Color for help text + /// + Help, + /// + /// Color for labels + /// + Label, + /// + /// Color for values, usually go beside labels + /// + Value, + /// + /// Color for passed tests + /// + Pass, + /// + /// Color for failed tests + /// + Failure, + /// + /// Color for warnings, ignored or skipped tests + /// + Warning, + /// + /// Color for errors and exceptions + /// + Error + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/CommandLineOptions.cs b/test/NUnitLite/NUnitFramework/nunitlite/CommandLineOptions.cs new file mode 100644 index 000000000..d536a0fa6 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/CommandLineOptions.cs @@ -0,0 +1,434 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Security; + +using NUnit.Options; + +namespace NUnit.Common +{ + /// + /// CommandLineOptions is the base class the specific option classes + /// used for nunit3-console and nunitlite. It encapsulates all common + /// settings and features of both. This is done to ensure that common + /// features remain common and for the convenience of having the code + /// in a common location. The class inherits from the Mono + /// Options OptionSet class and provides a central location + /// for defining and parsing options. + /// + public class CommandLineOptions : OptionSet + { + private static readonly string DEFAULT_WORK_DIRECTORY = GetDefaultWorkDirectory(); + + private bool validated; +#if !PORTABLE + private bool noresult; +#endif + +#region Constructor + + internal CommandLineOptions(IDefaultOptionsProvider defaultOptionsProvider, params string[] args) + { + // Apply default options + if (defaultOptionsProvider == null) throw new ArgumentNullException("defaultOptionsProvider"); + + TeamCity = defaultOptionsProvider.TeamCity; + + ConfigureOptions(); + if (args != null) + Parse(args); + } + + public CommandLineOptions(params string[] args) + { + ConfigureOptions(); + if (args != null) + Parse(args); + } + + private static string GetDefaultWorkDirectory() + { + try + { + return GetDefaultWorkDirectoryCore(); + } + catch ( SecurityException ) + { + // For restricted Silverlight environment. + return null; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static string GetDefaultWorkDirectoryCore() + { +#if NETCF || PORTABLE + return @"\My Documents"; +#elif SILVERLIGHT + return Environment.GetFolderPath(Environment.SpecialFolder.Personal); +#else + return Environment.CurrentDirectory; +#endif + } + + #endregion + + #region Properties + + // Action to Perform + + public bool Explore { get; private set; } + + public bool ShowHelp { get; private set; } + + public bool ShowVersion { get; private set; } + + // Select tests + + private List inputFiles = new List(); + public IList InputFiles { get { return inputFiles; } } + + private List testList = new List(); + public IList TestList { get { return testList; } } + + public string TestParameters { get; private set; } + + public string WhereClause { get; private set; } + public bool WhereClauseSpecified { get { return WhereClause != null; } } + + private int defaultTimeout = -1; + public int DefaultTimeout { get { return defaultTimeout; } } + public bool DefaultTimeoutSpecified { get { return defaultTimeout >= 0; } } + + private int randomSeed = -1; + public int RandomSeed { get { return randomSeed; } } + public bool RandomSeedSpecified { get { return randomSeed >= 0; } } + + public string DefaultTestNamePattern { get; private set; } + + private int numWorkers = -1; + public int NumberOfTestWorkers { get { return numWorkers; } } + public bool NumberOfTestWorkersSpecified { get { return numWorkers >= 0; } } + + public bool StopOnError { get; private set; } + + public bool WaitBeforeExit { get; private set; } + + // Output Control + + public bool NoHeader { get; private set; } + + public bool NoColor { get; private set; } + + public bool Verbose { get; private set; } + + public bool TeamCity { get; private set; } + + public string OutFile { get; private set; } + public bool OutFileSpecified { get { return OutFile != null; } } + + public string ErrFile { get; private set; } + public bool ErrFileSpecified { get { return ErrFile != null; } } + + public string DisplayTestLabels { get; private set; } + +#if !PORTABLE + private string workDirectory = null; + public string WorkDirectory + { + get { return workDirectory ?? DEFAULT_WORK_DIRECTORY; } + } + public bool WorkDirectorySpecified { get { return workDirectory != null; } } +#endif + + public string InternalTraceLevel { get; private set; } + public bool InternalTraceLevelSpecified { get { return InternalTraceLevel != null; } } + + /// Indicates whether a full report should be displayed. + public bool Full { get; private set; } + +#if !PORTABLE + private List resultOutputSpecifications = new List(); + public IList ResultOutputSpecifications + { + get + { + if (noresult) + return new OutputSpecification[0]; + + if (resultOutputSpecifications.Count == 0) + resultOutputSpecifications.Add(new OutputSpecification("TestResult.xml")); + + return resultOutputSpecifications; + } + } + + private List exploreOutputSpecifications = new List(); + public IList ExploreOutputSpecifications { get { return exploreOutputSpecifications; } } +#endif + // Error Processing + + public List errorMessages = new List(); + public IList ErrorMessages { get { return errorMessages; } } + +#endregion + +#region Public Methods + + public bool Validate() + { + if (!validated) + { + CheckOptionCombinations(); + + validated = true; + } + + return ErrorMessages.Count == 0; + } + +#endregion + +#region Helper Methods + + protected virtual void CheckOptionCombinations() + { + + } + + /// + /// Case is ignored when val is compared to validValues. When a match is found, the + /// returned value will be in the canonical case from validValues. + /// + protected string RequiredValue(string val, string option, params string[] validValues) + { + if (string.IsNullOrEmpty(val)) + ErrorMessages.Add("Missing required value for option '" + option + "'."); + + bool isValid = true; + + if (validValues != null && validValues.Length > 0) + { + isValid = false; + + foreach (string valid in validValues) + if (string.Compare(valid, val, StringComparison.OrdinalIgnoreCase) == 0) + return valid; + + } + + if (!isValid) + ErrorMessages.Add(string.Format("The value '{0}' is not valid for option '{1}'.", val, option)); + + return val; + } + + protected int RequiredInt(string val, string option) + { + // We have to return something even though the value will + // be ignored if an error is reported. The -1 value seems + // like a safe bet in case it isn't ignored due to a bug. + int result = -1; + + if (string.IsNullOrEmpty(val)) + ErrorMessages.Add("Missing required value for option '" + option + "'."); + else + { + // NOTE: Don't replace this with TryParse or you'll break the CF build! + try + { + result = int.Parse(val); + } + catch (Exception) + { + ErrorMessages.Add("An int value was expected for option '{0}' but a value of '{1}' was used"); + } + } + + return result; + } + + private string ExpandToFullPath(string path) + { + if (path == null) return null; + +#if NETCF || PORTABLE + return Path.Combine(DEFAULT_WORK_DIRECTORY , path); +#else + return Path.GetFullPath(path); +#endif + } + + protected virtual void ConfigureOptions() + { + // NOTE: The order in which patterns are added + // determines the display order for the help. + + // Select Tests + this.Add("test=", "Comma-separated list of {NAMES} of tests to run or explore. This option may be repeated.", + v => ((List)TestList).AddRange(TestNameParser.Parse(RequiredValue(v, "--test")))); +#if !PORTABLE + this.Add("testlist=", "File {PATH} containing a list of tests to run, one per line. This option may be repeated.", + v => + { + string testListFile = RequiredValue(v, "--testlist"); + + var fullTestListPath = ExpandToFullPath(testListFile); + + if (!File.Exists(fullTestListPath)) + ErrorMessages.Add("Unable to locate file: " + testListFile); + else + { + try + { + using (var rdr = new StreamReader(fullTestListPath)) + { + while (!rdr.EndOfStream) + { + var line = rdr.ReadLine().Trim(); + + if (!string.IsNullOrEmpty(line) && line[0] != '#') + ((List)TestList).Add(line); + } + } + } + catch (IOException) + { + ErrorMessages.Add("Unable to read file: " + testListFile); + } + } + }); + +#endif + this.Add("where=", "Test selection {EXPRESSION} indicating what tests will be run. See description below.", + v => WhereClause = RequiredValue(v, "--where")); + + this.Add("params|p=", "Define a test parameter.", + v => + { + string parameters = RequiredValue( v, "--params"); + + foreach (string param in parameters.Split(new[] { ';' })) + { + if (!param.Contains("=")) + ErrorMessages.Add("Invalid format for test parameter. Use NAME=VALUE."); + } + + if (TestParameters == null) + TestParameters = parameters; + else + TestParameters += ";" + parameters; + }); + + this.Add("timeout=", "Set timeout for each test case in {MILLISECONDS}.", + v => defaultTimeout = RequiredInt(v, "--timeout")); + + this.Add("seed=", "Set the random {SEED} used to generate test cases.", + v => randomSeed = RequiredInt(v, "--seed")); +#if !PORTABLE + this.Add("workers=", "Specify the {NUMBER} of worker threads to be used in running tests. If not specified, defaults to 2 or the number of processors, whichever is greater.", + v => numWorkers = RequiredInt(v, "--workers")); +#endif + this.Add("stoponerror", "Stop run immediately upon any test failure or error.", + v => StopOnError = v != null); + + this.Add("wait", "Wait for input before closing console window.", + v => WaitBeforeExit = v != null); +#if !PORTABLE + // Output Control + this.Add("work=", "{PATH} of the directory to use for output files. If not specified, defaults to the current directory.", + v => workDirectory = RequiredValue(v, "--work")); + + this.Add("output|out=", "File {PATH} to contain text output from the tests.", + v => OutFile = RequiredValue(v, "--output")); + + this.Add("err=", "File {PATH} to contain error output from the tests.", + v => ErrFile = RequiredValue(v, "--err")); + + this.Add("full", "Prints full report of all test results.", + v => Full = v != null); + + this.Add("result=", "An output {SPEC} for saving the test results.\nThis option may be repeated.", + v => resultOutputSpecifications.Add(new OutputSpecification(RequiredValue(v, "--resultxml")))); + + this.Add("explore:", "Display or save test info rather than running tests. Optionally provide an output {SPEC} for saving the test info. This option may be repeated.", v => + { + Explore = true; + if (v != null) + ExploreOutputSpecifications.Add(new OutputSpecification(v)); + }); + + this.Add("noresult", "Don't save any test results.", + v => noresult = v != null); +#endif + this.Add("labels=", "Specify whether to write test case names to the output. Values: Off, On, All", + v => DisplayTestLabels = RequiredValue(v, "--labels", "Off", "On", "All")); + + this.Add("test-name-format=", "Non-standard naming pattern to use in generating test names.", + v => DefaultTestNamePattern = RequiredValue(v, "--test-name-format")); + +#if !NETCF + this.Add("teamcity", "Turns on use of TeamCity service messages.", + v => TeamCity = v != null); +#endif + +#if !PORTABLE + this.Add("trace=", "Set internal trace {LEVEL}.\nValues: Off, Error, Warning, Info, Verbose (Debug)", + v => InternalTraceLevel = RequiredValue(v, "--trace", "Off", "Error", "Warning", "Info", "Verbose", "Debug")); + + this.Add("noheader|noh", "Suppress display of program information at start of run.", + v => NoHeader = v != null); + + this.Add("nocolor|noc", "Displays console output without color.", + v => NoColor = v != null); +#endif + this.Add("verbose|v", "Display additional information as the test runs.", + v => Verbose = v != null); + + this.Add("help|h", "Display this message and exit.", + v => ShowHelp = v != null); + + this.Add("version|V", "Display the header and exit.", + v => ShowVersion = v != null); + + // Default + this.Add("<>", v => + { +#if PORTABLE + if (v.StartsWith("-") || v.StartsWith("/") && Environment.NewLine == "\r\n") +#else + if (v.StartsWith("-") || v.StartsWith("/") && Path.DirectorySeparatorChar != '/') +#endif + ErrorMessages.Add("Invalid argument: " + v); + else + InputFiles.Add(v); + }); + } + +#endregion + } +} diff --git a/test/NUnitLite/src/framework/Runner/DebugWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/DebugWriter.cs similarity index 99% rename from test/NUnitLite/src/framework/Runner/DebugWriter.cs rename to test/NUnitLite/NUnitFramework/nunitlite/DebugWriter.cs index b6d990983..ba3d4c488 100644 --- a/test/NUnitLite/src/framework/Runner/DebugWriter.cs +++ b/test/NUnitLite/NUnitFramework/nunitlite/DebugWriter.cs @@ -26,7 +26,7 @@ using System.Diagnostics; using System.IO; -namespace NUnitLite.Runner +namespace NUnitLite { /// /// DebugWriter is a TextWriter that sends it's @@ -110,4 +110,4 @@ public override System.Text.Encoding Encoding } } } -#endif +#endif \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/DefaultOptionsProvider.cs b/test/NUnitLite/NUnitFramework/nunitlite/DefaultOptionsProvider.cs new file mode 100644 index 000000000..44d1ec199 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/DefaultOptionsProvider.cs @@ -0,0 +1,45 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +namespace NUnit.Common +{ + using System; + + internal sealed class DefaultOptionsProvider : IDefaultOptionsProvider + { +#if !SILVERLIGHT && !NETCF + private const string EnvironmentVariableTeamcityProjectName = "TEAMCITY_PROJECT_NAME"; +#endif + + public bool TeamCity + { + get + { +#if !SILVERLIGHT && !NETCF + return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariableTeamcityProjectName)); +#else + return false; +#endif + } + } + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/ExtendedTextWrapper.cs b/test/NUnitLite/NUnitFramework/nunitlite/ExtendedTextWrapper.cs new file mode 100644 index 000000000..34c56c2f9 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/ExtendedTextWrapper.cs @@ -0,0 +1,156 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.IO; +using System.Text; + +namespace NUnit.Common +{ + /// + /// ExtendedTextWrapper wraps a TextWriter and makes it + /// look like an ExtendedTextWriter. All style indications + /// are ignored. It's used when text is being written + /// to a file. + /// + public class ExtendedTextWrapper : ExtendedTextWriter + { + private TextWriter _writer; + + public ExtendedTextWrapper(TextWriter writer) + { + _writer = writer; + } + + #region TextWriter Overrides + + /// + /// Write a single char value + /// + public override void Write(char value) + { + _writer.Write(value); + } + + /// + /// Write a string value + /// + public override void Write(string value) + { + _writer.Write(value); + } + + /// + /// Write a string value followed by a NewLine + /// + public override void WriteLine(string value) + { + _writer.WriteLine(value); + } + + /// + /// Gets the encoding for this ExtendedTextWriter + /// + public override Encoding Encoding + { + get { return _writer.Encoding; } + } + + /// + /// Dispose the Extended TextWriter + /// + protected override void Dispose(bool disposing) + { + _writer.Dispose(); + } + + #endregion + + #region Extended Methods + + /// + /// Writes the value with the specified style. + /// + /// The style. + /// The value. + public override void Write(ColorStyle style, string value) + { + Write(value); + } + + /// + /// Writes the value with the specified style + /// + /// The style. + /// The value. + public override void WriteLine(ColorStyle style, string value) + { + WriteLine(value); + } + + /// + /// Writes the label and the option that goes with it. + /// + /// The label. + /// The option. + public override void WriteLabel(string label, object option) + { + Write(label); + Write(option.ToString()); + } + + /// + /// Writes the label and the option that goes with it. + /// + /// The label. + /// The option. + /// The color to display the value with + public override void WriteLabel(string label, object option, ColorStyle valueStyle) + { + WriteLabel(label, option); + } + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + public override void WriteLabelLine(string label, object option) + { + WriteLabel(label, option); + WriteLine(); + } + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + /// The color to display the value with + public override void WriteLabelLine(string label, object option, ColorStyle valueStyle) + { + WriteLabelLine(label, option); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/ExtendedTextWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/ExtendedTextWriter.cs new file mode 100644 index 000000000..f1bd6af21 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/ExtendedTextWriter.cs @@ -0,0 +1,82 @@ +// *********************************************************************** +// Copyright (c) 2014-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.IO; + +namespace NUnit.Common +{ + /// + /// ExtendedTextWriter extends the TextWriter abstract class + /// to support displaying text in color. + /// + public abstract class ExtendedTextWriter : TextWriter + { + #region Extended Methods + + /// + /// Writes the value with the specified style. + /// + /// The style. + /// The value. + public abstract void Write(ColorStyle style, string value); + + /// + /// Writes the value with the specified style + /// + /// The style. + /// The value. + public abstract void WriteLine(ColorStyle style, string value); + + /// + /// Writes the label and the option that goes with it. + /// + /// The label. + /// The option. + public abstract void WriteLabel(string label, object option); + + /// + /// Writes the label and the option that goes with it. + /// + /// The label. + /// The option. + /// The color to display the value with + public abstract void WriteLabel(string label, object option, ColorStyle valueStyle); + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + public abstract void WriteLabelLine(string label, object option); + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + /// The color to display the value with + public abstract void WriteLabelLine(string label, object option, ColorStyle valueStyle); + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/IDefaultOptionsProvider.cs b/test/NUnitLite/NUnitFramework/nunitlite/IDefaultOptionsProvider.cs new file mode 100644 index 000000000..e40c94ee3 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/IDefaultOptionsProvider.cs @@ -0,0 +1,30 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Common +{ + internal interface IDefaultOptionsProvider + { + bool TeamCity { get; } + } +} \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/NUnitLiteOptions.cs b/test/NUnitLite/NUnitFramework/nunitlite/NUnitLiteOptions.cs new file mode 100644 index 000000000..338b2ce14 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/NUnitLiteOptions.cs @@ -0,0 +1,44 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using NUnit.Common; + +namespace NUnitLite +{ + /// + /// NUnitLiteOptions encapsulates the option settings for NUnitLite. + /// Currently, there are no additional options beyond those common + /// options that are shared with nunit3-console. If NUnitLite should + /// acquire some unique options, they should be placed here. + /// + public class NUnitLiteOptions : CommandLineOptions + { + /// + /// Constructor + /// + public NUnitLiteOptions(params string[] args) : base(args) { } + + // Currently used only by test + internal NUnitLiteOptions(IDefaultOptionsProvider provider, params string[] args) : base(provider, args) { } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Options.cs b/test/NUnitLite/NUnitFramework/nunitlite/Options.cs new file mode 100644 index 000000000..e86b37000 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Options.cs @@ -0,0 +1,1151 @@ +// +// Options.cs +// +// Authors: +// Jonathan Pryor +// +// Copyright (C) 2008 Novell (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +// Compile With: +// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll +// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll +// +// The LINQ version just changes the implementation of +// OptionSet.Parse(IEnumerable), and confers no semantic changes. + +// +// A Getopt::Long-inspired option parsing library for C#. +// +// NDesk.Options.OptionSet is built upon a key/value table, where the +// key is a option format string and the value is a delegate that is +// invoked when the format string is matched. +// +// Option format strings: +// Regex-like BNF Grammar: +// name: .+ +// type: [=:] +// sep: ( [^{}]+ | '{' .+ '}' )? +// aliases: ( name type sep ) ( '|' name type sep )* +// +// Each '|'-delimited name is an alias for the associated action. If the +// format string ends in a '=', it has a required value. If the format +// string ends in a ':', it has an optional value. If neither '=' or ':' +// is present, no value is supported. `=' or `:' need only be defined on one +// alias, but if they are provided on more than one they must be consistent. +// +// Each alias portion may also end with a "key/value separator", which is used +// to split option values if the option accepts > 1 value. If not specified, +// it defaults to '=' and ':'. If specified, it can be any character except +// '{' and '}' OR the *string* between '{' and '}'. If no separator should be +// used (i.e. the separate values should be distinct arguments), then "{}" +// should be used as the separator. +// +// Options are extracted either from the current option by looking for +// the option name followed by an '=' or ':', or is taken from the +// following option IFF: +// - The current option does not contain a '=' or a ':' +// - The current option requires a value (i.e. not a Option type of ':') +// +// The `name' used in the option format string does NOT include any leading +// option indicator, such as '-', '--', or '/'. All three of these are +// permitted/required on any named option. +// +// Option bundling is permitted so long as: +// - '-' is used to start the option group +// - all of the bundled options are a single character +// - at most one of the bundled options accepts a value, and the value +// provided starts from the next character to the end of the string. +// +// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' +// as '-Dname=value'. +// +// Option processing is disabled by specifying "--". All options after "--" +// are returned by OptionSet.Parse() unchanged and unprocessed. +// +// Unprocessed options are returned from OptionSet.Parse(). +// +// Examples: +// int verbose = 0; +// OptionSet p = new OptionSet () +// .Add ("v", v => ++verbose) +// .Add ("name=|value=", v => Console.WriteLine (v)); +// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); +// +// The above would parse the argument string array, and would invoke the +// lambda expression three times, setting `verbose' to 3 when complete. +// It would also print out "A" and "B" to standard output. +// The returned array would contain the string "extra". +// +// C# 3.0 collection initializers are supported and encouraged: +// var p = new OptionSet () { +// { "h|?|help", v => ShowHelp () }, +// }; +// +// System.ComponentModel.TypeConverter is also supported, allowing the use of +// custom data types in the callback type; TypeConverter.ConvertFromString() +// is used to convert the value option to an instance of the specified +// type: +// +// var p = new OptionSet () { +// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, +// }; +// +// Random other tidbits: +// - Boolean options (those w/o '=' or ':' in the option format string) +// are explicitly enabled if they are followed with '+', and explicitly +// disabled if they are followed with '-': +// string a = null; +// var p = new OptionSet () { +// { "a", s => a = s }, +// }; +// p.Parse (new string[]{"-a"}); // sets v != null +// p.Parse (new string[]{"-a+"}); // sets v != null +// p.Parse (new string[]{"-a-"}); // sets v == null +// +// The NUnit version of this file introduces conditional compilation for +// building under the Compact Framework (NETCF) and Silverlight (SILVERLIGHT) +// as well as for use with a portable class library (PORTABLE). +// +// 11/5/2015 - +// Change namespace to avoid conflict with user code use of mono.options + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; + +// Missing XML Docs +#pragma warning disable 1591 + +#if PORTABLE +using NUnit.Compatibility; +#else +using System.Security.Permissions; +#endif + +#if LINQ +using System.Linq; +#endif + +#if TEST +using NDesk.Options; +#endif + +#if NUNIT_CONSOLE || NUNITLITE || NUNIT_ENGINE +namespace NUnit.Options +#elif NDESK_OPTIONS +namespace NDesk.Options +#else +namespace Mono.Options +#endif +{ + public class OptionValueCollection : IList, IList { + + List values = new List (); + OptionContext c; + + internal OptionValueCollection (OptionContext c) + { + this.c = c; + } + + #region ICollection + void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} + bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} + object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} + #endregion + + #region ICollection + public void Add (string item) {values.Add (item);} + public void Clear () {values.Clear ();} + public bool Contains (string item) {return values.Contains (item);} + public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} + public bool Remove (string item) {return values.Remove (item);} + public int Count {get {return values.Count;}} + public bool IsReadOnly {get {return false;}} + #endregion + + #region IEnumerable + IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} + #endregion + + #region IEnumerable + public IEnumerator GetEnumerator () {return values.GetEnumerator ();} + #endregion + + #region IList + int IList.Add (object value) {return (values as IList).Add (value);} + bool IList.Contains (object value) {return (values as IList).Contains (value);} + int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} + void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} + void IList.Remove (object value) {(values as IList).Remove (value);} + void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} + bool IList.IsFixedSize {get {return false;}} + object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} + #endregion + + #region IList + public int IndexOf (string item) {return values.IndexOf (item);} + public void Insert (int index, string item) {values.Insert (index, item);} + public void RemoveAt (int index) {values.RemoveAt (index);} + + private void AssertValid (int index) + { + if (c.Option == null) + throw new InvalidOperationException ("OptionContext.Option is null."); + if (index >= c.Option.MaxValueCount) + throw new ArgumentOutOfRangeException ("index"); + if (c.Option.OptionValueType == OptionValueType.Required && + index >= values.Count) + throw new OptionException (string.Format ( + c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), + c.OptionName); + } + + public string this [int index] { + get { + AssertValid (index); + return index >= values.Count ? null : values [index]; + } + set { + values [index] = value; + } + } + #endregion + + public List ToList () + { + return new List (values); + } + + public string[] ToArray () + { + return values.ToArray (); + } + + public override string ToString () + { + return string.Join (", ", values.ToArray ()); + } + } + + public class OptionContext { + private Option option; + private string name; + private int index; + private OptionSet set; + private OptionValueCollection c; + + public OptionContext (OptionSet set) + { + this.set = set; + this.c = new OptionValueCollection (this); + } + + public Option Option { + get {return option;} + set {option = value;} + } + + public string OptionName { + get {return name;} + set {name = value;} + } + + public int OptionIndex { + get {return index;} + set {index = value;} + } + + public OptionSet OptionSet { + get {return set;} + } + + public OptionValueCollection OptionValues { + get {return c;} + } + } + + public enum OptionValueType { + None, + Optional, + Required, + } + + public abstract class Option { + string prototype, description; + string[] names; + OptionValueType type; + int count; + string[] separators; + + protected Option (string prototype, string description) + : this (prototype, description, 1) + { + } + + protected Option (string prototype, string description, int maxValueCount) + { + if (prototype == null) + throw new ArgumentNullException ("prototype"); + if (prototype.Length == 0) + throw new ArgumentException ("Cannot be the empty string.", "prototype"); + if (maxValueCount < 0) + throw new ArgumentOutOfRangeException ("maxValueCount"); + + this.prototype = prototype; + this.names = prototype.Split ('|'); + this.description = description; + this.count = maxValueCount; + this.type = ParsePrototype (); + + if (this.count == 0 && type != OptionValueType.None) + throw new ArgumentException ( + "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + + "OptionValueType.Optional.", + "maxValueCount"); + if (this.type == OptionValueType.None && maxValueCount > 1) + throw new ArgumentException ( + string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), + "maxValueCount"); + if (Array.IndexOf (names, "<>") >= 0 && + ((names.Length == 1 && this.type != OptionValueType.None) || + (names.Length > 1 && this.MaxValueCount > 1))) + throw new ArgumentException ( + "The default option handler '<>' cannot require values.", + "prototype"); + } + + public string Prototype {get {return prototype;}} + public string Description {get {return description;}} + public OptionValueType OptionValueType {get {return type;}} + public int MaxValueCount {get {return count;}} + + public string[] GetNames () + { + return (string[]) names.Clone (); + } + + public string[] GetValueSeparators () + { + if (separators == null) + return new string [0]; + return (string[]) separators.Clone (); + } + + protected static T Parse (string value, OptionContext c) + { + Type tt = typeof (T); +#if PORTABLE + bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType && + !tt.GetTypeInfo().IsGenericTypeDefinition && + tt.GetGenericTypeDefinition () == typeof (Nullable<>); + Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); +#else + bool nullable = tt.IsValueType && tt.IsGenericType && + !tt.IsGenericTypeDefinition && + tt.GetGenericTypeDefinition () == typeof (Nullable<>); + Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); +#endif + +#if !NETCF && !SILVERLIGHT && !PORTABLE + TypeConverter conv = TypeDescriptor.GetConverter (targetType); +#endif + T t = default (T); + try { + if (value != null) +#if NETCF || SILVERLIGHT || PORTABLE + t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture); +#else + t = (T) conv.ConvertFromString (value); +#endif + } + catch (Exception e) { + throw new OptionException ( + string.Format ( + c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), + value, targetType.Name, c.OptionName), + c.OptionName, e); + } + return t; + } + + internal string[] Names {get {return names;}} + internal string[] ValueSeparators {get {return separators;}} + + static readonly char[] NameTerminator = new char[]{'=', ':'}; + + private OptionValueType ParsePrototype () + { + char type = '\0'; + List seps = new List (); + for (int i = 0; i < names.Length; ++i) { + string name = names [i]; + if (name.Length == 0) + throw new ArgumentException ("Empty option names are not supported.", "prototype"); + + int end = name.IndexOfAny (NameTerminator); + if (end == -1) + continue; + names [i] = name.Substring (0, end); + if (type == '\0' || type == name [end]) + type = name [end]; + else + throw new ArgumentException ( + string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), + "prototype"); + AddSeparators (name, end, seps); + } + + if (type == '\0') + return OptionValueType.None; + + if (count <= 1 && seps.Count != 0) + throw new ArgumentException ( + string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), + "prototype"); + if (count > 1) { + if (seps.Count == 0) + this.separators = new string[]{":", "="}; + else if (seps.Count == 1 && seps [0].Length == 0) + this.separators = null; + else + this.separators = seps.ToArray (); + } + + return type == '=' ? OptionValueType.Required : OptionValueType.Optional; + } + + private static void AddSeparators (string name, int end, ICollection seps) + { + int start = -1; + for (int i = end+1; i < name.Length; ++i) { + switch (name [i]) { + case '{': + if (start != -1) + throw new ArgumentException ( + string.Format ("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + start = i+1; + break; + case '}': + if (start == -1) + throw new ArgumentException ( + string.Format ("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + seps.Add (name.Substring (start, i-start)); + start = -1; + break; + default: + if (start == -1) + seps.Add (name [i].ToString ()); + break; + } + } + if (start != -1) + throw new ArgumentException ( + string.Format ("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + } + + public void Invoke (OptionContext c) + { + OnParseComplete (c); + c.OptionName = null; + c.Option = null; + c.OptionValues.Clear (); + } + + protected abstract void OnParseComplete (OptionContext c); + + public override string ToString () + { + return Prototype; + } + } + +#if !SILVERLIGHT && !PORTABLE + [Serializable] +#endif + public class OptionException : Exception + { + private string option; + + public OptionException () + { + } + + public OptionException (string message, string optionName) + : base (message) + { + this.option = optionName; + } + + public OptionException (string message, string optionName, Exception innerException) + : base (message, innerException) + { + this.option = optionName; + } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + protected OptionException (SerializationInfo info, StreamingContext context) + : base (info, context) + { + this.option = info.GetString ("OptionName"); + } +#endif + + public string OptionName { + get {return this.option;} + } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] + public override void GetObjectData (SerializationInfo info, StreamingContext context) + { + base.GetObjectData (info, context); + info.AddValue ("OptionName", option); + } +#endif + } + + public delegate void OptionAction (TKey key, TValue value); + + public class OptionSet : KeyedCollection + { +#if !PORTABLE + public OptionSet () + : this (delegate (string f) {return f;}) + { + } + + public OptionSet (Converter localizer) + { + this.localizer = localizer; + } + + Converter localizer; + + public Converter MessageLocalizer { + get {return localizer;} + } +#else + string localizer(string msg) + { + return msg; + } + + public string MessageLocalizer(string msg) + { + return msg; + } +#endif + + protected override string GetKeyForItem (Option item) + { + if (item == null) + throw new ArgumentNullException ("option"); + if (item.Names != null && item.Names.Length > 0) + return item.Names [0]; + // This should never happen, as it's invalid for Option to be + // constructed w/o any names. + throw new InvalidOperationException ("Option has no names!"); + } + + [Obsolete ("Use KeyedCollection.this[string]")] + protected Option GetOptionForName (string option) + { + if (option == null) + throw new ArgumentNullException ("option"); + try { + return base [option]; + } + catch (KeyNotFoundException) { + return null; + } + } + + protected override void InsertItem (int index, Option item) + { + base.InsertItem (index, item); + AddImpl (item); + } + + protected override void RemoveItem (int index) + { + base.RemoveItem (index); + Option p = Items [index]; + // KeyedCollection.RemoveItem() handles the 0th item + for (int i = 1; i < p.Names.Length; ++i) { + Dictionary.Remove (p.Names [i]); + } + } + + protected override void SetItem (int index, Option item) + { + base.SetItem (index, item); + RemoveItem (index); + AddImpl (item); + } + + private void AddImpl (Option option) + { + if (option == null) + throw new ArgumentNullException ("option"); + List added = new List (option.Names.Length); + try { + // KeyedCollection.InsertItem/SetItem handle the 0th name. + for (int i = 1; i < option.Names.Length; ++i) { + Dictionary.Add (option.Names [i], option); + added.Add (option.Names [i]); + } + } + catch (Exception) { + foreach (string name in added) + Dictionary.Remove (name); + throw; + } + } + + public new OptionSet Add (Option option) + { + base.Add (option); + return this; + } + + sealed class ActionOption : Option { + Action action; + + public ActionOption (string prototype, string description, int count, Action action) + : base (prototype, description, count) + { + if (action == null) + throw new ArgumentNullException ("action"); + this.action = action; + } + + protected override void OnParseComplete (OptionContext c) + { + action (c.OptionValues); + } + } + + public OptionSet Add (string prototype, Action action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, Action action) + { + if (action == null) + throw new ArgumentNullException ("action"); + Option p = new ActionOption (prototype, description, 1, + delegate (OptionValueCollection v) { action (v [0]); }); + base.Add (p); + return this; + } + + public OptionSet Add (string prototype, OptionAction action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, OptionAction action) + { + if (action == null) + throw new ArgumentNullException ("action"); + Option p = new ActionOption (prototype, description, 2, + delegate (OptionValueCollection v) {action (v [0], v [1]);}); + base.Add (p); + return this; + } + + sealed class ActionOption : Option { + Action action; + + public ActionOption (string prototype, string description, Action action) + : base (prototype, description, 1) + { + if (action == null) + throw new ArgumentNullException ("action"); + this.action = action; + } + + protected override void OnParseComplete (OptionContext c) + { + action (Parse (c.OptionValues [0], c)); + } + } + + sealed class ActionOption : Option { + OptionAction action; + + public ActionOption (string prototype, string description, OptionAction action) + : base (prototype, description, 2) + { + if (action == null) + throw new ArgumentNullException ("action"); + this.action = action; + } + + protected override void OnParseComplete (OptionContext c) + { + action ( + Parse (c.OptionValues [0], c), + Parse (c.OptionValues [1], c)); + } + } + + public OptionSet Add (string prototype, Action action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, Action action) + { + return Add (new ActionOption (prototype, description, action)); + } + + public OptionSet Add (string prototype, OptionAction action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, OptionAction action) + { + return Add (new ActionOption (prototype, description, action)); + } + + protected virtual OptionContext CreateOptionContext () + { + return new OptionContext (this); + } + +#if LINQ + public List Parse (IEnumerable arguments) + { + bool process = true; + OptionContext c = CreateOptionContext (); + c.OptionIndex = -1; + var def = GetOptionForName ("<>"); + var unprocessed = + from argument in arguments + where ++c.OptionIndex >= 0 && (process || def != null) + ? process + ? argument == "--" + ? (process = false) + : !Parse (argument, c) + ? def != null + ? Unprocessed (null, def, c, argument) + : true + : false + : def != null + ? Unprocessed (null, def, c, argument) + : true + : true + select argument; + List r = unprocessed.ToList (); + if (c.Option != null) + c.Option.Invoke (c); + return r; + } +#else + public List Parse (IEnumerable arguments) + { + OptionContext c = CreateOptionContext (); + c.OptionIndex = -1; + bool process = true; + List unprocessed = new List (); + Option def = Contains ("<>") ? this ["<>"] : null; + foreach (string argument in arguments) { + ++c.OptionIndex; + if (argument == "--") { + process = false; + continue; + } + if (!process) { + Unprocessed (unprocessed, def, c, argument); + continue; + } + if (!Parse (argument, c)) + Unprocessed (unprocessed, def, c, argument); + } + if (c.Option != null) + c.Option.Invoke (c); + return unprocessed; + } +#endif + + private static bool Unprocessed (ICollection extra, Option def, OptionContext c, string argument) + { + if (def == null) { + extra.Add (argument); + return false; + } + c.OptionValues.Add (argument); + c.Option = def; + c.Option.Invoke (c); + return false; + } + + private readonly Regex ValueOption = new Regex ( + @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); + + protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) + { + if (argument == null) + throw new ArgumentNullException ("argument"); + + flag = name = sep = value = null; + Match m = ValueOption.Match (argument); + if (!m.Success) { + return false; + } + flag = m.Groups ["flag"].Value; + name = m.Groups ["name"].Value; + if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { + sep = m.Groups ["sep"].Value; + value = m.Groups ["value"].Value; + } + return true; + } + + protected virtual bool Parse (string argument, OptionContext c) + { + if (c.Option != null) { + ParseValue (argument, c); + return true; + } + + string f, n, s, v; + if (!GetOptionParts (argument, out f, out n, out s, out v)) + return false; + + Option p; + if (Contains (n)) { + p = this [n]; + c.OptionName = f + n; + c.Option = p; + switch (p.OptionValueType) { + case OptionValueType.None: + c.OptionValues.Add (n); + c.Option.Invoke (c); + break; + case OptionValueType.Optional: + case OptionValueType.Required: + ParseValue (v, c); + break; + } + return true; + } + // no match; is it a bool option? + if (ParseBool (argument, n, c)) + return true; + // is it a bundled option? + if (ParseBundledValue (f, string.Concat (n + s + v), c)) + return true; + + return false; + } + + private void ParseValue (string option, OptionContext c) + { + if (option != null) + foreach (string o in c.Option.ValueSeparators != null + ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) + : new string[]{option}) { + c.OptionValues.Add (o); + } + if (c.OptionValues.Count == c.Option.MaxValueCount || + c.Option.OptionValueType == OptionValueType.Optional) + c.Option.Invoke (c); + else if (c.OptionValues.Count > c.Option.MaxValueCount) { + throw new OptionException (localizer (string.Format ( + "Error: Found {0} option values when expecting {1}.", + c.OptionValues.Count, c.Option.MaxValueCount)), + c.OptionName); + } + } + + private bool ParseBool (string option, string n, OptionContext c) + { + Option p; + string rn; + if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && + Contains ((rn = n.Substring (0, n.Length-1)))) { + p = this [rn]; + string v = n [n.Length-1] == '+' ? option : null; + c.OptionName = option; + c.Option = p; + c.OptionValues.Add (v); + p.Invoke (c); + return true; + } + return false; + } + + private bool ParseBundledValue (string f, string n, OptionContext c) + { + if (f != "-") + return false; + for (int i = 0; i < n.Length; ++i) { + Option p; + string opt = f + n [i].ToString (); + string rn = n [i].ToString (); + if (!Contains (rn)) { + if (i == 0) + return false; + throw new OptionException (string.Format (localizer ( + "Cannot bundle unregistered option '{0}'."), opt), opt); + } + p = this [rn]; + switch (p.OptionValueType) { + case OptionValueType.None: + Invoke (c, opt, n, p); + break; + case OptionValueType.Optional: + case OptionValueType.Required: { + string v = n.Substring (i+1); + c.Option = p; + c.OptionName = opt; + ParseValue (v.Length != 0 ? v : null, c); + return true; + } + default: + throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); + } + } + return true; + } + + private static void Invoke (OptionContext c, string name, string value, Option option) + { + c.OptionName = name; + c.Option = option; + c.OptionValues.Add (value); + option.Invoke (c); + } + + private const int OptionWidth = 29; + + public void WriteOptionDescriptions (TextWriter o) + { + foreach (Option p in this) { + int written = 0; + if (!WriteOptionPrototype (o, p, ref written)) + continue; + + if (written < OptionWidth) + o.Write (new string (' ', OptionWidth - written)); + else { + o.WriteLine (); + o.Write (new string (' ', OptionWidth)); + } + + bool indent = false; + string prefix = new string (' ', OptionWidth+2); + foreach (string line in GetLines (localizer (GetDescription (p.Description)))) { + if (indent) + o.Write (prefix); + o.WriteLine (line); + indent = true; + } + } + } + + bool WriteOptionPrototype (TextWriter o, Option p, ref int written) + { + string[] names = p.Names; + + int i = GetNextOptionIndex (names, 0); + if (i == names.Length) + return false; + + if (names [i].Length == 1) { + Write (o, ref written, " -"); + Write (o, ref written, names [0]); + } + else { + Write (o, ref written, " --"); + Write (o, ref written, names [0]); + } + + for ( i = GetNextOptionIndex (names, i+1); + i < names.Length; i = GetNextOptionIndex (names, i+1)) { + Write (o, ref written, ", "); + Write (o, ref written, names [i].Length == 1 ? "-" : "--"); + Write (o, ref written, names [i]); + } + + if (p.OptionValueType == OptionValueType.Optional || + p.OptionValueType == OptionValueType.Required) { + if (p.OptionValueType == OptionValueType.Optional) { + Write (o, ref written, localizer ("[")); + } + Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); + string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 + ? p.ValueSeparators [0] + : " "; + for (int c = 1; c < p.MaxValueCount; ++c) { + Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); + } + if (p.OptionValueType == OptionValueType.Optional) { + Write (o, ref written, localizer ("]")); + } + } + return true; + } + + static int GetNextOptionIndex (string[] names, int i) + { + while (i < names.Length && names [i] == "<>") { + ++i; + } + return i; + } + + static void Write (TextWriter o, ref int n, string s) + { + n += s.Length; + o.Write (s); + } + + private static string GetArgumentName (int index, int maxIndex, string description) + { + if (description == null) + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + string[] nameStart; + if (maxIndex == 1) + nameStart = new string[]{"{0:", "{"}; + else + nameStart = new string[]{"{" + index + ":"}; + for (int i = 0; i < nameStart.Length; ++i) { + int start, j = 0; + do { + start = description.IndexOf (nameStart [i], j); + } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); + if (start == -1) + continue; + int end = description.IndexOf ("}", start); + if (end == -1) + continue; + return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); + } + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + } + + private static string GetDescription (string description) + { + if (description == null) + return string.Empty; + StringBuilder sb = new StringBuilder (description.Length); + int start = -1; + for (int i = 0; i < description.Length; ++i) { + switch (description [i]) { + case '{': + if (i == start) { + sb.Append ('{'); + start = -1; + } + else if (start < 0) + start = i + 1; + break; + case '}': + if (start < 0) { + if ((i+1) == description.Length || description [i+1] != '}') + throw new InvalidOperationException ("Invalid option description: " + description); + ++i; + sb.Append ("}"); + } + else { + sb.Append (description.Substring (start, i - start)); + start = -1; + } + break; + case ':': + if (start < 0) + goto default; + start = i + 1; + break; + default: + if (start < 0) + sb.Append (description [i]); + break; + } + } + return sb.ToString (); + } + + private static IEnumerable GetLines (string description) + { + if (string.IsNullOrEmpty (description)) { + yield return string.Empty; + yield break; + } + int length = 80 - OptionWidth - 1; + int start = 0, end; + do { + end = GetLineEnd (start, length, description); + char c = description [end-1]; + if (char.IsWhiteSpace (c)) + --end; + bool writeContinuation = end != description.Length && !IsEolChar (c); + string line = description.Substring (start, end - start) + + (writeContinuation ? "-" : ""); + yield return line; + start = end; + if (char.IsWhiteSpace (c)) + ++start; + length = 80 - OptionWidth - 2 - 1; + } while (end < description.Length); + } + + private static bool IsEolChar (char c) + { + return !char.IsLetterOrDigit (c); + } + + private static int GetLineEnd (int start, int length, string description) + { + int end = System.Math.Min (start + length, description.Length); + int sep = -1; + for (int i = start+1; i < end; ++i) { + if (description [i] == '\n') + return i+1; + if (IsEolChar (description [i])) + sep = i+1; + } + if (sep == -1 || end == description.Length) + return end; + return sep; + } + } +} + diff --git a/test/NUnitLite/NUnitFramework/nunitlite/OutputManager.cs b/test/NUnitLite/NUnitFramework/nunitlite/OutputManager.cs new file mode 100644 index 000000000..a6f655c6d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/OutputManager.cs @@ -0,0 +1,127 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Xml; +using NUnit.Common; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnitLite +{ + /// + /// OutputManager is responsible for creating output files + /// from a test run in various formats. + /// + public class OutputManager + { + private string _workDirectory; + + /// + /// Construct an OutputManager + /// + /// The directory to use for reports + public OutputManager(string workDirectory) + { + _workDirectory = workDirectory; + } + + /// + /// Write the result of a test run according to a spec. + /// + /// The test result + /// An output specification + /// Settings + /// Filter + public void WriteResultFile(ITestResult result, OutputSpecification spec, IDictionary runSettings, TestFilter filter) + { + string outputPath = Path.Combine(_workDirectory, spec.OutputPath); + OutputWriter outputWriter = null; + + switch (spec.Format) + { + case "nunit3": + outputWriter = new NUnit3XmlOutputWriter(); + break; + + case "nunit2": + outputWriter = new NUnit2XmlOutputWriter(); + break; + + //case "user": + // Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); + // string dir = Path.GetDirectoryName(uri.LocalPath); + // outputWriter = new XmlTransformOutputWriter(Path.Combine(dir, spec.Transform)); + // break; + + default: + throw new ArgumentException( + string.Format("Invalid XML output format '{0}'", spec.Format), + "spec"); + } + + outputWriter.WriteResultFile(result, outputPath, runSettings, filter); + Console.WriteLine("Results ({0}) saved as {1}", spec.Format, outputPath); + } + + /// + /// Write out the result of exploring the tests + /// + /// The top-level test + /// An OutputSpecification + public void WriteTestFile(ITest test, OutputSpecification spec) + { + string outputPath = Path.Combine(_workDirectory, spec.OutputPath); + OutputWriter outputWriter = null; + + switch (spec.Format) + { + case "nunit3": + outputWriter = new NUnit3XmlOutputWriter(); + break; + + case "cases": + outputWriter = new TestCaseOutputWriter(); + break; + + //case "user": + // Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); + // string dir = Path.GetDirectoryName(uri.LocalPath); + // outputWriter = new XmlTransformOutputWriter(Path.Combine(dir, spec.Transform)); + // break; + + default: + throw new ArgumentException( + string.Format("Invalid XML output format '{0}'", spec.Format), + "spec"); + } + + outputWriter.WriteTestFile(test, outputPath); + Console.WriteLine("Tests ({0}) saved as {1}", spec.Format, outputPath); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/OutputSpecification.cs b/test/NUnitLite/NUnitFramework/nunitlite/OutputSpecification.cs new file mode 100644 index 000000000..99e2d97e9 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/OutputSpecification.cs @@ -0,0 +1,109 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; + +namespace NUnit.Common +{ + /// + /// OutputSpecification encapsulates a file output path and format + /// for use in saving the results of a run. + /// + public class OutputSpecification + { + #region Constructor + + /// + /// Construct an OutputSpecification from an option value. + /// + /// The option value string. + public OutputSpecification(string spec) + { + if (spec == null) + throw new NullReferenceException("Output spec may not be null"); + + string[] parts = spec.Split(';'); + this.OutputPath = parts[0]; + + for (int i = 1; i < parts.Length; i++) + { + string[] opt = parts[i].Split('='); + + if (opt.Length != 2) + throw new ArgumentException(); + + switch (opt[0].Trim()) + { + case "format": + string fmt = opt[1].Trim(); + + if (this.Format != null && this.Format != fmt) + throw new ArgumentException( + string.Format("Conflicting format options: {0}", spec)); + + this.Format = fmt; + break; + + case "transform": + string val = opt[1].Trim(); + + if (this.Transform != null && this.Transform != val) + throw new ArgumentException( + string.Format("Conflicting transform options: {0}", spec)); + + if (this.Format != null && this.Format != "user") + throw new ArgumentException( + string.Format("Conflicting format options: {0}", spec)); + + this.Format = "user"; + this.Transform = opt[1].Trim(); + break; + } + } + + if (Format == null) + Format = "nunit3"; + } + + #endregion + + #region Properties + + /// + /// Gets the path to which output will be written + /// + public string OutputPath { get; private set; } + + /// + /// Gets the name of the format to be used + /// + public string Format { get; private set; } + + /// + /// Gets the file name of a transform to be applied + /// + public string Transform { get; private set; } + + #endregion + } +} diff --git a/test/NUnitLite/src/framework/Runner/OutputWriters/NUnit2XmlOutputWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/NUnit2XmlOutputWriter.cs similarity index 79% rename from test/NUnitLite/src/framework/Runner/OutputWriters/NUnit2XmlOutputWriter.cs rename to test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/NUnit2XmlOutputWriter.cs index 8ae022828..b66d9ca97 100644 --- a/test/NUnitLite/src/framework/Runner/OutputWriters/NUnit2XmlOutputWriter.cs +++ b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/NUnit2XmlOutputWriter.cs @@ -22,19 +22,17 @@ // *********************************************************************** using System; +using System.Collections; +using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Xml; using System.IO; -using NUnit.Framework.Api; +using NUnit.Common; +using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#else -using System.Collections.Specialized; -#endif -namespace NUnitLite.Runner +namespace NUnitLite { /// /// NUnit2XmlOutputWriter is able to create an xml file representing @@ -43,29 +41,15 @@ namespace NUnitLite.Runner public class NUnit2XmlOutputWriter : OutputWriter { private XmlWriter xmlWriter; - private DateTime startTime; - -#if CLR_2_0 || CLR_4_0 - private static Dictionary resultStates = new Dictionary(); -#else - private static StringDictionary resultStates = new StringDictionary(); -#endif - - static NUnit2XmlOutputWriter() - { - resultStates["Passed"] = "Success"; - resultStates["Failed"] = "Failure"; - resultStates["Failed:Error"] = "Error"; - resultStates["Failed:Cancelled"] = "Cancelled"; - resultStates["Inconclusive"] = "Inconclusive"; - resultStates["Skipped"] = "Skipped"; - resultStates["Skipped:Ignored"] = "Ignored"; - resultStates["Skipped:Invalid"] = "NotRunnable"; - } - public NUnit2XmlOutputWriter(DateTime startTime) + /// + /// Write info about a test + /// + /// The test + /// A TextWriter + public override void WriteTestFile(ITest test, TextWriter writer) { - this.startTime = startTime; + throw new NotImplementedException("Explore test output is not supported by the NUnit2 format."); } /// @@ -73,7 +57,9 @@ public NUnit2XmlOutputWriter(DateTime startTime) /// /// The test result for the run /// The TextWriter to which the xml will be written - public override void WriteResultFile(ITestResult result, TextWriter writer) + /// + /// + public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary runSettings, TestFilter filter) { // NOTE: Under .NET 1.1, XmlTextWriter does not implement IDisposable, // but does implement Close(). Hence we cannot use a 'using' clause. @@ -106,7 +92,7 @@ private void WriteXmlOutput(ITestResult result, XmlWriter xmlWriter) private void InitializeXmlFile(ITestResult result) { - ResultSummary summaryResults = new ResultSummary(result); + ResultSummary summary = new ResultSummary(result); xmlWriter.WriteStartDocument(false); xmlWriter.WriteComment("This file represents the results of running a test suite"); @@ -114,17 +100,18 @@ private void InitializeXmlFile(ITestResult result) xmlWriter.WriteStartElement("test-results"); xmlWriter.WriteAttributeString("name", result.FullName); - xmlWriter.WriteAttributeString("total", summaryResults.TestCount.ToString()); - xmlWriter.WriteAttributeString("errors", summaryResults.ErrorCount.ToString()); - xmlWriter.WriteAttributeString("failures", summaryResults.FailureCount.ToString()); - xmlWriter.WriteAttributeString("not-run", summaryResults.NotRunCount.ToString()); - xmlWriter.WriteAttributeString("inconclusive", summaryResults.InconclusiveCount.ToString()); - xmlWriter.WriteAttributeString("ignored", summaryResults.IgnoreCount.ToString()); - xmlWriter.WriteAttributeString("skipped", summaryResults.SkipCount.ToString()); - xmlWriter.WriteAttributeString("invalid", summaryResults.InvalidCount.ToString()); - - xmlWriter.WriteAttributeString("date", XmlConvert.ToString(startTime, "yyyy-MM-dd")); - xmlWriter.WriteAttributeString("time", XmlConvert.ToString(startTime, "HH:mm:ss")); + xmlWriter.WriteAttributeString("total", summary.TestCount.ToString()); + xmlWriter.WriteAttributeString("errors", summary.ErrorCount.ToString()); + xmlWriter.WriteAttributeString("failures", summary.FailureCount.ToString()); + var notRunTotal = summary.SkipCount + summary.FailureCount + summary.InvalidCount; + xmlWriter.WriteAttributeString("not-run", notRunTotal.ToString()); + xmlWriter.WriteAttributeString("inconclusive", summary.InconclusiveCount.ToString()); + xmlWriter.WriteAttributeString("ignored", summary.IgnoreCount.ToString()); + xmlWriter.WriteAttributeString("skipped", summary.SkipCount.ToString()); + xmlWriter.WriteAttributeString("invalid", summary.InvalidCount.ToString()); + + xmlWriter.WriteAttributeString("date", result.StartTime.ToString("yyyy-MM-dd")); + xmlWriter.WriteAttributeString("time", result.StartTime.ToString("HH:mm:ss")); WriteEnvironment(); WriteCultureInfo(); } @@ -142,7 +129,7 @@ private void WriteCultureInfo() private void WriteEnvironment() { xmlWriter.WriteStartElement("environment"); - AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(Assembly.GetExecutingAssembly()); + var assemblyName = AssemblyHelper.GetAssemblyName(Assembly.GetExecutingAssembly()); xmlWriter.WriteAttributeString("nunit-version", assemblyName.Version.ToString()); xmlWriter.WriteAttributeString("clr-version", @@ -176,7 +163,8 @@ private void WriteResultElement(ITestResult result) switch (result.ResultState.Status) { case TestStatus.Skipped: - WriteReasonElement(result.Message); + if (result.Message != null) + WriteReasonElement(result.Message); break; case TestStatus.Failed: WriteFailureElement(result.Message, result.StackTrace); @@ -208,8 +196,8 @@ private void StartTestElement(ITestResult result) if (suite != null) { xmlWriter.WriteStartElement("test-suite"); - xmlWriter.WriteAttributeString("type", suite.TestType); - xmlWriter.WriteAttributeString("name", suite.TestType == "Assembly" + xmlWriter.WriteAttributeString("type", suite.TestType == "ParameterizedMethod" ? "ParameterizedTest" : suite.TestType); + xmlWriter.WriteAttributeString("name", suite.TestType == "Assembly" || suite.TestType == "Project" ? result.Test.FullName : result.Test.Name); } @@ -226,14 +214,14 @@ private void StartTestElement(ITestResult result) } TestStatus status = result.ResultState.Status; - string translatedResult = resultStates[result.ResultState.ToString()]; + string translatedResult = TranslateResult(result.ResultState); if (status != TestStatus.Skipped) { xmlWriter.WriteAttributeString("executed", "True"); xmlWriter.WriteAttributeString("result", translatedResult); xmlWriter.WriteAttributeString("success", status == TestStatus.Passed ? "True" : "False"); - xmlWriter.WriteAttributeString("time", result.Duration.TotalSeconds.ToString()); + xmlWriter.WriteAttributeString("time", result.Duration.ToString("0.000", NumberFormatInfo.InvariantInfo)); xmlWriter.WriteAttributeString("asserts", result.AssertCount.ToString()); } else @@ -243,6 +231,37 @@ private void StartTestElement(ITestResult result) } } + private string TranslateResult(ResultState resultState) + { + switch (resultState.Status) + { + default: + case TestStatus.Passed: + return "Success"; + case TestStatus.Inconclusive: + return "Inconclusive"; + case TestStatus.Failed: + switch (resultState.Label) + { + case "Error": + case "Cancelled": + return resultState.Label; + default: + return "Failure"; + } + case TestStatus.Skipped: + switch (resultState.Label) + { + case "Ignored": + return "Ignored"; + case "Invalid": + return "NotRunnable"; + default: + return "Skipped"; + } + } + } + private void WriteCategories(ITestResult result) { IPropertyBag properties = result.Test.Properties; @@ -292,7 +311,7 @@ private void WriteReasonElement(string message) { xmlWriter.WriteStartElement("reason"); xmlWriter.WriteStartElement("message"); - xmlWriter.WriteCData(message); + WriteCData(message); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); } @@ -332,7 +351,7 @@ private void WriteChildResults(ITestResult result) //{ // /*The default code page for the system will be used. // Since all code pages use the same lower 128 bytes, this should be sufficient - // for finding uprintable control characters that make the xslt processor error. + // for finding unprintable control characters that make the xslt processor error. // We use characters encoded by the default code page to avoid mistaking bytes as // individual characters on non-latin code pages.*/ // char[] encodedChars = System.Text.Encoding.Default.GetChars(System.Text.Encoding.Default.GetBytes(encodedString)); diff --git a/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/NUnit3XmlOutputWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/NUnit3XmlOutputWriter.cs new file mode 100644 index 000000000..03b5d3fa9 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/NUnit3XmlOutputWriter.cs @@ -0,0 +1,148 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Xml; +using NUnit.Common; +using NUnit.Framework.Api; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnitLite +{ + /// + /// NUnit3XmlOutputWriter is responsible for writing the results + /// of a test to a file in NUnit 3.0 format. + /// + public class NUnit3XmlOutputWriter : OutputWriter + { + /// + /// Writes test info to the specified TextWriter + /// + /// The test to be written + /// A TextWriter to which the test info is written + public override void WriteTestFile(ITest test, TextWriter writer) + { + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Indent = true; + + using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings)) + { + test.ToXml(true).WriteTo(xmlWriter); + } + } + + /// + /// Writes the test result to the specified TextWriter + /// + /// The result to be written to a file + /// A TextWriter to which the result is written + /// + /// + public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary runSettings, TestFilter filter) + { + XmlWriterSettings xmlSettings = new XmlWriterSettings(); + xmlSettings.Indent = true; + + using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlSettings)) + { + WriteXmlResultOutput(result, xmlWriter, runSettings, filter); + } + } + + private void WriteXmlResultOutput(ITestResult result, XmlWriter xmlWriter, IDictionary runSettings, TestFilter filter) + { + TNode resultNode = result.ToXml(true); + + // Insert elements as first child in reverse order + if (runSettings != null) // Some platforms don't have settings + FrameworkController.InsertSettingsElement(resultNode, runSettings); +#if !SILVERLIGHT + FrameworkController.InsertEnvironmentElement(resultNode); +#endif + + TNode testRun = MakeTestRunElement(result); + +#if !SILVERLIGHT && !NETCF + testRun.ChildNodes.Add(MakeCommandLineElement()); +#endif + testRun.ChildNodes.Add(MakeTestFilterElement(filter)); + testRun.ChildNodes.Add(resultNode); + + testRun.WriteTo(xmlWriter); + } + + private TNode MakeTestRunElement(ITestResult result) + { + TNode testRun = new TNode("test-run"); + + testRun.AddAttribute("id", "2"); + testRun.AddAttribute("name", result.Name); + testRun.AddAttribute("fullname", result.FullName); + testRun.AddAttribute("testcasecount", result.Test.TestCaseCount.ToString()); + + testRun.AddAttribute("result", result.ResultState.Status.ToString()); + if (result.ResultState.Label != string.Empty) + testRun.AddAttribute("label", result.ResultState.Label); + + testRun.AddAttribute("start-time", result.StartTime.ToString("u")); + testRun.AddAttribute("end-time", result.EndTime.ToString("u")); + testRun.AddAttribute("duration", result.Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo)); + + testRun.AddAttribute("total", (result.PassCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString()); + testRun.AddAttribute("passed", result.PassCount.ToString()); + testRun.AddAttribute("failed", result.FailCount.ToString()); + testRun.AddAttribute("inconclusive", result.InconclusiveCount.ToString()); + testRun.AddAttribute("skipped", result.SkipCount.ToString()); + testRun.AddAttribute("asserts", result.AssertCount.ToString()); + + testRun.AddAttribute("random-seed", Randomizer.InitialSeed.ToString()); + + // NOTE: The console runner adds attributes for engine-version and clr-version + // Neither of these is needed under nunitlite since there is no engine involved + // and we are running under the same runtime as the tests. + + return testRun; + } + +#if !SILVERLIGHT && !NETCF + private static TNode MakeCommandLineElement() + { + return new TNode("command-line", Environment.CommandLine, true); + } +#endif + + private static TNode MakeTestFilterElement(TestFilter filter) + { + TNode result = new TNode("filter"); + if (!filter.IsEmpty) + filter.AddToXml(result, true); + return result; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/OutputWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/OutputWriter.cs new file mode 100644 index 000000000..75e569a16 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/OutputWriter.cs @@ -0,0 +1,83 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnitLite +{ + /// + /// OutputWriter is an abstract class used to write test + /// results to a file in various formats. Specific + /// OutputWriters are derived from this class. + /// + public abstract class OutputWriter + { + /// + /// Writes a test result to a file + /// + /// The result to be written + /// Path to the file to which the result is written + /// A dictionary of settings used for this test run + public void WriteResultFile(ITestResult result, string outputPath, IDictionary runSettings, TestFilter filter) + { + using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8)) + { + WriteResultFile(result, writer, runSettings, filter); + } + } + + /// + /// Writes test info to a file + /// + /// The test to be written + /// Path to the file to which the test info is written + public void WriteTestFile(ITest test, string outputPath) + { + using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8)) + { + WriteTestFile(test, writer); + } + } + + /// + /// Abstract method that writes a test result to a TextWriter + /// + /// The result to be written + /// A TextWriter to which the result is written + /// A dictionary of settings used for this test run + /// + public abstract void WriteResultFile(ITestResult result, TextWriter writer, IDictionary runSettings, TestFilter filter); + + /// + /// Abstract method that writes test info to a TextWriter + /// + /// The test to be written + /// A TextWriter to which the test info is written + public abstract void WriteTestFile(ITest test, TextWriter writer); + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/TestCaseOutputWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/TestCaseOutputWriter.cs new file mode 100644 index 000000000..0cdd51ce8 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/OutputWriters/TestCaseOutputWriter.cs @@ -0,0 +1,63 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Collections; +using System.Collections.Generic; +using System.IO; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnitLite +{ + /// + /// TestCaseOutputWriter lists test cases + /// + public class TestCaseOutputWriter : OutputWriter + { + /// + /// Write a list of test cases to a file + /// + /// + /// + public override void WriteTestFile(ITest test, TextWriter writer) + { + if (test.IsSuite) + foreach (var child in test.Tests) + WriteTestFile(child, writer); + else + writer.WriteLine(test.FullName); + } + + /// + /// Write a list of test cases to a file + /// + /// + /// + /// + /// + public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary runSettings, TestFilter filter) + { + WriteTestFile(result.Test, writer); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Program.cs b/test/NUnitLite/NUnitFramework/nunitlite/Program.cs new file mode 100644 index 000000000..0a0c23620 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Program.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using NUnit.Common; + +namespace NUnitLite +{ + static class Program + { + [STAThread] + public static int Main(string[] args) + { + return new AutoRun().Execute(args); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs b/test/NUnitLite/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..e83b25cd2 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs @@ -0,0 +1,49 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("nunitlite.tests, PublicKey=002400000480000094" + + "000000060200000024000052534131000400000100010031eea" + + "370b1984bfa6d1ea760e1ca6065cee41a1a279ca234933fe977" + + "a096222c0e14f9e5a17d5689305c6d7f1206a85a53c48ca0100" + + "80799d6eeef61c98abd18767827dc05daea6b6fbd2e868410d9" + + "bee5e972a004ddd692dec8fa404ba4591e847a8cf35de21c2d3" + + "723bc8d775a66b594adeb967537729fe2a446b548cd57a6")] + +#if NET_4_5 +[assembly: AssemblyTitle("NUnitLite Runner .NET 4.5")] +#elif NET_4_0 +[assembly: AssemblyTitle("NUnitLite Runner .NET 4.0")] +#elif NET_2_0 +[assembly: AssemblyTitle("NUnitLite Runner .NET 2.0")] +#elif SL_5_0 +[assembly: AssemblyTitle("NUnitLite Runner Silverlight 5.0")] +#elif NETCF_3_5 +[assembly: AssemblyTitle("NUnitLite Runner CF 3.5")] +#else +[assembly: AssemblyTitle("NUnitLite Runner")] +#endif + +[assembly: AssemblyDescription("")] \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/ResultSummary.cs b/test/NUnitLite/NUnitFramework/nunitlite/ResultSummary.cs new file mode 100644 index 000000000..cfda2a214 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/ResultSummary.cs @@ -0,0 +1,228 @@ +// *********************************************************************** +// Copyright (c) 2014-2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework.Interfaces; + +namespace NUnitLite +{ + /// + /// Helper class used to summarize the result of a test run + /// + public class ResultSummary + { + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// The result. + public ResultSummary(ITestResult result) + { + InitializeCounters(); + + ResultState = result.ResultState; + StartTime = result.StartTime; + EndTime = result.EndTime; + Duration = result.Duration; + + Summarize(result); + } + + #endregion + + #region Properties + + /// + /// Gets the number of test cases for which results + /// have been summarized. Any tests excluded by use of + /// Category or Explicit attributes are not counted. + /// + public int TestCount { get; private set; } + + /// + /// Returns the number of test cases actually run. + /// + public int RunCount + { + get { return PassCount + ErrorCount + FailureCount + InconclusiveCount; } + } + + /// + /// Gets the number of tests not run for any reason. + /// + public int NotRunCount + { + get { return InvalidCount + SkipCount + IgnoreCount + ExplicitCount; } + } + + /// + /// Returns the number of failed test cases (including errors and invalid tests) + /// + public int FailedCount + { + get { return FailureCount + InvalidCount + ErrorCount; } + } + + /// + /// Returns the sum of skipped test cases, including ignored and explicit tests + /// + public int TotalSkipCount + { + get { return SkipCount + IgnoreCount + ExplicitCount; } + } + + /// + /// Gets the count of passed tests + /// + public int PassCount { get; private set; } + + /// + /// Gets count of failed tests, excluding errors and invalid tests + /// + public int FailureCount { get; private set; } + + /// + /// Gets the error count + /// + public int ErrorCount { get; private set; } + + /// + /// Gets the count of inconclusive tests + /// + public int InconclusiveCount { get; private set; } + + /// + /// Returns the number of test cases that were not runnable + /// due to errors in the signature of the class or method. + /// Such tests are also counted as Errors. + /// + public int InvalidCount { get; private set; } + + /// + /// Gets the count of skipped tests, excluding ignored tests + /// + public int SkipCount { get; private set; } + + /// + /// Gets the ignore count + /// + public int IgnoreCount { get; private set; } + + /// + /// Gets the explicit count + /// + public int ExplicitCount { get; private set; } + + /// + /// Invalid Test Fixtures + /// + public int InvalidTestFixtures { get; private set; } + + /// + /// Gets the ResultState of the test result, which + /// indicates the success or failure of the test. + /// + public ResultState ResultState { get; private set; } + + /// + /// Gets or sets the time the test started running. + /// + public DateTime StartTime { get; private set; } + + /// + /// Gets or sets the time the test finished running. + /// + public DateTime EndTime { get; private set; } + + /// + /// Gets or sets the elapsed time for running the test in seconds + /// + public double Duration { get; private set; } + + #endregion + + #region Helper Methods + + private void InitializeCounters() + { + TestCount = 0; + PassCount = 0; + FailureCount = 0; + ErrorCount = 0; + InconclusiveCount = 0; + SkipCount = 0; + IgnoreCount = 0; + ExplicitCount = 0; + InvalidCount = 0; + } + + private void Summarize(ITestResult result) + { + var label = result.ResultState.Label; + var status = result.ResultState.Status; + + if (result.Test.IsSuite) + { + if (status == TestStatus.Failed && label == "Invalid") + InvalidTestFixtures++; + + foreach (ITestResult r in result.Children) + Summarize(r); + } + else + { + TestCount++; + switch (status) + { + case TestStatus.Passed: + PassCount++; + break; + case TestStatus.Skipped: + if (label == "Ignored") + IgnoreCount++; + else if (label == "Explicit") + ExplicitCount++; + else + SkipCount++; + break; + case TestStatus.Failed: + if (label == "Invalid") + InvalidCount++; + else if (label == "Error") + ErrorCount++; + else + FailureCount++; + break; + case TestStatus.Inconclusive: + InconclusiveCount++; + break; + } + + return; + } + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TestPage.xaml b/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TestPage.xaml new file mode 100644 index 000000000..67edb5090 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TestPage.xaml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NUnitLite + + + + Tests + + + + Passed + + + + Failed + + + + Errors + + + + Inconclusive + + + + Not Run + + + + + + + + + + + Running Tests... + + + + diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TestPage.xaml.cs b/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TestPage.xaml.cs new file mode 100644 index 000000000..52b14f058 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TestPage.xaml.cs @@ -0,0 +1,68 @@ +#if SILVERLIGHT +using System.Collections.Generic; +using System.Reflection; +using System.Windows; +using System.Windows.Controls; +using NUnit.Common; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnitLite.Runner.Silverlight +{ + /// + /// TestPage is the display page for the test results + /// + public partial class TestPage : UserControl + { + private Assembly _callingAssembly; + private TextUI _textUI; + private TextRunner _textRunner; + + /// + /// Initializes a new instance of the class. + /// + public TestPage() + { + InitializeComponent(); + + _textUI = new TextUI(new TextBlockWriter(this.ScratchArea)); + _callingAssembly = Assembly.GetCallingAssembly(); + _textRunner = new TextRunner(_callingAssembly); + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Display initial information so user sees something + _textUI.DisplayHeader(); + _textUI.DisplayRuntimeEnvironment(); + _textUI.DisplayTestFiles(new string[] { AssemblyHelper.GetAssemblyName(_callingAssembly).Name }); + + Dispatcher.BeginInvoke(() => ExecuteTests()); + } + + #region Helper Methods + + private void ExecuteTests() + { + // Clear original display so info won't appear twice + this.ScratchArea.Inlines.Clear(); + + _textRunner.Execute(_textUI, new NUnitLiteOptions()); + + ResultSummary summary = _textRunner.Summary; + + this.Total.Text = summary.TestCount.ToString(); + this.Failures.Text = summary.FailureCount.ToString(); + this.Errors.Text = summary.ErrorCount.ToString(); + var notRunTotal = summary.SkipCount + summary.InvalidCount + summary.IgnoreCount; + this.NotRun.Text = notRunTotal.ToString(); + this.Passed.Text = summary.PassCount.ToString(); + this.Inconclusive.Text = summary.InconclusiveCount.ToString(); + + this.Notice.Visibility = Visibility.Collapsed; + } + + #endregion + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TextBlockWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TextBlockWriter.cs new file mode 100644 index 000000000..8ecc18b35 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Silverlight/TextBlockWriter.cs @@ -0,0 +1,225 @@ +// *********************************************************************** +// Copyright (c) 2012 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if SILVERLIGHT +using System; +using System.Diagnostics; +using System.IO; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Media; +using NUnit.Common; + +namespace NUnitLite.Runner.Silverlight +{ + /// + /// TextBlockWriter is a TextWriter that sends it's + /// output to a Silverlight TextBlock. + /// + public class TextBlockWriter : ExtendedTextWriter + { + private TextBlock _textBlock; + + /// + /// Initializes a new instance of the class. + /// + /// The text block. + public TextBlockWriter(TextBlock textBlock) + { + this._textBlock = textBlock; + } + + #region TextWriter Overrides + + ///// + ///// Writes a character to the text stream. + ///// + ///// The character to write to the text stream. + ///// + ///// The is closed. + ///// + ///// + ///// An I/O error occurs. + ///// + //public override void Write(char value) + //{ + // textBlock.Text += value; + //} + + /// + /// Writes a string to the text stream. + /// + /// The string to write. + /// + /// The is closed. + /// + /// + /// An I/O error occurs. + /// + public override void Write(string value) + { + Write(ColorStyle.Default, value); + } + + /// + /// Writes a string followed by a line terminator to the text stream. + /// + /// The string to write. If is null, only the line termination characters are written. + /// + /// The is closed. + /// + /// + /// An I/O error occurs. + /// + public override void WriteLine(string value) + { + Write(value); + WriteLine(); + } + + /// + /// Adds a LineBreak to the TextBlock + /// + public override void WriteLine() + { + _textBlock.Inlines.Add(new LineBreak()); + } + + /// + /// When overridden in a derived class, returns the in which the output is written. + /// + /// + /// + /// The Encoding in which the output is written. + /// + public override System.Text.Encoding Encoding + { + get { return System.Text.Encoding.UTF8; } + } + + #endregion + + #region ExtendeTextWriter Overrides + + /// + /// Writes the value with the specified style. + /// + /// The style. + /// The value. + public override void Write(ColorStyle style, string value) + { + _textBlock.Inlines.Add(new Run() + { + Text = value, + Foreground = GetBrush(style) + }); + } + + /// + /// Writes the value with the specified style. + /// + /// The style. + /// The value. + public override void WriteLine(ColorStyle style, string value) + { + Write(style, value); + WriteLine(); + } + + /// + /// Writes the label and the option that goes with it. + /// + /// The label. + /// The option. + public override void WriteLabel(string label, object option) + { + WriteLabel(label, option, ColorStyle.Value); + } + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + public override void WriteLabelLine(string label, object option) + { + WriteLabelLine(label, option, ColorStyle.Value); + } + + /// + /// Writes the label and the option that goes with it and optionally writes a new line. + /// + /// The label. + /// The option. + /// The color to display the value with + public override void WriteLabel(string label, object option, ColorStyle valueStyle) + { + Write(ColorStyle.Label, label); + Write(valueStyle, option == null ? "" : option.ToString()); + } + + /// + /// Writes the label and the option that goes with it followed by a new line. + /// + /// The label. + /// The option. + /// The color to display the value with + public override void WriteLabelLine(string label, object option, ColorStyle valueStyle) + { + WriteLabel(label, option, valueStyle); + WriteLine(); + } + + #endregion + + #region Helper Methods + + private SolidColorBrush GetBrush(ColorStyle style) + { + + if ((int)style < 0 || (int)style > 11) + style = ColorStyle.Default; + + return new SolidColorBrush(_colors[(int)style]); + } + + // Colors for each ColorStyle, in same order as enum + private static readonly Color[] _colors = new Color[] { + Colors.White, // Header + Colors.LightGray, // SubHeader + Colors.Cyan, // SectionHeader + Color.FromArgb(255,0,255,0), // Default + Colors.LightGray, // Output + Color.FromArgb(255,0,255,0), // Help + Color.FromArgb(255,0,255,0), // Label + Colors.White, // Value + Color.FromArgb(255,0,255,0), // Pass + Colors.Red, // Failure + Colors.Yellow, // Warning + Colors.Red // Error + }; + + #endregion + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/nunitlite/StringExtensions.cs b/test/NUnitLite/NUnitFramework/nunitlite/StringExtensions.cs new file mode 100644 index 000000000..26efe80e9 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/StringExtensions.cs @@ -0,0 +1,382 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if NETCF +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace System +{ + public static class StringExtensions + { + public static string ToUpperInvariant(this string s) + { + return s.ToUpper(CultureInfo.InvariantCulture); + } + + public static String[] Split(this string s, char[] separator, StringSplitOptions options) + { + return s.Split(separator, Int32.MaxValue, options); + } + + public static String[] Split(this string s, char[] separator, int count, StringSplitOptions options) + { + if (count < 0) + throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero."); + if ((options != StringSplitOptions.None) && (options != StringSplitOptions.RemoveEmptyEntries)) + throw new ArgumentException("Illegal enum value: " + options + "."); + + if (s.Length == 0 && (options & StringSplitOptions.RemoveEmptyEntries) != 0) + return EmptyArray.Value; + + if (count <= 1) + { + return count == 0 ? + EmptyArray.Value : + new String[1] { + s + }; + } + + return s.SplitByCharacters(separator, count, options != 0); + } + + public static String[] Split(this string s, string[] separator, StringSplitOptions options) + { + return s.Split(separator, Int32.MaxValue, options); + } + + public static String[] Split(this string s, string[] separator, int count, StringSplitOptions options) + { + if (count < 0) + throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero."); + if ((options != StringSplitOptions.None) && (options != StringSplitOptions.RemoveEmptyEntries)) + throw new ArgumentException("Illegal enum value: " + options + "."); + + if (count <= 1) + { + return count == 0 ? + EmptyArray.Value : + new String[1] { + s + }; + } + + bool removeEmpty = (options & StringSplitOptions.RemoveEmptyEntries) != 0; + + if (separator == null || separator.Length == 0) + return s.SplitByCharacters(null, count, removeEmpty); + + if (s.Length == 0 && removeEmpty) + return EmptyArray.Value; + + List arr = new List(); + + int pos = 0; + int matchCount = 0; + while (pos < s.Length) + { + int matchIndex = -1; + int matchPos = Int32.MaxValue; + + // Find the first position where any of the separators matches + for (int i = 0; i < separator.Length; ++i) + { + string sep = separator[i]; + if (sep == null || sep.Length == 0) + continue; + + int match = s.IndexOfOrdinalUnchecked(sep, pos, s.Length - pos); + if (match >= 0 && match < matchPos) + { + matchIndex = i; + matchPos = match; + } + } + + if (matchIndex == -1) + break; + + if (!(matchPos == pos && removeEmpty)) + { + if (arr.Count == count - 1) + break; + arr.Add(s.Substring(pos, matchPos - pos)); + } + + pos = matchPos + separator[matchIndex].Length; + + matchCount++; + } + + if (matchCount == 0) + return new String[] { s }; + + // string contained only separators + if (removeEmpty && matchCount != 0 && pos == s.Length && arr.Count == 0) + return EmptyArray.Value; + + if (!(removeEmpty && pos == s.Length)) + arr.Add(s.Substring(pos)); + + return arr.ToArray(); + } + + static readonly char[] WhiteChars = { + (char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, + (char) 0x85, (char) 0x1680, (char) 0x2028, (char) 0x2029, + (char) 0x20, (char) 0xA0, (char) 0x2000, (char) 0x2001, (char) 0x2002, (char) 0x2003, (char) 0x2004, + (char) 0x2005, (char) 0x2006, (char) 0x2007, (char) 0x2008, (char) 0x2009, (char) 0x200A, (char) 0x200B, + (char) 0x3000, (char) 0xFEFF + }; + + unsafe static string[] SplitByCharacters(this string s, char[] sep, int count, bool removeEmpty) + { + if (sep == null || sep.Length == 0) + sep = WhiteChars; + + int[] split_points = null; + int total_points = 0; + --count; + + if (sep == null || sep.Length == 0) + { + fixed(char* src = s) + { + char* src_ptr = src; + int len = s.Length; + + while (len > 0) + { + if (char.IsWhiteSpace(*src_ptr++)) + { + if (split_points == null) + split_points = new int[8]; + else if (split_points.Length == total_points) + Array.Resize(ref split_points, split_points.Length * 2); + + split_points[total_points++] = s.Length - len; + if (total_points == count && !removeEmpty) + break; + } + --len; + } + } + } + else + { + fixed(char* src = s) + { + fixed(char* sep_src = sep) + { + char* src_ptr = src; + char* sep_ptr_end = sep_src + sep.Length; + int len = s.Length; + while (len > 0) + { + char* sep_ptr = sep_src; + do + { + if (*sep_ptr++ == *src_ptr) + { + if (split_points == null) + split_points = new int[8]; + else if (split_points.Length == total_points) + Array.Resize(ref split_points, split_points.Length * 2); + + split_points[total_points++] = s.Length - len; + if (total_points == count && !removeEmpty) + len = 0; + + break; + } + } while (sep_ptr != sep_ptr_end); + + ++src_ptr; + --len; + } + } + } + } + + if (total_points == 0) + return new string[] { s }; + + var res = new string[Math.Min(total_points, count) + 1]; + int prev_index = 0; + int i = 0; + if (!removeEmpty) + { + for (; i < total_points; ++i) + { + var start = split_points[i]; + res[i] = s.SubstringUnchecked(prev_index, start - prev_index); + prev_index = start + 1; + } + + res[i] = s.SubstringUnchecked(prev_index, s.Length - prev_index); + } + else + { + int used = 0; + int length; + for (; i < total_points; ++i) + { + var start = split_points[i]; + length = start - prev_index; + if (length != 0) + { + if (used == count) + break; + + res[used++] = s.SubstringUnchecked(prev_index, length); + } + + prev_index = start + 1; + } + + length = s.Length - prev_index; + if (length != 0) + res[used++] = s.SubstringUnchecked(prev_index, length); + + if (used != res.Length) + Array.Resize(ref res, used); + } + + return res; + } + + internal static String SubstringUnchecked(this string s, int startIndex, int length) + { + return s.Substring(startIndex, length); + /* + if (length == 0) + return String.Empty; + + string tmp = InternalAllocateStr (length); + fixed (char* dest = tmp, src = s) + { + CharCopy (dest, src + startIndex, length); + } + return tmp; + */ + } + + internal static unsafe int IndexOfOrdinalUnchecked(this string s, string value) + { + return s.IndexOfOrdinalUnchecked(value, 0, s.Length); + } + + internal static unsafe int IndexOfOrdinalUnchecked(this string s, string value, int startIndex, int count) + { + int valueLen = value.Length; + if (count < valueLen) + return -1; + + if (valueLen <= 1) + { + if (valueLen == 1) + return s.IndexOfUnchecked(value[0], startIndex, count); + return startIndex; + } + + fixed(char* thisptr = s, valueptr = value) + { + char* ap = thisptr + startIndex; + char* thisEnd = ap + count - valueLen + 1; + while (ap != thisEnd) + { + if (*ap == *valueptr) + { + for (int i = 1; i < valueLen; i++) + { + if (ap[i] != valueptr[i]) + goto NextVal; + } + return (int)(ap - thisptr); + } +NextVal: + ap++; + } + } + return -1; + } + + internal static unsafe int IndexOfUnchecked(this string s, char value, int startIndex, int count) + { + // It helps JIT compiler to optimize comparison + int value_32 = (int)value; + + fixed(char* start = s) + { + char* ptr = start + startIndex; + char* end_ptr = ptr + (count >> 3 << 3); + + while (ptr != end_ptr) + { + if (*ptr == value_32) + return (int)(ptr - start); + if (ptr[1] == value_32) + return (int)(ptr - start + 1); + if (ptr[2] == value_32) + return (int)(ptr - start + 2); + if (ptr[3] == value_32) + return (int)(ptr - start + 3); + if (ptr[4] == value_32) + return (int)(ptr - start + 4); + if (ptr[5] == value_32) + return (int)(ptr - start + 5); + if (ptr[6] == value_32) + return (int)(ptr - start + 6); + if (ptr[7] == value_32) + return (int)(ptr - start + 7); + + ptr += 8; + } + + end_ptr += count & 0x07; + while (ptr != end_ptr) + { + if (*ptr == value_32) + return (int)(ptr - start); + + ptr++; + } + return -1; + } + } + + } +} + +namespace System +{ + public static class EmptyArray + { + public static readonly T[] Value = new T[0]; + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/nunitlite/StringSplitOptions.cs b/test/NUnitLite/NUnitFramework/nunitlite/StringSplitOptions.cs new file mode 100644 index 000000000..13fadcffc --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/StringSplitOptions.cs @@ -0,0 +1,36 @@ +// +// System.StringSplitOptions.cs +// +// Copyright (C) 2004-2005 Novell (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +#if NETCF +namespace System +{ + [Flags] + public enum StringSplitOptions + { + None = 0, + RemoveEmptyEntries = 1 + } +} +#endif diff --git a/test/NUnitLite/src/framework/Runner/TcpWriter.cs b/test/NUnitLite/NUnitFramework/nunitlite/TcpWriter.cs similarity index 98% rename from test/NUnitLite/src/framework/Runner/TcpWriter.cs rename to test/NUnitLite/NUnitFramework/nunitlite/TcpWriter.cs index 2279f572a..818f5e16e 100644 --- a/test/NUnitLite/src/framework/Runner/TcpWriter.cs +++ b/test/NUnitLite/NUnitFramework/nunitlite/TcpWriter.cs @@ -21,12 +21,13 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** +#if false using System; using System.IO; using System.Net.Sockets; using System.Text; -namespace NUnitLite.Runner +namespace NUnitLite { /// /// Redirects output to a Tcp connection @@ -71,3 +72,4 @@ public override System.Text.Encoding Encoding } } } +#endif diff --git a/test/NUnitLite/NUnitFramework/nunitlite/TeamCityEventListener.cs b/test/NUnitLite/NUnitFramework/nunitlite/TeamCityEventListener.cs new file mode 100644 index 000000000..86d364731 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/TeamCityEventListener.cs @@ -0,0 +1,159 @@ +// *********************************************************************** +// Copyright (c) 2014 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if !SILVERLIGHT && !NETCF +using System; +using System.Globalization; +using System.IO; +using NUnit.Framework.Interfaces; + +namespace NUnitLite +{ + /// + /// TeamCityEventListener class handles ITestListener events + /// by issuing TeamCity service messages on the Console. + /// + public class TeamCityEventListener : ITestListener + { + readonly TextWriter _outWriter; + +#if !PORTABLE + /// + /// Default constructor using Console.Out + /// + /// + /// This constructor must be called before Console.Out is + /// redirected in order to work correctly under TeamCity. + /// + public TeamCityEventListener() : this(Console.Out) { } +#endif + + /// + /// Construct a TeamCityEventListener specifying a TextWriter. Used for testing. + /// + /// The TextWriter to receive normal messages. + public TeamCityEventListener(TextWriter outWriter) + { + _outWriter = outWriter; + } + + /// + /// Called when a test has just started + /// + /// The test that is starting + public void TestStarted(ITest test) + { + if (test.IsSuite) + TC_TestSuiteStarted(test.Name); + else + TC_TestStarted(test.Name); + } + + /// + /// Called when a test has finished + /// + /// The result of the test + public void TestFinished(ITestResult result) + { + string testName = result.Test.Name; + + if (result.Test.IsSuite) + TC_TestSuiteFinished(testName); + else + switch (result.ResultState.Status) + { + case TestStatus.Passed: + TC_TestFinished(testName, result.Duration); + break; + case TestStatus.Inconclusive: + TC_TestIgnored(testName, "Inconclusive"); + break; + case TestStatus.Skipped: + TC_TestIgnored(testName, result.Message); + break; + case TestStatus.Failed: + TC_TestFailed(testName, result.Message, result.StackTrace); + TC_TestFinished(testName, result.Duration); + break; + } + } + + /// + /// Called when a test produces output for immediate display + /// + /// A TestOutput object containing the text to display + public void TestOutput(TestOutput output) { } + +#region Helper Methods + + private void TC_TestSuiteStarted(string name) + { + _outWriter.WriteLine("##teamcity[testSuiteStarted name='{0}']", Escape(name)); + } + + private void TC_TestSuiteFinished(string name) + { + _outWriter.WriteLine("##teamcity[testSuiteFinished name='{0}']", Escape(name)); + } + + private void TC_TestStarted(string name) + { + _outWriter.WriteLine("##teamcity[testStarted name='{0}' captureStandardOutput='true']", Escape(name)); + } + + private void TC_TestFinished(string name, double duration) + { + // TeamCity expects the duration to be in milliseconds + int milliseconds = (int)(duration * 1000d); + _outWriter.WriteLine("##teamcity[testFinished name='{0}' duration='{1}']", Escape(name), milliseconds); + } + + private void TC_TestIgnored(string name, string reason) + { + _outWriter.WriteLine("##teamcity[testIgnored name='{0}' message='{1}']", Escape(name), Escape(reason)); + } + + private void TC_TestFailed(string name, string message, string details) + { + _outWriter.WriteLine("##teamcity[testFailed name='{0}' message='{1}' details='{2}']", Escape(name), Escape(message), Escape(details)); + } + + private static string Escape(string input) + { + return input != null + ? input.Replace("|", "||") + .Replace("'", "|'") + .Replace("\n", "|n") + .Replace("\r", "|r") + .Replace(char.ConvertFromUtf32(int.Parse("0086", NumberStyles.HexNumber)), "|x") + .Replace(char.ConvertFromUtf32(int.Parse("2028", NumberStyles.HexNumber)), "|l") + .Replace(char.ConvertFromUtf32(int.Parse("2029", NumberStyles.HexNumber)), "|p") + .Replace("[", "|[") + .Replace("]", "|]") + : null; + } + +#endregion + } +} +#endif diff --git a/test/NUnitLite/NUnitFramework/nunitlite/TestNameParser.cs b/test/NUnitLite/NUnitFramework/nunitlite/TestNameParser.cs new file mode 100644 index 000000000..dc3e388a0 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/TestNameParser.cs @@ -0,0 +1,108 @@ +// *********************************************************************** +// Copyright (c) 2011 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System.Collections.Generic; + +namespace NUnit.Common +{ + /// + /// TestNameParser is used to parse the arguments to the + /// -run option, separating testnames at the correct point. + /// + public class TestNameParser + { + /// + /// Parse the -run argument and return an array of argument + /// + /// argument + /// + public static string[] Parse(string argument) + { + List list = new List(); + + int index = 0; + while (index < argument.Length) + { + string name = GetTestName(argument, ref index); + if (name != null && name != string.Empty) + list.Add(name); + } + + return list.ToArray(); + } + + private static string GetTestName(string argument, ref int index) + { + int separator = GetSeparator(argument, index); + string result; + + if (separator >= 0) + { + result = argument.Substring(index, separator - index).Trim(); + index = separator + 1; + } + else + { + result = argument.Substring(index).Trim(); + index = argument.Length; + } + + return result; + } + + private static int GetSeparator(string argument, int index) + { + int nest = 0; + + while (index < argument.Length) + { + switch (argument[index]) + { + case ',': + if (nest == 0) + return index; + break; + + case '"': + while (++index < argument.Length && argument[index] != '"') + ; + break; + + case '(': + case '<': + nest++; + break; + + case ')': + case '>': + nest--; + break; + } + + index++; + } + + return -1; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/TestSelectionParser.cs b/test/NUnitLite/NUnitFramework/nunitlite/TestSelectionParser.cs new file mode 100644 index 000000000..8f7583377 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/TestSelectionParser.cs @@ -0,0 +1,280 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Text; + +// Missing XML Docs +#pragma warning disable 1591 + +namespace NUnit.Common +{ + public class TestSelectionParser + { + private Tokenizer _tokenizer; + + private static readonly Token LPAREN = new Token(TokenKind.Symbol, "("); + private static readonly Token RPAREN = new Token(TokenKind.Symbol, ")"); + private static readonly Token AND_OP1 = new Token(TokenKind.Symbol, "&"); + private static readonly Token AND_OP2 = new Token(TokenKind.Symbol, "&&"); + private static readonly Token AND_OP3 = new Token(TokenKind.Word, "and"); + private static readonly Token AND_OP4 = new Token(TokenKind.Word, "AND"); + private static readonly Token OR_OP1 = new Token(TokenKind.Symbol, "|"); + private static readonly Token OR_OP2 = new Token(TokenKind.Symbol, "||"); + private static readonly Token OR_OP3 = new Token(TokenKind.Word, "or"); + private static readonly Token OR_OP4 = new Token(TokenKind.Word, "OR"); + private static readonly Token NOT_OP = new Token(TokenKind.Symbol, "!"); + + private static readonly Token EQ_OP1 = new Token(TokenKind.Symbol, "="); + private static readonly Token EQ_OP2 = new Token(TokenKind.Symbol, "=="); + private static readonly Token NE_OP = new Token(TokenKind.Symbol, "!="); + private static readonly Token MATCH_OP = new Token(TokenKind.Symbol, "=~"); + private static readonly Token NOMATCH_OP = new Token(TokenKind.Symbol, "!~"); + + private static readonly Token[] AND_OPS = new Token[] { AND_OP1, AND_OP2, AND_OP3, AND_OP4 }; + private static readonly Token[] OR_OPS = new Token[] { OR_OP1, OR_OP2, OR_OP3, OR_OP4 }; + private static readonly Token[] EQ_OPS = new Token[] { EQ_OP1, EQ_OP2 }; + private static readonly Token[] REL_OPS = new Token[] { EQ_OP1, EQ_OP2, NE_OP, MATCH_OP, NOMATCH_OP }; + + private static readonly Token EOF = new Token(TokenKind.Eof); + + public string Parse(string input) + { + _tokenizer = new Tokenizer(input); + + if (_tokenizer.LookAhead == EOF) + throw new TestSelectionParserException("No input provided for test selection."); + + var result = ParseFilterExpression(); + + Expect(EOF); + return result; + } + + /// + /// Parse a single term or an or expression, returning the xml + /// + /// + public string ParseFilterExpression() + { + var terms = new List(); + terms.Add(ParseFilterTerm()); + + while (LookingAt(OR_OPS)) + { + NextToken(); + terms.Add(ParseFilterTerm()); + } + + if (terms.Count == 1) + return terms[0]; + + var sb = new StringBuilder(""); + + foreach (string term in terms) + sb.Append(term); + + sb.Append(""); + + return sb.ToString(); + } + + /// + /// Parse a single element or an and expression and return the xml + /// + public string ParseFilterTerm() + { + var elements = new List(); + elements.Add(ParseFilterElement()); + + while (LookingAt(AND_OPS)) + { + NextToken(); + elements.Add(ParseFilterElement()); + } + + if (elements.Count == 1) + return elements[0]; + + var sb = new StringBuilder(""); + + foreach (string element in elements) + sb.Append(element); + + sb.Append(""); + + return sb.ToString(); + } + + /// + /// Parse a single filter element such as a category expression + /// and return the xml representation of the filter. + /// + public string ParseFilterElement() + { + if (LookingAt(LPAREN, NOT_OP)) + return ParseExpressionInParentheses(); + + Token lhs = Expect(TokenKind.Word); + + switch (lhs.Text) + { + case "id": + case "cat": + case "method": + case "class": + case "name": + case "test": + Token op = lhs.Text == "id" + ? Expect(EQ_OPS) + : Expect(REL_OPS); + Token rhs = Expect(TokenKind.String, TokenKind.Word); + return EmitFilterElement(lhs, op, rhs); + + default: + // Assume it's a property name + op = Expect(REL_OPS); + rhs = Expect(TokenKind.String, TokenKind.Word); + return EmitPropertyElement(lhs, op, rhs); + //throw InvalidTokenError(lhs); + } + } + + private static string EmitFilterElement(Token lhs, Token op, Token rhs) + { + string fmt = null; + + if (op == EQ_OP1 || op == EQ_OP2) + fmt = "<{0}>{1}"; + else if (op == NE_OP) + fmt = "<{0}>{1}"; + else if (op == MATCH_OP) + fmt = "<{0} re='1'>{1}"; + else if (op == NOMATCH_OP) + fmt = "<{0} re='1'>{1}"; + else + fmt = "<{0} op='" + op.Text + "'>{1}"; + + return EmitElement(fmt, lhs, rhs); + } + + private static string EmitPropertyElement(Token lhs, Token op, Token rhs) + { + string fmt = null; + + if (op == EQ_OP1 || op == EQ_OP2) + fmt = "{1}"; + else if (op == NE_OP) + fmt = "{1}"; + else if (op == MATCH_OP) + fmt = "{1}"; + else if (op == NOMATCH_OP) + fmt = "{1}"; + else + fmt = "{1}"; + + return EmitElement(fmt, lhs, rhs); + } + + private static string EmitElement(string fmt, Token lhs, Token rhs) + { + return string.Format(fmt, lhs.Text, XmlEscape(rhs.Text)); + } + + private string ParseExpressionInParentheses() + { + Token op = Expect(LPAREN, NOT_OP); + + if (op == NOT_OP) Expect(LPAREN); + + string result = ParseFilterExpression(); + + Expect(RPAREN); + + if (op == NOT_OP) + result = "" + result + ""; + + return result; + } + + // Require a token of one or more kinds + private Token Expect(params TokenKind[] kinds) + { + Token token = NextToken(); + + foreach (TokenKind kind in kinds) + if (token.Kind == kind) + return token; + + throw InvalidTokenError(token); + } + + // Require a token from a list of tokens + private Token Expect(params Token[] valid) + { + Token token = NextToken(); + + foreach (Token item in valid) + if (token == item) + return token; + + throw InvalidTokenError(token); + } + + private Exception InvalidTokenError(Token token) + { + return new TestSelectionParserException(string.Format( + "Unexpected token '{0}' at position {1} in selection expression.", token.Text, token.Pos)); + } + + private Token LookAhead + { + get { return _tokenizer.LookAhead; } + } + + private bool LookingAt(params Token[] tokens) + { + foreach (Token token in tokens) + if (LookAhead == token) + return true; + + return false; + } + + private Token NextToken() + { + return _tokenizer.NextToken(); + } + + private static string XmlEscape(string text) + { + return text + .Replace("&", "&") + .Replace("\"", """) + .Replace("<", "<") + .Replace(">", ">") + .Replace("'", "'"); + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/TestSelectionParserException.cs b/test/NUnitLite/NUnitFramework/nunitlite/TestSelectionParserException.cs new file mode 100644 index 000000000..ef6694d7b --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/TestSelectionParserException.cs @@ -0,0 +1,57 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Runtime.Serialization; + +namespace NUnit.Common +{ + /// + /// TestSelectionParserException is thrown when an error + /// is found while parsing the selection expression. + /// +#if !SILVERLIGHT && !PORTABLE + [Serializable] +#endif + public class TestSelectionParserException : Exception + { + /// + /// Construct with a message + /// + public TestSelectionParserException(string message) : base(message) { } + + /// + /// Construct with a message and inner exception + /// + /// + /// + public TestSelectionParserException(string message, Exception innerException) : base(message, innerException) { } + +#if !NETCF && !SILVERLIGHT && !PORTABLE + /// + /// Serialization constructor + /// + public TestSelectionParserException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/TextRunner.cs b/test/NUnitLite/NUnitFramework/nunitlite/TextRunner.cs new file mode 100644 index 000000000..a1d55978e --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/TextRunner.cs @@ -0,0 +1,488 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using NUnit.Common; +using NUnit; +using NUnit.Framework.Api; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Filters; + +namespace NUnitLite +{ + /// + /// TextRunner is a general purpose class that runs tests and + /// outputs to a text-based user interface (TextUI). + /// + /// Call it from your Main like this: + /// new TextRunner(textWriter).Execute(args); + /// OR + /// new TextUI().Execute(args); + /// The provided TextWriter is used by default, unless the + /// arguments to Execute override it using -out. The second + /// form uses the Console, provided it exists on the platform. + /// + /// NOTE: When running on a platform without a Console, such + /// as Windows Phone, the results will simply not appear if + /// you fail to specify a file in the call itself or as an option. + /// + public class TextRunner : ITestListener + { + #region Runner Return Codes + + /// OK + public const int OK = 0; + /// Invalid Arguments + public const int INVALID_ARG = -1; + /// File not found + public const int FILE_NOT_FOUND = -2; + /// Test fixture not found - No longer in use + //public const int FIXTURE_NOT_FOUND = -3; + /// Invalid test suite + public const int INVALID_TEST_FIXTURE = -4; + /// Unexpected error occurred + public const int UNEXPECTED_ERROR = -100; + + #endregion + + private Assembly _testAssembly; + private readonly List _assemblies = new List(); + private ITestAssemblyRunner _runner; + + private NUnitLiteOptions _options; + private ITestListener _teamCity = null; + + private TextUI _textUI; + +#if SILVERLIGHT + private List _results = new List(); +#endif + + #region Constructors + + //// + //// Initializes a new instance of the class. + //// + public TextRunner() { } + + /// + /// Initializes a new instance of the class + /// specifying a test assembly whose tests are to be run. + /// + /// + /// + public TextRunner(Assembly testAssembly) + { + _testAssembly = testAssembly; + } + + #endregion + + #region Properties + + public ResultSummary Summary { get; private set; } + + #endregion + + #region Public Methods + +#if !SILVERLIGHT && !PORTABLE + public int Execute(string[] args) + { + var options = new NUnitLiteOptions(args); + + InitializeInternalTrace(options); + + ExtendedTextWriter outWriter = null; + if (options.OutFile != null) + { + outWriter = new ExtendedTextWrapper(TextWriter.Synchronized(new StreamWriter(Path.Combine(options.WorkDirectory, options.OutFile)))); + Console.SetOut(outWriter); + } + else + { + outWriter = new ColorConsoleWriter(); + } + + TextWriter errWriter = null; + if (options.ErrFile != null) + { + errWriter = TextWriter.Synchronized(new StreamWriter(Path.Combine(options.WorkDirectory, options.ErrFile))); + Console.SetError(errWriter); + } + + try + { + return Execute(outWriter, Console.In, options); + } + finally + { + if (options.OutFile != null && outWriter != null) + outWriter.Close(); + + if (options.ErrFile != null && errWriter != null) + errWriter.Close(); + } + } +#endif + + public int Execute(ExtendedTextWriter writer, TextReader reader, string[] args) + { + return Execute(writer, reader, new NUnitLiteOptions(args)); + } + + public int Execute(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options) + { + var textUI = new TextUI(writer, reader, options); + return Execute(textUI, options); + } + + /// + /// Execute a test run + /// + /// The assembly from which tests are loaded + public int Execute(TextUI textUI, NUnitLiteOptions options) + { + _textUI = textUI; + _options = options; + _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); + + try + { +#if !SILVERLIGHT +#if !PORTABLE + if (!Directory.Exists(_options.WorkDirectory)) + Directory.CreateDirectory(_options.WorkDirectory); +#endif + +#if !NETCF + if (_options.TeamCity) + _teamCity = new TeamCityEventListener(_textUI.Writer); +#endif +#endif + + + if (_options.ShowVersion || !_options.NoHeader) + _textUI.DisplayHeader(); + + if (_options.ShowHelp) + { + _textUI.DisplayHelp(); + return TextRunner.OK; + } + + // We already showed version as a part of the header + if (_options.ShowVersion) + return TextRunner.OK; + + if (_options.ErrorMessages.Count > 0) + { + _textUI.DisplayErrors(_options.ErrorMessages); + _textUI.DisplayHelp(); + + return TextRunner.INVALID_ARG; + } + + _textUI.DisplayRuntimeEnvironment(); + + var testFile = _testAssembly != null + ? AssemblyHelper.GetAssemblyPath(_testAssembly) + : _options.InputFiles.Count > 0 + ? _options.InputFiles[0] + : null; + + if (testFile != null) + { + _textUI.DisplayTestFiles(new string[] { testFile }); + if (_testAssembly == null) + _testAssembly = AssemblyHelper.Load(testFile); + } + + + if (_options.WaitBeforeExit && _options.OutFile != null) + _textUI.DisplayWarning("Ignoring /wait option - only valid for Console"); + + foreach (string nameOrPath in _options.InputFiles) + _assemblies.Add(AssemblyHelper.Load(nameOrPath)); + + var runSettings = MakeRunSettings(_options); + + // We display the filters at this point so that any exception message + // thrown by CreateTestFilter will be understandable. + _textUI.DisplayTestFilters(); + + TestFilter filter = CreateTestFilter(_options); + + _runner.Load(_testAssembly, runSettings); + return _options.Explore ? ExploreTests() : RunTests(filter, runSettings); + } + catch (FileNotFoundException ex) + { + _textUI.DisplayError(ex.Message); + return FILE_NOT_FOUND; + } + catch (Exception ex) + { + _textUI.DisplayError(ex.ToString()); + return UNEXPECTED_ERROR; + } +#if !SILVERLIGHT + finally + { + if (_options.WaitBeforeExit) + _textUI.WaitForUser("Press Enter key to continue . . ."); + } +#endif + } + +#endregion + + #region Helper Methods + + public int RunTests(TestFilter filter, IDictionary runSettings) + { + var startTime = DateTime.UtcNow; + + ITestResult result = _runner.Run(this, filter); + +#if SILVERLIGHT + // Silverlight can't display results while the test is running + // so we do it afterwards. + foreach(ITestResult testResult in _results) + _textUI.TestFinished(testResult); +#endif + ReportResults(result); + +#if !SILVERLIGHT && !PORTABLE + if (_options.ResultOutputSpecifications.Count > 0) + { + var outputManager = new OutputManager(_options.WorkDirectory); + + foreach (var spec in _options.ResultOutputSpecifications) + outputManager.WriteResultFile(result, spec, runSettings, filter); + } +#endif + if (Summary.InvalidTestFixtures > 0) + return INVALID_TEST_FIXTURE; + + return Summary.FailureCount + Summary.ErrorCount + Summary.InvalidCount; + } + + public void ReportResults(ITestResult result) + { + Summary = new ResultSummary(result); + + if (Summary.ExplicitCount + Summary.SkipCount + Summary.IgnoreCount > 0) + _textUI.DisplayNotRunReport(result); + + if (result.ResultState.Status == TestStatus.Failed) + _textUI.DisplayErrorsAndFailuresReport(result); + +#if FULL + if (_options.Full) + _textUI.PrintFullReport(_result); +#endif + + _textUI.DisplayRunSettings(); + + _textUI.DisplaySummaryReport(Summary); + } + + private int ExploreTests() + { +#if !PORTABLE && !SILVERLIGHT + ITest testNode = _runner.LoadedTest; + + var specs = _options.ExploreOutputSpecifications; + + if (specs.Count == 0) + new TestCaseOutputWriter().WriteTestFile(testNode, Console.Out); + else + { + var outputManager = new OutputManager(_options.WorkDirectory); + + foreach (var spec in _options.ExploreOutputSpecifications) + outputManager.WriteTestFile(testNode, spec); + } +#endif + + return OK; + } + + /// + /// Make the settings for this run - this is public for testing + /// + public static Dictionary MakeRunSettings(NUnitLiteOptions options) + { + // Transfer command line options to run settings + var runSettings = new Dictionary(); + + if (options.RandomSeed >= 0) + runSettings[FrameworkPackageSettings.RandomSeed] = options.RandomSeed; + +#if !PORTABLE + if (options.WorkDirectory != null) + runSettings[FrameworkPackageSettings.WorkDirectory] = Path.GetFullPath(options.WorkDirectory); +#endif + if (options.DefaultTimeout >= 0) + runSettings[FrameworkPackageSettings.DefaultTimeout] = options.DefaultTimeout; + + if (options.StopOnError) + runSettings[FrameworkPackageSettings.StopOnError] = true; + + if (options.DefaultTestNamePattern != null) + runSettings[FrameworkPackageSettings.DefaultTestNamePattern] = options.DefaultTestNamePattern; + + return runSettings; + } + + /// + /// Create the test filter for this run - public for testing + /// + /// + /// + public static TestFilter CreateTestFilter(NUnitLiteOptions options) + { + var filter = TestFilter.Empty; + + if (options.TestList.Count > 0) + { + var testFilters = new List(); + foreach (var test in options.TestList) + testFilters.Add(new FullNameFilter(test)); + + filter = testFilters.Count > 1 + ? new OrFilter(testFilters.ToArray()) + : testFilters[0]; + } + + + if (options.WhereClauseSpecified) + { + string xmlText = new TestSelectionParser().Parse(options.WhereClause); + var whereFilter = TestFilter.FromXml(TNode.FromXml(xmlText)); + filter = filter.IsEmpty + ? whereFilter + : new AndFilter(filter, whereFilter); + } + + return filter; + } + +#if !PORTABLE && !SILVERLIGHT + private void InitializeInternalTrace(NUnitLiteOptions _options) + { + var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel ?? "Off", true); + + if (traceLevel != InternalTraceLevel.Off) + { + var logName = GetLogFileName(); + +#if NETCF // NETCF: Try to encapsulate this + InternalTrace.Initialize(Path.Combine(NUnit.Env.DocumentFolder, logName), traceLevel); +#else + StreamWriter streamWriter = null; + if (traceLevel > InternalTraceLevel.Off) + { + string logPath = Path.Combine(Environment.CurrentDirectory, logName); + streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write)); + streamWriter.AutoFlush = true; + } + InternalTrace.Initialize(streamWriter, traceLevel); +#endif + } + } + + private string GetLogFileName() + { + const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.{2}"; + + // Some mobiles don't have an Open With menu item, + // so we use .txt, which is opened easily. +#if NETCF + const string ext = "txt"; +#else + const string ext = "log"; +#endif + var baseName = _testAssembly != null + ? _testAssembly.GetName().Name + : _options.InputFiles.Count > 0 + ? Path.GetFileNameWithoutExtension(_options.InputFiles[0]) + : "NUnitLite"; + + return string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, baseName, ext); + } +#endif + + #endregion + + #region ITestListener Members + + /// + /// Called when a test or suite has just started + /// + /// The test that is starting + public void TestStarted(ITest test) + { + if (_teamCity != null) + _teamCity.TestStarted(test); + } + + /// + /// Called when a test has finished + /// + /// The result of the test + public void TestFinished(ITestResult result) + { + if (_teamCity != null) + _teamCity.TestFinished(result); + +#if !SILVERLIGHT + _textUI.TestFinished(result); +#else + // For Silverlight, we can't display the results + // until the run is completed. We don't save anything + // unless there is associated output, since that's + // the only time we display anything in Silverlight. + if (result.Output.Length > 0) + _results.Add(result); +#endif + } + + /// + /// Called when a test produces output for immediate display + /// + /// A TestOutput object containing the text to display + public void TestOutput(TestOutput output) + { + _textUI.TestOutput(output); + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/TextUI.cs b/test/NUnitLite/NUnitFramework/nunitlite/TextUI.cs new file mode 100644 index 000000000..60e974c0a --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/TextUI.cs @@ -0,0 +1,621 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Reflection; +using NUnit.Common; +using NUnit.Compatibility; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; + +namespace NUnitLite +{ + public class TextUI + { + public ExtendedTextWriter Writer { get; private set; } + + private TextReader _reader; + private NUnitLiteOptions _options; + + #region Constructors + + public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options) + { + Writer = writer; + _reader = reader; + _options = options; + } + + public TextUI(ExtendedTextWriter writer, TextReader reader) + : this(writer, reader, new NUnitLiteOptions()) { } + + public TextUI(ExtendedTextWriter writer) +#if SILVERLIGHT || PORTABLE + : this(writer, null, new NUnitLiteOptions()) { } +#else + : this(writer, Console.In, new NUnitLiteOptions()) { } +#endif + + #endregion + + #region Public Methods + + #region DisplayHeader + + /// + /// Writes the header. + /// + public void DisplayHeader() + { + Assembly executingAssembly = GetType().GetTypeInfo().Assembly; + AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly); + Version version = assemblyName.Version; + string copyright = "Copyright (C) 2016, Charlie Poole"; + string build = ""; + + var copyrightAttr = executingAssembly.GetCustomAttribute(); + if (copyrightAttr != null) + copyright = copyrightAttr.Copyright; + + var configAttr = executingAssembly.GetCustomAttribute(); + if (configAttr != null) + build = string.Format("({0})", configAttr.Configuration); + + WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build)); + WriteSubHeader(copyright); + Writer.WriteLine(); + } + + #endregion + + #region DisplayTestFiles + + public void DisplayTestFiles(IEnumerable testFiles) + { + WriteSectionHeader("Test Files"); + + foreach (string testFile in testFiles) + Writer.WriteLine(ColorStyle.Default, " " + testFile); + + Writer.WriteLine(); + } + + #endregion + + #region DisplayHelp + + public void DisplayHelp() + { + WriteHeader("Usage: NUNITLITE [assembly] [options]"); + Writer.WriteLine(); + WriteHelpLine("Runs a set of NUnitLite tests from the console."); + Writer.WriteLine(); + + WriteSectionHeader("Assembly:"); + WriteHelpLine(" An alternate assembly from which to execute tests. Normally, the tests"); + WriteHelpLine(" contained in the executable test assembly itself are run. An alternate"); + WriteHelpLine(" assembly is specified using the assembly name, without any path or."); + WriteHelpLine(" extension. It must be in the same in the same directory as the executable"); + WriteHelpLine(" or on the probing path."); + Writer.WriteLine(); + + WriteSectionHeader("Options:"); + using (var sw = new StringWriter()) + { + _options.WriteOptionDescriptions(sw); + Writer.Write(ColorStyle.Help, sw.ToString()); + } + + WriteSectionHeader("Notes:"); + WriteHelpLine(" * File names may be listed by themselves, with a relative path or "); + WriteHelpLine(" using an absolute path. Any relative path is based on the current "); + WriteHelpLine(" directory or on the Documents folder if running on a under the "); + WriteHelpLine(" compact framework."); + Writer.WriteLine(); + WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired"); + Writer.WriteLine(); + WriteHelpLine(" * Options that take values may use an equal sign or a colon"); + WriteHelpLine(" to separate the option from its value."); + Writer.WriteLine(); + WriteHelpLine(" * Several options that specify processing of XML output take"); + WriteHelpLine(" an output specification as a value. A SPEC may take one of"); + WriteHelpLine(" the following forms:"); + WriteHelpLine(" --OPTION:filename"); + WriteHelpLine(" --OPTION:filename;format=formatname"); + WriteHelpLine(" --OPTION:filename;transform=xsltfile"); + Writer.WriteLine(); + WriteHelpLine(" The --result option may use any of the following formats:"); + WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0"); + WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit"); + Writer.WriteLine(); + WriteHelpLine(" The --explore option may use any of the following formats:"); + WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0"); + WriteHelpLine(" cases - a text file listing the full names of all test cases."); + WriteHelpLine(" If --explore is used without any specification following, a list of"); + WriteHelpLine(" test cases is output to the console."); + Writer.WriteLine(); + } + + #endregion + + #region DisplayRuntimeEnvironment + + /// + /// Displays info about the runtime environment. + /// + public void DisplayRuntimeEnvironment() + { +#if !PORTABLE + WriteSectionHeader("Runtime Environment"); + Writer.WriteLabelLine(" OS Version: ", Environment.OSVersion); + Writer.WriteLabelLine(" CLR Version: ", Environment.Version); + Writer.WriteLine(); +#endif + } + + #endregion + + #region DisplayTestFilters + + public void DisplayTestFilters() + { + if (_options.TestList.Count > 0 || _options.WhereClauseSpecified) + { + WriteSectionHeader("Test Filters"); + + if (_options.TestList.Count > 0) + foreach (string testName in _options.TestList) + Writer.WriteLabelLine(" Test: ", testName); + + if (_options.WhereClauseSpecified) + Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim()); + + Writer.WriteLine(); + } + } + + #endregion + + #region DisplayRunSettings + + public void DisplayRunSettings() + { + WriteSectionHeader("Run Settings"); + + if (_options.DefaultTimeout >= 0) + Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout); + +#if PARALLEL + Writer.WriteLabelLine( + " Number of Test Workers: ", + _options.NumberOfTestWorkers >= 0 + ? _options.NumberOfTestWorkers +#if NETCF + : 2); +#else + : Math.Max(Environment.ProcessorCount, 2)); +#endif +#endif + +#if !PORTABLE + Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? NUnit.Env.DefaultWorkDirectory); +#endif + + Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off"); + + if (_options.TeamCity) + Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages"); + + Writer.WriteLine(); + } + + #endregion + + #region TestFinished + + private bool _testCreatedOutput = false; + + public void TestFinished(ITestResult result) + { + bool isSuite = result.Test.IsSuite; + + var labels = "ON"; + +#if !SILVERLIGHT + if (_options.DisplayTestLabels != null) + labels = _options.DisplayTestLabels.ToUpperInvariant(); +#endif + + if (!isSuite && labels == "ALL" || !isSuite && labels == "ON" && result.Output.Length > 0) + { + WriteLabelLine(result.Test.FullName); + } + + if (result.Output.Length > 0) + { + WriteOutputLine(result.Output); + + if (!result.Output.EndsWith("\n")) + Writer.WriteLine(); + } + + if (result.Test is TestAssembly && _testCreatedOutput) + { + Writer.WriteLine(); + _testCreatedOutput = false; + } + } + + #endregion + + #region TestOutput + + public void TestOutput(TestOutput output) + { + var labels = "ON"; + +#if !SILVERLIGHT + if (_options.DisplayTestLabels != null) + labels = _options.DisplayTestLabels.ToUpperInvariant(); +#endif + + if (labels == "ON" || labels == "All") + if (output.TestName != null) + WriteLabelLine(output.TestName); + + WriteOutputLine(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text); + } + + #endregion + + #region WaitForUser + + public void WaitForUser(string message) + { + // Ignore if we don't have a TextReader + if (_reader != null) + { + Writer.WriteLine(ColorStyle.Label, message); + _reader.ReadLine(); + } + } + + #endregion + + #region Test Result Reports + + #region DisplaySummaryReport + + public void DisplaySummaryReport(ResultSummary summary) + { + var status = summary.ResultState.Status; + + var overallResult = status.ToString(); + if (overallResult == "Skipped") + overallResult = "Warning"; + + ColorStyle overallStyle = status == TestStatus.Passed + ? ColorStyle.Pass + : status == TestStatus.Failed + ? ColorStyle.Failure + : status == TestStatus.Skipped + ? ColorStyle.Warning + : ColorStyle.Output; + + if (_testCreatedOutput) + Writer.WriteLine(); + + WriteSectionHeader("Test Run Summary"); + Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle); + + WriteSummaryCount(" Test Count: ", summary.TestCount); + WriteSummaryCount(", Passed: ", summary.PassCount); + WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure); + WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount); + WriteSummaryCount(", Skipped: ", summary.TotalSkipCount); + Writer.WriteLine(); + + if (summary.FailedCount > 0) + { + WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure); + WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error); + WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error); + Writer.WriteLine(); + } + if (summary.TotalSkipCount > 0) + { + WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning); + WriteSummaryCount(", Explicit: ", summary.ExplicitCount); + WriteSummaryCount(", Other: ", summary.SkipCount); + Writer.WriteLine(); + } + + Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u")); + Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u")); + Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration)); + Writer.WriteLine(); + } + + private void WriteSummaryCount(string label, int count) + { + Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture)); + } + + private void WriteSummaryCount(string label, int count, ColorStyle color) + { + Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value); + } + + #endregion + + #region DisplayErrorsAndFailuresReport + + public void DisplayErrorsAndFailuresReport(ITestResult result) + { + _reportIndex = 0; + WriteSectionHeader("Errors and Failures"); + DisplayErrorsAndFailures(result); + Writer.WriteLine(); + +#if !SILVERLIGHT + if (_options.StopOnError) + { + Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error"); + Writer.WriteLine(); + } +#endif + } + + #endregion + + #region DisplayNotRunReport + + public void DisplayNotRunReport(ITestResult result) + { + _reportIndex = 0; + WriteSectionHeader("Tests Not Run"); + + DisplayNotRunResults(result); + + Writer.WriteLine(); + } + + #endregion + + #region DisplayFullReport + +#if FULL // Not currently used, but may be reactivated + /// + /// Prints a full report of all results + /// + public void DisplayFullReport(ITestResult result) + { + WriteLine(ColorStyle.SectionHeader, "All Test Results -"); + _writer.WriteLine(); + + DisplayAllResults(result, " "); + + _writer.WriteLine(); + } +#endif + + #endregion + + #endregion + + #region DisplayWarning + + public void DisplayWarning(string text) + { + Writer.WriteLine(ColorStyle.Warning, text); + } + + #endregion + + #region DisplayError + + public void DisplayError(string text) + { + Writer.WriteLine(ColorStyle.Error, text); + } + + #endregion + + #region DisplayErrors + + public void DisplayErrors(IList messages) + { + foreach (string message in messages) + DisplayError(message); + } + + #endregion + + #endregion + + #region Helper Methods + + private void DisplayErrorsAndFailures(ITestResult result) + { + if (result.Test.IsSuite) + { + if (result.ResultState.Status == TestStatus.Failed) + { + var suite = result.Test as TestSuite; + var site = result.ResultState.Site; + if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown) + DisplayTestResult(result); + if (site == FailureSite.SetUp) return; + } + + foreach (ITestResult childResult in result.Children) + DisplayErrorsAndFailures(childResult); + } + else if (result.ResultState.Status == TestStatus.Failed) + DisplayTestResult(result); + } + + private void DisplayNotRunResults(ITestResult result) + { + if (result.HasChildren) + foreach (ITestResult childResult in result.Children) + DisplayNotRunResults(childResult); + else if (result.ResultState.Status == TestStatus.Skipped) + DisplayTestResult(result); + } + + private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' }; + private int _reportIndex; + + private void DisplayTestResult(ITestResult result) + { + string status = result.ResultState.Label; + if (string.IsNullOrEmpty(status)) + status = result.ResultState.Status.ToString(); + + if (status == "Failed" || status == "Error") + { + var site = result.ResultState.Site.ToString(); + if (site == "SetUp" || site == "TearDown") + status = site + " " + status; + } + + ColorStyle style = ColorStyle.Output; + switch (result.ResultState.Status) + { + case TestStatus.Failed: + style = ColorStyle.Failure; + break; + case TestStatus.Skipped: + style = status == "Ignored" ? ColorStyle.Warning : ColorStyle.Output; + break; + case TestStatus.Passed: + style = ColorStyle.Pass; + break; + } + + Writer.WriteLine(); + Writer.WriteLine( + style, string.Format("{0}) {1} : {2}", ++_reportIndex, status, result.FullName)); + + if (!string.IsNullOrEmpty(result.Message)) + Writer.WriteLine(style, result.Message.TrimEnd(TRIM_CHARS)); + + if (!string.IsNullOrEmpty(result.StackTrace)) + Writer.WriteLine(style, result.StackTrace.TrimEnd(TRIM_CHARS)); + } + +#if FULL + private void DisplayAllResults(ITestResult result, string indent) + { + string status = null; + ColorStyle style = ColorStyle.Output; + switch (result.ResultState.Status) + { + case TestStatus.Failed: + status = "FAIL"; + style = ColorStyle.Failure; + break; + case TestStatus.Skipped: + if (result.ResultState.Label == "Ignored") + { + status = "IGN "; + style = ColorStyle.Warning; + } + else + { + status = "SKIP"; + style = ColorStyle.Output; + } + break; + case TestStatus.Inconclusive: + status = "INC "; + style = ColorStyle.Output; + break; + case TestStatus.Passed: + status = "OK "; + style = ColorStyle.Pass; + break; + } + + WriteLine(style, status + indent + result.Name); + + if (result.HasChildren) + foreach (ITestResult childResult in result.Children) + PrintAllResults(childResult, indent + " "); + } +#endif + + private void WriteHeader(string text) + { + Writer.WriteLine(ColorStyle.Header, text); + } + + private void WriteSubHeader(string text) + { + Writer.WriteLine(ColorStyle.SubHeader, text); + } + + private void WriteSectionHeader(string text) + { + Writer.WriteLine(ColorStyle.SectionHeader, text); + } + + private void WriteHelpLine(string text) + { + Writer.WriteLine(ColorStyle.Help, text); + } + + private string _currentLabel; + + private void WriteLabelLine(string label) + { + if (label != _currentLabel) + { + Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label); + _testCreatedOutput = true; + _currentLabel = label; + } + } + + private void WriteOutputLine(string text) + { + WriteOutputLine(ColorStyle.Output, text); + } + + private void WriteOutputLine(ColorStyle color, string text) + { + Writer.Write(color, text); + + if (!text.EndsWith(Environment.NewLine)) + Writer.WriteLine(); + + _testCreatedOutput = true; + } + + #endregion + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/Tokenizer.cs b/test/NUnitLite/NUnitFramework/nunitlite/Tokenizer.cs new file mode 100644 index 000000000..59c0cec7b --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/Tokenizer.cs @@ -0,0 +1,251 @@ +// *********************************************************************** +// Copyright (c) 2015 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Text; + +// Missing XML Docs +#pragma warning disable 1591 + +namespace NUnit.Common +{ + public enum TokenKind + { + Eof, + Word, + String, + Symbol + } + + public class Token + { + public Token(TokenKind kind) : this(kind, string.Empty) { } + + public Token(TokenKind kind, char ch) : this(kind, ch.ToString()) { } + + public Token(TokenKind kind, string text) + { + Kind = kind; + Text = text; + } + + public TokenKind Kind { get; private set; } + + public string Text { get; private set; } + + public int Pos { get; set; } + + #region Equality Overrides + + public override bool Equals(object obj) + { + return obj is Token && this == (Token)obj; + } + + public override int GetHashCode() + { + return Text.GetHashCode(); + } + + public override string ToString() + { + return Text != null + ? Kind.ToString() + ":" + Text + : Kind.ToString(); + } + + public static bool operator ==(Token t1, Token t2) + { + bool t1Null = ReferenceEquals(t1, null); + bool t2Null = ReferenceEquals(t2, null); + + if (t1Null && t2Null) + return true; + + if (t1Null || t2Null) + return false; + + return t1.Kind == t2.Kind && t1.Text == t2.Text; + } + + public static bool operator !=(Token t1, Token t2) + { + return !(t1 == t2); + } + + #endregion + } + + /// + /// Tokenizer class performs lexical analysis for the TestSelectionParser. + /// It recognizes a very limited set of tokens: words, symbols and + /// quoted strings. This is sufficient for the simple DSL we use to + /// select which tests to run. + /// + public class Tokenizer + { + private string _input; + private int _index; + + private const char EOF_CHAR = '\0'; + private const string WORD_BREAK_CHARS = "=!()&|"; + private readonly string[] DOUBLE_CHAR_SYMBOLS = new string[] { "==", "=~", "!=", "!~", "&&", "||" }; + + private Token _lookahead; + + public Tokenizer(string input) + { + if (input == null) + throw new ArgumentNullException("input"); + + _input = input; + _index = 0; + } + + public Token LookAhead + { + get + { + if (_lookahead == null) + _lookahead = GetNextToken(); + + return _lookahead; + } + } + + public Token NextToken() + { + Token result = _lookahead ?? GetNextToken(); + _lookahead = null; + return result; + } + + private Token GetNextToken() + { + SkipBlanks(); + + var ch = NextChar; + int pos = _index; + + switch (ch) + { + case EOF_CHAR: + return new Token(TokenKind.Eof) { Pos = pos }; + + // Single char symbols + case '(': + case ')': + GetChar(); + return new Token(TokenKind.Symbol, ch) { Pos = pos }; + + // Possible double char symbols + case '&': + case '|': + case '=': + case '!': + GetChar(); + foreach(string dbl in DOUBLE_CHAR_SYMBOLS) + if (ch == dbl[0] && NextChar == dbl[1]) + { + GetChar(); + return new Token(TokenKind.Symbol, dbl) { Pos = pos }; + } + + return new Token(TokenKind.Symbol, ch); + + case '"': + case '\'': + case '/': + return GetString(); + + default: + return GetWord(); + } + } + + private bool IsWordChar(char c) + { + if (char.IsWhiteSpace(c) || c == EOF_CHAR) + return false; + + return WORD_BREAK_CHARS.IndexOf(c) < 0; + } + + private Token GetWord() + { + var sb = new StringBuilder(); + int pos = _index; + + while (IsWordChar(NextChar)) + sb.Append(GetChar()); + + return new Token(TokenKind.Word, sb.ToString()) { Pos = pos }; + } + + private Token GetString() + { + var sb = new StringBuilder(); + int pos = _index; + + char quote = GetChar(); // Save the initial quote char + + while (NextChar != EOF_CHAR) + { + var ch = GetChar(); + if (ch == '\\') + ch = GetChar(); + else if (ch == quote) + break; + sb.Append(ch); + } + + return new Token(TokenKind.String, sb.ToString()) { Pos = pos }; + } + + /// + /// Get the next character in the input, consuming it. + /// + /// The next char + private char GetChar() + { + return _index < _input.Length ? _input[_index++] : EOF_CHAR; + } + + /// + /// Peek ahead at the next character in input + /// + private char NextChar + { + get + { + return _index < _input.Length ? _input[_index] : EOF_CHAR; + } + } + + private void SkipBlanks() + { + while (char.IsWhiteSpace(NextChar)) + _index++; + } + } +} diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-2.0.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-2.0.csproj new file mode 100644 index 000000000..5e6481475 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-2.0.csproj @@ -0,0 +1,104 @@ + + + + + Debug + AnyCPU + {28C7B9D6-BE1F-45E5-952C-0D5C9CA3EFDF} + Library + Properties + NUnitLite + nunitlite + v2.0 + 512 + obj\$(Configuration)\net-2.0\ + + + true + full + false + ..\..\..\bin\Debug\net-2.0\ + TRACE;DEBUG;NET_2_0;NUNITLITE;PARALLEL + prompt + 4 + true + + + pdbonly + true + ..\..\..\bin\Release\net-2.0\ + TRACE;NET_2_0;NUNITLITE;PARALLEL + prompt + 4 + true + + + true + + + ..\..\nunit.snk + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + Code + + + + + + + + + + + + + + + + + + + + + {12B66B03-90F1-4992-BD33-BDF3C69AE49E} + nunit.framework-2.0 + + + + + nunit.snk + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-3.5.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-3.5.csproj new file mode 100644 index 000000000..52728d00c --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-3.5.csproj @@ -0,0 +1,104 @@ + + + + + Debug + AnyCPU + {82F93F6E-5C10-4CC7-BC65-AC0B9CA6D39A} + Library + Properties + NUnitLite + nunitlite + v3.5 + 512 + obj\$(Configuration)\net-3.5\ + + + true + full + false + ..\..\..\bin\Debug\net-3.5\ + TRACE;DEBUG;NET_3_5;NUNITLITE;PARALLEL + prompt + 4 + true + + + pdbonly + true + ..\..\..\bin\Release\net-3.5\ + TRACE;NET_3_5;NUNITLITE;PARALLEL + prompt + 4 + true + + + true + + + ..\..\nunit.snk + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + Code + + + + + + + + + + + + + + + + + + + + + {7FA125B4-E377-4D4C-AECB-17B934E3A4B3} + nunit.framework-3.5 + + + + + nunit.snk + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-4.0.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-4.0.csproj new file mode 100644 index 000000000..73d329fe6 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-4.0.csproj @@ -0,0 +1,103 @@ + + + + + Debug + AnyCPU + {DBD0C8B0-BE4E-4CBF-AAD4-44BEA2EA830B} + Library + Properties + NUnitLite + nunitlite + v4.0 + 512 + + obj\$(Configuration)\net-4.0\ + + + true + full + false + ..\..\..\bin\Debug\net-4.0\ + TRACE;DEBUG;NET_4_0;NUNITLITE;PARALLEL + prompt + 4 + true + + + pdbonly + true + ..\..\..\bin\Release\net-4.0\ + TRACE;NET_4_0;NUNITLITE;PARALLEL + prompt + 4 + true + + + true + + + ..\..\nunit.snk + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {6A281C98-B74D-403B-8536-966871B992E3} + nunit.framework-4.0 + + + + + nunit.snk + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-4.5.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-4.5.csproj new file mode 100644 index 000000000..5a1980cae --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-4.5.csproj @@ -0,0 +1,105 @@ + + + + + Debug + AnyCPU + {46EC0BC1-8F51-4B4D-B967-2EE452EA68FC} + Library + Properties + NUnitLite + nunitlite + v4.5 + 512 + + obj\$(Configuration)\net-4.5\ + + + true + full + false + ..\..\..\bin\Debug\net-4.5\ + TRACE;DEBUG;NET_4_5;NUNITLITE;PARALLEL + prompt + 4 + true + false + + + pdbonly + true + ..\..\..\bin\Release\net-4.5\ + TRACE;NET_4_5;NUNITLITE;PARALLEL + prompt + 4 + true + false + + + true + + + ..\..\nunit.snk + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {D209C368-1277-4EA6-A887-AA6EBA51AB99} + nunit.framework-4.5 + + + + + nunit.snk + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-netcf-3.5.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-netcf-3.5.csproj new file mode 100644 index 000000000..83e3e328e --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-netcf-3.5.csproj @@ -0,0 +1,129 @@ + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {FCB4F998-02D6-4D7F-A188-E0FB1F12F151} + Library + Properties + NUnitLite + nunitlite + {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + PocketPC + 4118C335-430C-497f-BE48-11C3316B135E + 5.1 + nunitlite.runner_netcf_3._5 + v3.5 + Windows Mobile 5.0 Pocket PC SDK + + + obj\$(Configuration)\netcf-3.5\ + true + ..\..\nunit.snk + + + + + true + full + false + ..\..\..\bin\Debug\netcf-3.5\ + TRACE;DEBUG;WindowsCE;NETCF;NETCF_3_5;NUNITLITE + true + true + prompt + 512 + 4 + true + Off + true + + + pdbonly + true + ..\..\..\bin\Release\netcf-3.5\ + TRACE;WindowsCE;NETCF;NETCF_3_5;NUNITLITE;PARALLEL + true + true + prompt + 512 + 4 + true + Off + true + + + + + + + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {B41DB8FB-0D2F-45CE-9345-AF469FC05EE8} + nunit.framework-netcf-3.5 + + + + + nunit.snk + + + + + + + + + + + + diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-portable.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-portable.csproj new file mode 100644 index 000000000..5f43a7a23 --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-portable.csproj @@ -0,0 +1,87 @@ + + + + + 10.0 + Debug + AnyCPU + {D339BFC2-AF3F-46FA-899A-14BAD4BCA35B} + Library + Properties + NUnitLite + nunitlite + Profile259 + v4.5 + 512 + {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + obj\$(Configuration)\portable\ + true + ..\..\nunit.snk + + + true + full + false + ..\..\..\bin\Debug\portable\ + TRACE;DEBUG;PORTABLE;NUNITLITE + prompt + 4 + false + true + + + pdbonly + true + ..\..\..\bin\Release\portable\ + TRACE;PORTABLE;NUNITLITE + prompt + 4 + false + true + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + + + + {D6FBBB3A-F6B8-45BB-B657-A7226AB96624} + nunit.framework-portable + + + + + nunit.snk + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-sl-5.0.csproj b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-sl-5.0.csproj new file mode 100644 index 000000000..20765708d --- /dev/null +++ b/test/NUnitLite/NUnitFramework/nunitlite/nunitlite-sl-5.0.csproj @@ -0,0 +1,141 @@ + + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {0A5F920A-1BF5-4DAC-B799-0C618B203797} + {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + NUnitLite + nunitlite + Silverlight + v5.0 + $(TargetFrameworkVersion) + false + true + true + obj\$(Configuration)\sl-5.0\ + + + + v3.5 + + + true + full + false + ..\..\..\Bin\Debug\sl-5.0\ + TRACE;DEBUG;SILVERLIGHT;SL_5_0;NUNITLITE + true + true + prompt + 4 + true + + + pdbonly + true + ..\..\..\Bin\Release\sl-5.0\ + TRACE;SILVERLIGHT;SL_5_0;NUNITLITE + true + true + prompt + 4 + true + + + true + + + ..\..\nunit.snk + + + + + True + + + + $(TargetFrameworkDirectory)System.Core.dll + + + True + + + + + + + Properties\CommonAssemblyInfo.cs + + + Properties\FrameworkVersion.cs + + + + + + + + + + + + + + + + + + + TestPage.xaml + + + + + + + + + + + + + + MSBuild:Compile + Designer + + + + + {3deb15f9-e7da-403f-b6d3-a8499310397f} + nunit.framework-sl-5.0 + + + + + nunit.snk + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/NUnitLite/NUnitLite.nuspec b/test/NUnitLite/NUnitLite.nuspec deleted file mode 100644 index 608981902..000000000 --- a/test/NUnitLite/NUnitLite.nuspec +++ /dev/null @@ -1,34 +0,0 @@ - - - - NUnitLite - ${package.version}${package.suffix} - Charlie Poole - Charlie Poole - http://nunit.org/nuget/nunitlite-license.txt - http://nunitlite.org - http://nunit.org/nuget/nunit_32x32.png - false - NUnitLite is a lightweight testing framework for .NET, based on NUnit. - NUnitLite provides a subset of the features of NUnit, uses minimal resources and runs on resource-restricted platforms used in embedded and mobile development. This packaage contains builds of NUnitLite for .NET 2.0, 3.5, 4.0 and 4.5 as well as Silverlight 5.0. How to use this package: 1. Create a console application for your tests and delete the generated class containing Main(). 2. Install the NUnitLite package, which creates a new Main() as well as adding a reference to NUnitLite. 3. Add your tests to the test project and start the project to execute them. - Copyright (c) 2004-2012 Charlie Poole - en-US - test testing tdd framework fluent assert device phone compact embedded - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/NUnitLite.sln b/test/NUnitLite/NUnitLite.sln deleted file mode 100644 index 6fca02bb6..000000000 --- a/test/NUnitLite/NUnitLite.sln +++ /dev/null @@ -1,411 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-2.0", "src\framework\nunitlite-2.0.csproj", "{C24A3FC4-2541-4E9C-BADD-564777610B75}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.tests-2.0", "src\tests\nunitlite.tests-2.0.csproj", "{C8FA4073-B24E-4178-93A1-5E1256C8B528}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestResultConsole", "src\TestResultConsole\TestResultConsole.csproj", "{8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.testdata-2.0", "src\testdata\nunitlite.testdata-2.0.csproj", "{442DAB16-3063-4FE3-90B6-C29C3D85360D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NET-2.0", "NET-2.0", "{A466054B-B601-46A2-8D7B-03DE10A94F09}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NET-3.5", "NET-3.5", "{08B11E56-AB8C-4374-8709-45631094B29B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NET-4.0", "NET-4.0", "{D0ED3F4D-113E-4858-8042-C657CAC0CF46}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-3.5", "src\framework\nunitlite-3.5.csproj", "{43B24DC5-16D6-45EF-93F1-B021B785A892}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.testdata-3.5", "src\testdata\nunitlite.testdata-3.5.csproj", "{652AFEEB-B19C-4C67-A014-2248EA72F229}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.tests-3.5", "src\tests\nunitlite.tests-3.5.csproj", "{94A4E298-F324-4531-856F-127505F766E5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-4.0", "src\framework\nunitlite-4.0.csproj", "{1567BCCE-7BE9-4815-84D7-7F794DB39081}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.testdata-4.0", "src\testdata\nunitlite.testdata-4.0.csproj", "{5C77A144-3CD1-42FC-B622-410E1945CA1E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.tests-4.0", "src\tests\nunitlite.tests-4.0.csproj", "{497A578E-EF93-4190-96E0-B7F22E08027B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{601BC853-DE7B-47EB-A92B-AEDE16A17FCF}" - ProjectSection(SolutionItems) = preProject - CHANGES.txt = CHANGES.txt - LICENSE.txt = LICENSE.txt - NOTES.txt = NOTES.txt - nunitlite.build = nunitlite.build - nunitlite.build.include = nunitlite.build.include - NUnitLite.nuspec = NUnitLite.nuspec - nunitlite.projects.common = nunitlite.projects.common - NUnitLiteCF.nuspec = NUnitLiteCF.nuspec - README.txt = README.txt - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mock-assembly-2.0", "src\mock-assembly\mock-assembly-2.0.csproj", "{1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mock-assembly-3.5", "src\mock-assembly\mock-assembly-3.5.csproj", "{1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mock-assembly-4.0", "src\mock-assembly\mock-assembly-4.0.csproj", "{961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SL-4.0", "SL-4.0", "{B4F52628-112A-4C09-A597-2DC7B5AEE818}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-sl-4.0", "src\framework\nunitlite-sl-4.0.csproj", "{41326141-EB24-4984-9D9B-5CFAA55946BA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mock-assembly-sl-4.0", "src\mock-assembly\mock-assembly-sl-4.0.csproj", "{3C1249FC-B5DF-4E3A-ADDD-817526254876}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.testdata-sl-4.0", "src\testdata\nunitlite.testdata-sl-4.0.csproj", "{E97412B5-8C91-4236-8E9A-24C8E20BC675}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.tests-sl-4.0", "src\tests\nunitlite.tests-sl-4.0.csproj", "{0B899C26-9114-440A-A8A1-615CDE7EE6BD}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SL-5.0", "SL-5.0", "{AEB97450-F9CF-4CF4-90D0-6CD5EDAB8588}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-sl-5.0", "src\framework\nunitlite-sl-5.0.csproj", "{5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mock-assembly-sl-5.0", "src\mock-assembly\mock-assembly-sl-5.0.csproj", "{3C19A734-11BB-48FD-81D0-042B6A8D4CFC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.testdata-sl-5.0", "src\testdata\nunitlite.testdata-sl-5.0.csproj", "{A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.tests-sl-5.0", "src\tests\nunitlite.tests-sl-5.0.csproj", "{7107C352-7F42-497E-A26C-25E9AAE8E54C}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SL-3.0", "SL-3.0", "{035EFB6B-82E9-4510-AC99-B586E6381B25}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite-sl-3.0", "src\framework\nunitlite-sl-3.0.csproj", "{02B02379-2596-4E45-8B10-835D62EA2D9E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mock-assembly-sl-3.0", "src\mock-assembly\mock-assembly-sl-3.0.csproj", "{BB355D2C-FB4F-4526-9B40-7944C40FDFDA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.testdata-sl-3.0", "src\testdata\nunitlite.testdata-sl-3.0.csproj", "{6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nunitlite.tests-sl-3.0", "src\tests\nunitlite.tests-sl-3.0.csproj", "{FFEA1F81-9631-43A8-8368-FBC14B1E7B02}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ci-test-runner-sl-5.0", "src\runner\ci-test-runner-sl-5.0.csproj", "{71848958-61FC-49B1-986B-CD824F9C3D9C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ci-test-runner-sl-4.0", "src\runner\ci-test-runner-sl-4.0.csproj", "{6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ci-test-runner-sl-3.0", "src\runner\ci-test-runner-sl-3.0.csproj", "{AA4E9904-77D0-406B-A50C-A0508DDB56A7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Debug|x86.ActiveCfg = Debug|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Release|Any CPU.Build.0 = Release|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {C24A3FC4-2541-4E9C-BADD-564777610B75}.Release|x86.ActiveCfg = Release|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Debug|x86.ActiveCfg = Debug|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Release|Any CPU.Build.0 = Release|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {C8FA4073-B24E-4178-93A1-5E1256C8B528}.Release|x86.ActiveCfg = Release|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Debug|x86.ActiveCfg = Debug|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Release|Any CPU.Build.0 = Release|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3}.Release|x86.ActiveCfg = Release|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Debug|x86.ActiveCfg = Debug|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Release|Any CPU.Build.0 = Release|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {442DAB16-3063-4FE3-90B6-C29C3D85360D}.Release|x86.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Any CPU.Build.0 = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Debug|x86.ActiveCfg = Debug|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Any CPU.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Any CPU.Build.0 = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {43B24DC5-16D6-45EF-93F1-B021B785A892}.Release|x86.ActiveCfg = Release|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Debug|Any CPU.Build.0 = Debug|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Debug|x86.ActiveCfg = Debug|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Release|Any CPU.ActiveCfg = Release|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Release|Any CPU.Build.0 = Release|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {652AFEEB-B19C-4C67-A014-2248EA72F229}.Release|x86.ActiveCfg = Release|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Debug|x86.ActiveCfg = Debug|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Release|Any CPU.Build.0 = Release|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {94A4E298-F324-4531-856F-127505F766E5}.Release|x86.ActiveCfg = Release|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Debug|x86.ActiveCfg = Debug|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Release|Any CPU.Build.0 = Release|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {1567BCCE-7BE9-4815-84D7-7F794DB39081}.Release|x86.ActiveCfg = Release|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Debug|x86.ActiveCfg = Debug|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Release|Any CPU.Build.0 = Release|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {5C77A144-3CD1-42FC-B622-410E1945CA1E}.Release|x86.ActiveCfg = Release|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Debug|x86.ActiveCfg = Debug|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Release|Any CPU.Build.0 = Release|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {497A578E-EF93-4190-96E0-B7F22E08027B}.Release|x86.ActiveCfg = Release|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Debug|x86.ActiveCfg = Debug|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Release|Any CPU.Build.0 = Release|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B}.Release|x86.ActiveCfg = Release|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Debug|x86.ActiveCfg = Debug|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Release|Any CPU.Build.0 = Release|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7}.Release|x86.ActiveCfg = Release|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Debug|x86.ActiveCfg = Debug|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Release|Any CPU.Build.0 = Release|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A}.Release|x86.ActiveCfg = Release|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Debug|x86.ActiveCfg = Debug|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Release|Any CPU.Build.0 = Release|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {41326141-EB24-4984-9D9B-5CFAA55946BA}.Release|x86.ActiveCfg = Release|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Debug|x86.ActiveCfg = Debug|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Release|Any CPU.Build.0 = Release|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3C1249FC-B5DF-4E3A-ADDD-817526254876}.Release|x86.ActiveCfg = Release|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Debug|x86.ActiveCfg = Debug|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Release|Any CPU.Build.0 = Release|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {E97412B5-8C91-4236-8E9A-24C8E20BC675}.Release|x86.ActiveCfg = Release|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Debug|x86.ActiveCfg = Debug|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Release|Any CPU.Build.0 = Release|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {0B899C26-9114-440A-A8A1-615CDE7EE6BD}.Release|x86.ActiveCfg = Release|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Debug|x86.ActiveCfg = Debug|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Release|Any CPU.Build.0 = Release|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3}.Release|x86.ActiveCfg = Release|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Debug|x86.ActiveCfg = Debug|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Release|Any CPU.Build.0 = Release|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC}.Release|x86.ActiveCfg = Release|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Debug|x86.ActiveCfg = Debug|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Release|Any CPU.Build.0 = Release|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E}.Release|x86.ActiveCfg = Release|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Debug|x86.ActiveCfg = Debug|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Release|Any CPU.Build.0 = Release|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {7107C352-7F42-497E-A26C-25E9AAE8E54C}.Release|x86.ActiveCfg = Release|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Debug|x86.ActiveCfg = Debug|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Release|Any CPU.Build.0 = Release|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {02B02379-2596-4E45-8B10-835D62EA2D9E}.Release|x86.ActiveCfg = Release|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Debug|x86.ActiveCfg = Debug|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Release|Any CPU.Build.0 = Release|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA}.Release|x86.ActiveCfg = Release|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Debug|x86.ActiveCfg = Debug|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Release|Any CPU.Build.0 = Release|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB}.Release|x86.ActiveCfg = Release|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Debug|x86.ActiveCfg = Debug|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Release|Any CPU.Build.0 = Release|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02}.Release|x86.ActiveCfg = Release|Any CPU - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Debug|Any CPU.ActiveCfg = Debug|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Debug|x86.ActiveCfg = Debug|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Debug|x86.Build.0 = Debug|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Release|Any CPU.ActiveCfg = Release|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Release|Mixed Platforms.Build.0 = Release|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Release|x86.ActiveCfg = Release|x86 - {71848958-61FC-49B1-986B-CD824F9C3D9C}.Release|x86.Build.0 = Release|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Debug|Any CPU.ActiveCfg = Debug|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Debug|x86.ActiveCfg = Debug|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Debug|x86.Build.0 = Debug|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Release|Any CPU.ActiveCfg = Release|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Release|Mixed Platforms.Build.0 = Release|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Release|x86.ActiveCfg = Release|x86 - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA}.Release|x86.Build.0 = Release|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Debug|Any CPU.ActiveCfg = Debug|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Debug|x86.ActiveCfg = Debug|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Debug|x86.Build.0 = Debug|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Release|Any CPU.ActiveCfg = Release|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Release|Mixed Platforms.Build.0 = Release|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Release|x86.ActiveCfg = Release|x86 - {AA4E9904-77D0-406B-A50C-A0508DDB56A7}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {C8FA4073-B24E-4178-93A1-5E1256C8B528} = {A466054B-B601-46A2-8D7B-03DE10A94F09} - {442DAB16-3063-4FE3-90B6-C29C3D85360D} = {A466054B-B601-46A2-8D7B-03DE10A94F09} - {C24A3FC4-2541-4E9C-BADD-564777610B75} = {A466054B-B601-46A2-8D7B-03DE10A94F09} - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B} = {A466054B-B601-46A2-8D7B-03DE10A94F09} - {43B24DC5-16D6-45EF-93F1-B021B785A892} = {08B11E56-AB8C-4374-8709-45631094B29B} - {652AFEEB-B19C-4C67-A014-2248EA72F229} = {08B11E56-AB8C-4374-8709-45631094B29B} - {94A4E298-F324-4531-856F-127505F766E5} = {08B11E56-AB8C-4374-8709-45631094B29B} - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7} = {08B11E56-AB8C-4374-8709-45631094B29B} - {1567BCCE-7BE9-4815-84D7-7F794DB39081} = {D0ED3F4D-113E-4858-8042-C657CAC0CF46} - {5C77A144-3CD1-42FC-B622-410E1945CA1E} = {D0ED3F4D-113E-4858-8042-C657CAC0CF46} - {497A578E-EF93-4190-96E0-B7F22E08027B} = {D0ED3F4D-113E-4858-8042-C657CAC0CF46} - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A} = {D0ED3F4D-113E-4858-8042-C657CAC0CF46} - {41326141-EB24-4984-9D9B-5CFAA55946BA} = {B4F52628-112A-4C09-A597-2DC7B5AEE818} - {3C1249FC-B5DF-4E3A-ADDD-817526254876} = {B4F52628-112A-4C09-A597-2DC7B5AEE818} - {E97412B5-8C91-4236-8E9A-24C8E20BC675} = {B4F52628-112A-4C09-A597-2DC7B5AEE818} - {0B899C26-9114-440A-A8A1-615CDE7EE6BD} = {B4F52628-112A-4C09-A597-2DC7B5AEE818} - {6414BA5A-8CB7-4022-AABB-7E38BB6DB5EA} = {B4F52628-112A-4C09-A597-2DC7B5AEE818} - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3} = {AEB97450-F9CF-4CF4-90D0-6CD5EDAB8588} - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC} = {AEB97450-F9CF-4CF4-90D0-6CD5EDAB8588} - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E} = {AEB97450-F9CF-4CF4-90D0-6CD5EDAB8588} - {7107C352-7F42-497E-A26C-25E9AAE8E54C} = {AEB97450-F9CF-4CF4-90D0-6CD5EDAB8588} - {71848958-61FC-49B1-986B-CD824F9C3D9C} = {AEB97450-F9CF-4CF4-90D0-6CD5EDAB8588} - {02B02379-2596-4E45-8B10-835D62EA2D9E} = {035EFB6B-82E9-4510-AC99-B586E6381B25} - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA} = {035EFB6B-82E9-4510-AC99-B586E6381B25} - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB} = {035EFB6B-82E9-4510-AC99-B586E6381B25} - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02} = {035EFB6B-82E9-4510-AC99-B586E6381B25} - {AA4E9904-77D0-406B-A50C-A0508DDB56A7} = {035EFB6B-82E9-4510-AC99-B586E6381B25} - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = NUnitLiteTests\NUnitLiteTests.csproj - EndGlobalSection -EndGlobal diff --git a/test/NUnitLite/README.txt b/test/NUnitLite/README.txt deleted file mode 100644 index fa21f70e0..000000000 --- a/test/NUnitLite/README.txt +++ /dev/null @@ -1,154 +0,0 @@ -NUnitLite Version 1.0 - September 13, 2013 - -NUnitLite is a small-footprint implementation of much of the current NUnit framework. It is distributed in source form and is intended for use in situations where NUnit is too large or complex. In particular, it targets mobile and embedded environments as well as testing of applications that require "embedding" the framework in another piece of software, as when testing plugin architectures. - -This file provides basic information about NUnitLite. For more info see the NUnitLite web site at http://nunitlite.com. - -COPYRIGHT AND LICENSE - -NUnitLite is Copyright 2004-2013, Charlie Poole and is licensed under the MIT license. - -A copy of the license is distributed with the program in the file LICENSE.txt and is also available at http://www.opensource.org/licenses/mit-license.php. - -NUnitLite is based on ideas in NUnit, but not on the NUnit implementation. In addition, some code developed in NUnitLite was subsequently contributed to the NUnit project, where it is available under the NUnit license. Subsequently, some (but not all) of the newer NUnit features were ported back to NUnitLite. - -ATTRIBUTES - -NUnitLite supports most of the same attributes as NUnit 2.6.2. - CategoryAttribute - CombinatorialAttribute - CultureAttribute - DatapointAttribute - DatapointsAttribute - DescriptionAttribute - ExpectedExceptionAttribute - ExplicitAttribute - IgnoreAttribute - MaxTimeAttribute - PairwiseAttribute - PlatformAttribute - PropertyAttribute - RandomAttribute - RangeAttribute - SequentialAttribute - SetCultureAttribute (not available on compact framework) - SetUICultureAttribute (not available on compact framework) - SetUpAttribute - TearDownAttribute - TestAttribute - TestCaseAttribute - TestCaseSourceAttribute - TestFixtureAttribute - TestFixtureSetUpAttribute - TestFixtureTearDownAttribute - TheoryAttribute - TimeoutAttribute - ValuesAttribute - ValueSourceAttribute - -ASSERTS - -The programmer expresses expected test conditions using the Assert class. The existing functionality of most current NUnit Assert methods is supported, but the syntax has been changed to use the more extensible constraint-based format. The following methods are supported: - Assert.Pass - Assert.Fail - Assert.Ignore - Assert.Inconclusive - Assert.That - Assert.ByVal - Assert.Throws - Assert.DoesNotThrow - Assert.Catch - Assert.Null - Assert.NotNull - Assert.True - Assert.False - Assert.AreEqual - Assert.AreNotEqual - Assert.AreSame - Assert.AreNotSame - -ASSUMPTIONS - -The programmer may express assumptions in the test using Assume.That() A failure in Assume.That causes an Inconclusive result. - -CONSTRAINTS - -NUnitLite supports most of the same built-in constraints as NUnit. Users may also derive custom constraints from the abstract Constraint class. The following built-in constraints are provided: - AllItemsConstraint - AndConstraint - AssignableFromConstraint - AssignableToConstraint - AttributeConstraint - AttributeExistsConstraint - BinarySerializableConstraint (not available on compact framework) - CollectionContainsConstraint - CollectionEquivalentConstraint - CollectionOrderedConstraint - CollectionSubsetConstraint - ContainsConstraint - DelayedConstraint - EmptyCollectionConstraint - EmptyConstraint - EmptyDirectoryConstraint - EmptyStringConstraint - EndsWithConstraint - EqualConstraint - ExactCountConstraint - ExactTypeConstraint - ExceptionTypeConstraint - FalseConstraint - GreaterThanConstraint - GreaterThanOrEqualConstraint - InstanceOfTypeConstraint - LessThanConstraint - LessThanOrEqualConstraint - NaNConstraint - NoItemConstraint - NotConstraint - NullConstraint - NullOrEmptyStringConstraint - OrConstraint - PredicateConstraint - PropertyConstraint - PropertyExistsConstraint - RangeConstraint - RegexConstraint (not available on compact framework) - ReusableConstraint - SameAsConstraint - SamePathConstraint - SamePathOrUnderConstraint - SomeItemsConstraint - StartsWithConstraint - SubPathConstraint - SubstringConstraint - ThrowsConstraint - ThrowsNothingConstraint - TrueConstraint - UniqueItemsConstraint - XmlSerializableConstraint (not available on compact framework 1.0) - -Although constraints may be created using their constructors, the more usual approach is to make use of one or more of the NUnitLite SyntaxHelpers. The following helpers are provided: - - Is: Not, All, Null, True, False, Positive, Negative, NaN, Empty, Unique, - EqualTo, SameAs, GreaterThan, GreaterThanOrEqualTo, LessThan, LessThanOrEqualTo, - AtLeast, AtMost, TypeOf, InstanceOf, AssignableFrom, AssignableTo, - StringContaining, StringStarting, StringEnding, StringMatching, - EquivalentTo, SubsetOf, BinarySerializable, XmlSerializable, - Ordered, SamePath, SamePathOrUnder, InRange - - Contains: Substring, Item - - Has: No, All, Some, None,Exactly, Property, Length, Count, Message, InnerException, Member, Attribute - -Tests are loaded as a tree structure of suites, fixtures and test cases. Each fixture contains it's tests. Tests are executed in the order found, without any guarantees of ordering. A separate instance of the fixture object is created for each test case executed by NUnitLite. The embedded console runner produces a summary of tests run and lists any errors or failures. It can also save an XML representation of the test results. - -USAGE - -NUnitLite is not "installed" in your system. Instead, you should include nunitlite.dll in your project. Your test assembly should be an exe file and should reference the nunitlite assembly. If you place a call like this in your Main - new TextUI().Execute(args); -then NUnitLite will run all the tests in the test project, using the args provided. Use -help to see the available options. - -DOCUMENTATION - -NUnitLite uses the NUnit.Framework namespace, which allows relatively easy portability between NUnit and NUnitLite. Currently, there is no separate set of documentation for NUnitLite so you should use the docs for NUnit 2.6 or later in conjunction with the information in this file. - diff --git a/test/NUnitLite/nunit.snk b/test/NUnitLite/nunit.snk new file mode 100644 index 000000000..db2cc7fd3 Binary files /dev/null and b/test/NUnitLite/nunit.snk differ diff --git a/test/NUnitLite/src/TestResultConsole/AssemblyInfo.cs b/test/NUnitLite/src/TestResultConsole/AssemblyInfo.cs deleted file mode 100644 index 967586f76..000000000 --- a/test/NUnitLite/src/TestResultConsole/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("TestResultConsole.cs")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("TestResultConsole.cs")] -[assembly: AssemblyCopyright("Copyright © 2007")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("0245d9d3-40c9-47f0-a109-31131cc0ea53")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/test/NUnitLite/src/TestResultConsole/Program.cs b/test/NUnitLite/src/TestResultConsole/Program.cs deleted file mode 100644 index 3aa2c6743..000000000 --- a/test/NUnitLite/src/TestResultConsole/Program.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.IO; -using System.Net.Sockets; -using System.Text; - -namespace TestResultConsole.cs -{ - class Program - { - static int port = 9000; - - static void Main(string[] args) - { - TcpListener listener = new TcpListener(port); - - listener.Start(); - Console.WriteLine("Waiting for test to begin..."); - TcpClient client = listener.AcceptTcpClient(); - - Console.WriteLine("Connected to test runner..."); - Console.WriteLine(); - - NetworkStream ns = client.GetStream(); - TextReader rdr = new StreamReader(ns); - - try - { - while (client.Connected) - { - string data = rdr.ReadLine(); - Console.WriteLine(data); - } - } - catch (IOException e) - { - if (client.Connected) - Console.WriteLine(e.ToString()); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - - client.Close(); - listener.Stop(); - } - } -} - diff --git a/test/NUnitLite/src/TestResultConsole/TestResultConsole.csproj b/test/NUnitLite/src/TestResultConsole/TestResultConsole.csproj deleted file mode 100644 index 5ea4f5924..000000000 --- a/test/NUnitLite/src/TestResultConsole/TestResultConsole.csproj +++ /dev/null @@ -1,91 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {8CB31CE4-639A-4A34-B04D-A8CE3FEBECB3} - Exe - Properties - TestResultConsole - TestResultConsole - - - 3.5 - - - v2.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Api/ExpectedExceptionData.cs b/test/NUnitLite/src/framework/Api/ExpectedExceptionData.cs deleted file mode 100644 index cf92ff4ff..000000000 --- a/test/NUnitLite/src/framework/Api/ExpectedExceptionData.cs +++ /dev/null @@ -1,143 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Api -{ - /// - /// ExpectedExceptionData is a struct used within the framework - /// to encapsulate information about an expected exception. - /// - public struct ExpectedExceptionData - { - #region Fields - - private Type expectedExceptionType; - private string expectedExceptionName; - private string expectedMessage; - private MessageMatch matchType; - private string userMessage; - private string handlerName; - private MethodInfo exceptionHandler; - - #endregion - - #region Properties - - /// - /// The Type of any exception that is expected. - /// - public Type ExpectedExceptionType - { - get { return expectedExceptionType; } - set - { - expectedExceptionType = value; - expectedExceptionName = value.FullName; - } - } - - /// - /// The FullName of any exception that is expected - /// - public string ExpectedExceptionName - { - get { return expectedExceptionName; } - set - { - expectedExceptionName = value; - expectedExceptionType = null; - } - } - - /// - /// The Message of any exception that is expected - /// - public string ExpectedMessage - { - get { return expectedMessage; } - set { expectedMessage = value; } - } - - /// - /// The type of match to be performed on the expected message - /// - public MessageMatch MatchType - { - get { return matchType; } - set { matchType = value; } - } - - /// - /// A user message to be issued in case of error - /// - public string UserMessage - { - get { return userMessage; } - set { userMessage = value; } - } - - /// - /// The name of an alternate exception handler to be - /// used to validate the exception. - /// - public string HandlerName - { - get { return handlerName; } - set - { - handlerName = value; - exceptionHandler = null; - } - } - - #endregion - - #region Methods - - /// - /// Returns a MethodInfo for the handler to be used to - /// validate any exception thrown. - /// - /// The Type of the fixture. - /// A MethodInfo. - public MethodInfo GetExceptionHandler(Type fixtureType) - { - if (exceptionHandler == null && handlerName != null) - { - exceptionHandler = fixtureType.GetMethod( - handlerName, - BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - null, - new Type[] { typeof(System.Exception) }, - null); - } - - return exceptionHandler; - } - - #endregion - }; -} diff --git a/test/NUnitLite/src/framework/Api/IPropertyBag.cs b/test/NUnitLite/src/framework/Api/IPropertyBag.cs deleted file mode 100644 index 50095ff19..000000000 --- a/test/NUnitLite/src/framework/Api/IPropertyBag.cs +++ /dev/null @@ -1,162 +0,0 @@ -using System; - -namespace NUnit.Framework.Api -{ - /// - /// A PropertyBag represents a collection of name/value pairs - /// that allows duplicate entries with the same key. Methods - /// are provided for adding a new pair as well as for setting - /// a key to a single value. All keys are strings but values - /// may be of any type. Null values are not permitted, since - /// a null entry represents the absence of the key. - /// - /// The entries in a PropertyBag are of two kinds: those that - /// take a single value and those that take multiple values. - /// However, the PropertyBag has no knowledge of which entries - /// fall into each category and the distinction is entirely - /// up to the code using the PropertyBag. - /// - /// When working with multi-valued properties, client code - /// should use the Add method to add name/value pairs and - /// indexing to retrieve a list of all values for a given - /// key. For example: - /// - /// bag.Add("Tag", "one"); - /// bag.Add("Tag", "two"); - /// Assert.That(bag["Tag"], - /// Is.EqualTo(new string[] { "one", "two" })); - /// - /// When working with single-valued propeties, client code - /// should use the Set method to set the value and Get to - /// retrieve the value. The GetSetting methods may also be - /// used to retrieve the value in a type-safe manner while - /// also providing default. For example: - /// - /// bag.Set("Priority", "low"); - /// bag.Set("Priority", "high"); // replaces value - /// Assert.That(bag.Get("Priority"), - /// Is.EqualTo("high")); - /// Assert.That(bag.GetSetting("Priority", "low"), - /// Is.EqualTo("high")); - /// - public interface IPropertyBag : IXmlNodeBuilder, System.Collections.IEnumerable - { - /// - /// Get the number of key/value pairs in the property bag - /// - int Count { get; } - - /// - /// Adds a key/value pair to the property bag - /// - /// The key - /// The value - void Add(string key, object value); - - - /// - /// Sets the value for a key, removing any other - /// values that are already in the property set. - /// - /// - /// - void Set(string key, object value); - - /// - /// Gets a single value for a key, using the first - /// one if multiple values are present and returning - /// null if the value is not found. - /// - object Get(string key); - - /// - /// Gets a single string value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - string GetSetting(string key, string defaultValue); - - /// - /// Gets a single int value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - int GetSetting(string key, int defaultValue); - - /// - /// Gets a single boolean value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - bool GetSetting(string key, bool defaultValue); - - /// - /// Gets a single enum value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - System.Enum GetSetting(string key, System.Enum defaultValue); - - /// - /// Removes all entries for a key from the property set. - /// If the key is not found, no error occurs. - /// - /// The key for which the entries are to be removed - void Remove(string key); - - /// - /// Removes a single entry if present. If not found, - /// no error occurs. - /// - /// - /// - void Remove(string key, object value); - - /// - /// Removes a specific PropertyEntry. If the entry is not - /// found, no errr occurs. - /// - /// The property entry to remove - void Remove(PropertyEntry entry); - - /// - /// Gets a flag indicating whether the specified key has - /// any entries in the property set. - /// - /// The key to be checked - /// True if their are values present, otherwise false - bool ContainsKey(string key); - - /// - /// Gets a flag indicating whether the specified key and - /// value are present in the property set. - /// - /// The key to be checked - /// The value to be checked - /// True if the key and value are present, otherwise false - bool Contains(string key, object value); - - /// - /// Gets a flag indicating whether the specified key and - /// value are present in the property set. - /// - /// The property entry to be checked - /// True if the entry is present, otherwise false - bool Contains(PropertyEntry entry); - - /// - /// Gets or sets the list of values for a particular key - /// - /// The key for which the values are to be retrieved or set - System.Collections.IList this[string key] { get; set; } - - /// - /// Gets a collection containing all the keys in the property set - /// -#if CLR_2_0 || CLR_4_0 - System.Collections.Generic.ICollection Keys { get; } -#else - System.Collections.ICollection Keys { get; } -#endif - } -} diff --git a/test/NUnitLite/src/framework/Api/ITest.cs b/test/NUnitLite/src/framework/Api/ITest.cs deleted file mode 100644 index f66ed65d7..000000000 --- a/test/NUnitLite/src/framework/Api/ITest.cs +++ /dev/null @@ -1,107 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Api -{ - /// - /// Common interface supported by all representations - /// of a test. Only includes informational fields. - /// The Run method is specifically excluded to allow - /// for data-only representations of a test. - /// - public interface ITest : IXmlNodeBuilder - { - /// - /// Gets or sets the id of the test - /// - int Id { get; set; } - - /// - /// Gets the name of the test - /// - string Name { get; } - - /// - /// Gets the fully qualified name of the test - /// - string FullName { get; } - - /// - /// Gets the Type of the test fixture, if applicable, or - /// null if no fixture type is associated with this test. - /// - Type FixtureType { get; } - - /// - /// Indicates whether the test can be run using - /// the RunState enum. - /// - RunState RunState { get; set; } - - /// - /// Count of the test cases ( 1 if this is a test case ) - /// - int TestCaseCount { get; } - - /// - /// Gets the properties of the test - /// - IPropertyBag Properties { get; } - - /// - /// Gets the parent test, if any. - /// - /// The parent test or null if none exists. - ITest Parent { get; } - - /// - /// Returns true if this is a test suite - /// - bool IsSuite { get; } - - /// - /// Gets a bool indicating whether the current test - /// has any descendant tests. - /// - bool HasChildren { get; } - - /// - /// Gets the Int value representing the seed for the RandomGenerator - /// - /// - int Seed { get; } - - /// - /// Gets this test's child tests - /// - /// A list of child tests -#if CLR_2_0 || CLR_4_0 - System.Collections.Generic.IList Tests { get; } -#else - System.Collections.IList Tests { get; } -#endif - } -} - diff --git a/test/NUnitLite/src/framework/Api/ITestAssemblyRunner.cs b/test/NUnitLite/src/framework/Api/ITestAssemblyRunner.cs deleted file mode 100644 index 184c78dfd..000000000 --- a/test/NUnitLite/src/framework/Api/ITestAssemblyRunner.cs +++ /dev/null @@ -1,83 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Api -{ - /// - /// The ITestAssemblyRunner interface is implemented by classes - /// that are able to execute a suite of tests loaded - /// from an assembly. - /// - public interface ITestAssemblyRunner - { - #region Properties - - /// - /// Gets the tree of loaded tests, or null if - /// no tests have been loaded. - /// - ITest LoadedTest { get; } - - #endregion - - #region Methods - - /// - /// Loads the tests found in an Assembly, returning an - /// indication of whether or not the load succeeded. - /// - /// File name of the assembly to load - /// Dictionary of settings to use in loading the test - /// True if the load was successful - bool Load(string assemblyName, System.Collections.IDictionary settings); - - /// - /// Loads the tests found in an Assembly, returning an - /// indication of whether or not the load succeeded. - /// - /// The assembly to load - /// Dictionary of settings to use in loading the test - /// True if the load was successful - bool Load(Assembly assembly, System.Collections.IDictionary settings); - - ///// - ///// Count Test Cases using a filter - ///// - ///// The filter to apply - ///// The number of test cases found - //int CountTestCases(TestFilter filter); - - /// - /// Run selected tests and return a test result. The test is run synchronously, - /// and the listener interface is notified as it progresses. - /// - /// Interface to receive ITestListener notifications. - /// A test filter used to select tests to be run - ITestResult Run(ITestListener listener, ITestFilter filter); - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Api/ITestCaseData.cs b/test/NUnitLite/src/framework/Api/ITestCaseData.cs deleted file mode 100644 index 565a7109a..000000000 --- a/test/NUnitLite/src/framework/Api/ITestCaseData.cs +++ /dev/null @@ -1,71 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFn -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Api -{ - /// - /// The ITestCaseData interface is implemented by a class - /// that is able to return complete testcases for use by - /// a parameterized test method. - /// - public interface ITestCaseData - { - /// - /// Gets the name to be used for the test - /// - string TestName { get; } - - /// - /// Gets the RunState for this test case. - /// - RunState RunState { get; } - - /// - /// Gets the argument list to be provided to the test - /// - object[] Arguments { get; } - - /// - /// Gets the expected result of the test case - /// - object ExpectedResult { get; } - - /// - /// Returns true if an expected result has been set - /// - bool HasExpectedResult { get; } - - /// - /// Gets data about any expected exception. - /// - ExpectedExceptionData ExceptionData { get; } - - /// - /// Gets the property dictionary for the test case - /// - IPropertyBag Properties { get; } - } -} diff --git a/test/NUnitLite/src/framework/Api/ITestCaseSource.cs b/test/NUnitLite/src/framework/Api/ITestCaseSource.cs deleted file mode 100644 index 74cb7bbe5..000000000 --- a/test/NUnitLite/src/framework/Api/ITestCaseSource.cs +++ /dev/null @@ -1,50 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFn -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Api -{ - /// - /// ITestCaseSource interface is implemented by Types that know how to - /// return a set of ITestCaseData items for use by a test method. - /// - /// - /// This method is defined differently depending on the version of .NET. - /// - public interface ITestCaseSource - { - /// - /// Returns a set of ITestCaseDataItems for use as arguments - /// to a parameterized test method. - /// - /// The method for which data is needed. - /// -#if CLR_2_0 || CLR_4_0 - System.Collections.Generic.IEnumerable GetTestCasesFor(MethodInfo method); -#else - System.Collections.IEnumerable GetTestCasesFor(MethodInfo method); -#endif - } -} diff --git a/test/NUnitLite/src/framework/Api/ITestCaseSourceProvider.cs b/test/NUnitLite/src/framework/Api/ITestCaseSourceProvider.cs deleted file mode 100644 index 9442e9dff..000000000 --- a/test/NUnitLite/src/framework/Api/ITestCaseSourceProvider.cs +++ /dev/null @@ -1,50 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFn -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Api -{ - /// - /// The ITestCaseSourceProvider interface is implemented by Types that - /// are able to provide a test case source for use by a test method. - /// - public interface IDynamicTestCaseSource - { - /// - /// Returns a test case source. May be called on a provider - /// implementing the source internally or able to create - /// a source instance on it's own. - /// - /// - ITestCaseSource GetTestCaseSource(); - - /// - /// Returns a test case source based on an instance of a - /// source object. - /// - /// - /// - ITestCaseSource GetTestCaseSource(object instance); - } -} diff --git a/test/NUnitLite/src/framework/Api/ITestFilter.cs b/test/NUnitLite/src/framework/Api/ITestFilter.cs deleted file mode 100644 index 37ccc4d53..000000000 --- a/test/NUnitLite/src/framework/Api/ITestFilter.cs +++ /dev/null @@ -1,49 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Api -{ - /// - /// Interface to be implemented by filters applied to tests. - /// The filter applies when running the test, after it has been - /// loaded, since this is the only time an ITest exists. - /// - public interface ITestFilter - { - /// - /// Indicates whether this is the EmptyFilter - /// - bool IsEmpty { get; } - - /// - /// Determine if a particular test passes the filter criteria. Pass - /// may examine the parents and/or descendants of a test, depending - /// on the semantics of the particular filter - /// - /// The test to which the filter is applied - /// True if the test passes the fFilter, otherwise false - bool Pass( ITest test ); - } -} diff --git a/test/NUnitLite/src/framework/Api/ITestListener.cs b/test/NUnitLite/src/framework/Api/ITestListener.cs deleted file mode 100644 index 5fb259331..000000000 --- a/test/NUnitLite/src/framework/Api/ITestListener.cs +++ /dev/null @@ -1,52 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Api -{ - /// - /// The ITestListener interface is used internally to receive - /// notifications of significant events while a test is being - /// run. The events are propogated to clients by means of an - /// AsyncCallback. NUnit extensions may also monitor these events. - /// - public interface ITestListener - { - /// - /// Called when a test has just started - /// - /// The test that is starting - void TestStarted(ITest test); - - /// - /// Called when a test has finished - /// - /// The result of the test - void TestFinished(ITestResult result); - - /// - /// Called when the test creates text output. - /// - /// A console message - void TestOutput(TestOutput testOutput); - } -} diff --git a/test/NUnitLite/src/framework/Api/IXmlNodeBuilder.cs b/test/NUnitLite/src/framework/Api/IXmlNodeBuilder.cs deleted file mode 100644 index f2ef0580b..000000000 --- a/test/NUnitLite/src/framework/Api/IXmlNodeBuilder.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; - -namespace NUnit.Framework.Api -{ - /// - /// An object implementing IXmlNodeBuilder is able to build - /// an XmlResult representation of itself and any children. - /// Note that the interface refers to the implementation - /// of XmlNode in the NUnit.Framework.Api namespace. - /// - public interface IXmlNodeBuilder - { - /// - /// Returns an XmlNode representating the current object. - /// - /// If true, children are included where applicable - /// An XmlNode representing the result - XmlNode ToXml(bool recursive); - - /// - /// Returns an XmlNode representing the current object after - /// adding it as a child of the supplied parent node. - /// - /// The parent node. - /// If true, children are included, where applicable - /// - XmlNode AddToXml(XmlNode parentNode, bool recursive); - } -} diff --git a/test/NUnitLite/src/framework/Api/PropertyEntry.cs b/test/NUnitLite/src/framework/Api/PropertyEntry.cs deleted file mode 100644 index 5b9d6fd33..000000000 --- a/test/NUnitLite/src/framework/Api/PropertyEntry.cs +++ /dev/null @@ -1,70 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Api -{ - /// - /// Immutable class that stores a property entry as a Name/Value pair. - /// - public class PropertyEntry - { - private readonly string name; - private readonly object value; - - /// - /// Initializes a new immutable instance of the class. - /// - /// - /// - public PropertyEntry(string name, object value) - { - this.name = name; - this.value = value; - } - - /// Name of the PropertyEntry. - public string Name - { - get { return name; } - } - - /// Value of the PropertyEntry. - public object Value - { - get { return value; } - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - return string.Format("{0}={1}", name, value); - } - } -} diff --git a/test/NUnitLite/src/framework/Api/ResultState.cs b/test/NUnitLite/src/framework/Api/ResultState.cs deleted file mode 100644 index 9b0a7d516..000000000 --- a/test/NUnitLite/src/framework/Api/ResultState.cs +++ /dev/null @@ -1,139 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Api -{ - /// - /// The ResultState class represents the outcome of running a test. - /// It contains two pieces of information. The Status of the test - /// is an enum indicating whether the test passed, failed, was - /// skipped or was inconclusive. The Label provides a more - /// detailed breakdown for use by client runners. - /// - public class ResultState - { - private readonly TestStatus status; - private readonly string label; - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The TestStatus. - public ResultState(TestStatus status) : this (status, string.Empty) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The TestStatus. - /// The label. - public ResultState(TestStatus status, string label) - { - this.status = status; - this.label = label == null ? string.Empty : label; - } - - #endregion - - #region Predefined ResultStates - - /// - /// The result is inconclusive - /// - public readonly static ResultState Inconclusive = new ResultState(TestStatus.Inconclusive); - - /// - /// The test was not runnable. - /// - public readonly static ResultState NotRunnable = new ResultState(TestStatus.Skipped, "Invalid"); - - /// - /// The test has been skipped. - /// - public readonly static ResultState Skipped = new ResultState(TestStatus.Skipped); - - /// - /// The test has been ignored. - /// - public readonly static ResultState Ignored = new ResultState(TestStatus.Skipped, "Ignored"); - - /// - /// The test succeeded - /// - public readonly static ResultState Success = new ResultState(TestStatus.Passed); - - /// - /// The test failed - /// - public readonly static ResultState Failure = new ResultState(TestStatus.Failed); - - /// - /// The test encountered an unexpected exception - /// - public readonly static ResultState Error = new ResultState(TestStatus.Failed, "Error"); - - /// - /// The test was cancelled by the user - /// - public readonly static ResultState Cancelled = new ResultState(TestStatus.Failed, "Cancelled"); - - #endregion - - #region Properties - - /// - /// Gets the TestStatus for the test. - /// - /// The status. - public TestStatus Status - { - get { return status; } - } - - /// - /// Gets the label under which this test resullt is - /// categorized, if any. - /// - public string Label - { - get { return label; } - } - - #endregion - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - string s = status.ToString(); - return label == null || label.Length == 0 ? s : string.Format("{0}:{1}", s, label); - } - } -} diff --git a/test/NUnitLite/src/framework/Api/TestOutput.cs b/test/NUnitLite/src/framework/Api/TestOutput.cs deleted file mode 100644 index 31aad6d52..000000000 --- a/test/NUnitLite/src/framework/Api/TestOutput.cs +++ /dev/null @@ -1,109 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Api -{ - using System; - - /// - /// The TestOutput class holds a unit of output from - /// a test to either stdOut or stdErr - /// - public class TestOutput - { - string text; - TestOutputType type; - - /// - /// Construct with text and an ouput destination type - /// - /// Text to be output - /// Destination of output - public TestOutput(string text, TestOutputType type) - { - this.text = text; - this.type = type; - } - - /// - /// Return string representation of the object for debugging - /// - /// - public override string ToString() - { - return type + ": " + text; - } - - /// - /// Get the text - /// - public string Text - { - get - { - return this.text; - } - } - - /// - /// Get the output type - /// - public TestOutputType Type - { - get - { - return this.type; - } - } - } - - /// - /// Enum representing the output destination - /// It uses combinable flags so that a given - /// output control can accept multiple types - /// of output. Normally, each individual - /// output uses a single flag value. - /// - public enum TestOutputType - { - /// - /// Send output to stdOut - /// - Out, - - /// - /// Send output to stdErr - /// - Error, - - /// - /// Send output to Trace - /// - Trace, - - /// - /// Send output to Log - /// - Log - } -} diff --git a/test/NUnitLite/src/framework/Api/XmlNode.cs b/test/NUnitLite/src/framework/Api/XmlNode.cs deleted file mode 100644 index 138fbcf6e..000000000 --- a/test/NUnitLite/src/framework/Api/XmlNode.cs +++ /dev/null @@ -1,352 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Api -{ - /// - /// XmlNode represents a single node in the XML representation - /// of a Test or TestResult. It replaces System.Xml.XmlNode and - /// provides a minimal set of methods for operating on the XML - /// in a platform-independent manner. - /// - public class XmlNode - { - #region Private Fields - - private string name; - - private AttributeDictionary attributes; - - private NodeList childNodes; - - private string textContent; - - #endregion - - #region Constructors - - /// - /// Constructs a new instance of XmlNode - /// - /// The name of the node - public XmlNode(string name) - { - this.name = name; - this.attributes = new AttributeDictionary(); - this.childNodes = new NodeList(); - } - - #endregion - - #region Static Methods - - /// - /// Creates a new top level element node. - /// - /// The element name. - /// - public static XmlNode CreateTopLevelElement(string name) - { - return new XmlNode(name); - } - - #endregion - - #region Properties - - /// - /// Gets the name of the node - /// - public string Name - { - get { return name; } - } - - /// - /// Gets the text content of the node - /// - public string TextContent - { - get { return textContent; } - set { textContent = value; } - } - - /// - /// Gets the text content of the node escaped as needed. - /// This is for use in writing out the XML representation. - /// - public string EscapedTextContent - { - get { return Escape(textContent); } - } - - /// - /// Gets the dictionary of attributes - /// - public AttributeDictionary Attributes - { - get { return attributes; } - } - - /// - /// Gets a list of child nodes - /// - public NodeList ChildNodes - { - get { return childNodes; } - } - - /// - /// Gets the first child of this node, or null - /// - public XmlNode FirstChild - { - get - { - return ChildNodes.Count > 0 - ? ChildNodes[0] as XmlNode - : null; - } - } - - #endregion - - #region Instance Methods - - /// - /// Adds a new element as a child of the current node and returns it. - /// - /// The element name. - /// The newly created child element - public XmlNode AddElement(string name) - { - XmlNode childResult = new XmlNode(name); - ChildNodes.Add(childResult); - return childResult; - } - - /// - /// Adds an attribute with a specified name and value to the XmlNode. - /// - /// The name of the attribute. - /// The value of the attribute. - public void AddAttribute(string name, string value) - { - this.Attributes.Add(name, value); - } - - /// - /// Finds a single descendant of this node matching an xpath - /// specification. The format of the specification is - /// limited to what is needed by NUnit and its tests. - /// - /// - /// - public XmlNode FindDescendant(string xpath) - { - NodeList nodes = FindDescendants(xpath); - - return nodes.Count > 0 - ? nodes[0] as XmlNode - : null; - } - - /// - /// Finds all descendants of this node matching an xpath - /// specification. The format of the specification is - /// limited to what is needed by NUnit and its tests. - /// - /// - /// - public NodeList FindDescendants(string xpath) - { - NodeList nodeList = new NodeList(); - nodeList.Add(this); - - return ApplySelection(nodeList, xpath); - } - - /// - /// Writes the XML representation of the node to an XmlWriter - /// - /// - public void WriteTo(System.Xml.XmlWriter writer) - { - writer.WriteStartElement(this.Name); - - foreach (string name in this.Attributes.Keys) - writer.WriteAttributeString(name, Attributes[name]); - - if (this.TextContent != null) - writer.WriteChars(this.TextContent.ToCharArray(), 0, this.TextContent.Length); - - foreach (XmlNode node in this.ChildNodes) - node.WriteTo(writer); - - writer.WriteEndElement(); - } - - #endregion - - #region Helper Methods - - private static NodeList ApplySelection(NodeList nodeList, string xpath) - { - Guard.ArgumentNotNullOrEmpty(xpath, "xpath"); - if (xpath[0] == '/') - throw new ArgumentException("XPath expressions starting with '/' are not supported", "xpath"); - if (xpath.IndexOf("//") >= 0) - throw new ArgumentException("XPath expressions with '//' are not supported", "xpath"); - - string head = xpath; - string tail = null; - - int slash = xpath.IndexOf('/'); - if (slash >= 0) - { - head = xpath.Substring(0, slash); - tail = xpath.Substring(slash + 1); - } - - NodeList resultNodes = new NodeList(); - NodeFilter filter = new NodeFilter(head); - - foreach(XmlNode node in nodeList) - foreach (XmlNode childNode in node.ChildNodes) - if (filter.Pass(childNode)) - resultNodes.Add(childNode); - - return tail != null - ? ApplySelection(resultNodes, tail) - : resultNodes; - } - - private static string Escape(string original) - { - return original - .Replace("&", "&") - .Replace("\"", """) - .Replace("'", "'") - .Replace("<", "<") - .Replace(">", ">"); - } - - #endregion - - #region Nested NodeFilter class - - class NodeFilter - { - private string nodeName; - private string propName; - private string propValue; - - public NodeFilter(string xpath) - { - this.nodeName = xpath; - - int lbrack = xpath.IndexOf('['); - if (lbrack >= 0) - { - if (!xpath.EndsWith("]")) - throw new ArgumentException("Invalid property expression", "xpath"); - - nodeName = xpath.Substring(0, lbrack); - string filter = xpath.Substring(lbrack+1, xpath.Length - lbrack - 2); - - int equals = filter.IndexOf('='); - if (equals < 0 || filter[0] != '@') - throw new ArgumentException("Invalid property expression", "xpath"); - - this.propName = filter.Substring(1, equals - 1).Trim(); - this.propValue = filter.Substring(equals + 1).Trim(new char[] { ' ', '"', '\'' }); - } - } - - public bool Pass(XmlNode node) - { - if (node.Name != nodeName) - return false; - - if (propName == null) - return true; - - return (string)node.Attributes[propName] == propValue; - } - } - - #endregion - } - - /// - /// Class used to represent a list of XmlResults - /// -#if CLR_2_0 || CLR_4_0 - public class NodeList : System.Collections.Generic.List - { - } -#else - public class NodeList : System.Collections.ArrayList - { - } -#endif - - /// - /// Class used to represent the attributes of a node - /// -#if CLR_2_0 || CLR_4_0 - public class AttributeDictionary : System.Collections.Generic.Dictionary - { - } -#else - public class AttributeDictionary : System.Collections.Specialized.StringDictionary - { - private System.Collections.ArrayList orderedKeys = new System.Collections.ArrayList(); - - /// - /// Adds a key and value to the dictionary. Overridden to - /// save the order in which keys are added. - /// - /// The attribute key - /// The attribute value - public override void Add(string key, string value) - { - base.Add(key, value); - orderedKeys.Add(key); - } - - /// - /// Gets the keys in the same order they were added. - /// - public override System.Collections.ICollection Keys - { - get - { - return orderedKeys; - } - } - } -#endif -} diff --git a/test/NUnitLite/src/framework/AssemblyInfo.cs b/test/NUnitLite/src/framework/AssemblyInfo.cs deleted file mode 100644 index f130d22fb..000000000 --- a/test/NUnitLite/src/framework/AssemblyInfo.cs +++ /dev/null @@ -1,110 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("NUnitLite")] -[assembly: AssemblyDescription("NUnitLite unit-testing framework")] -[assembly: AssemblyCompany("NUnit Software")] -[assembly: AssemblyProduct("NUnitLite")] -[assembly: AssemblyCopyright("Copyright 2013, Charlie Poole")] -[assembly: AssemblyTrademark("NUnitLite")] -[assembly: AssemblyCulture("")] - -// Set AssemblyConfiguration attribute depending on -// how we are building the assembly. -#if DEBUG -#if NET_4_5 -[assembly: AssemblyConfiguration(".NET 4.5 Debug")] -#elif NET_4_0 -[assembly: AssemblyConfiguration(".NET 4.0 Debug")] -#elif NET_3_5 -[assembly: AssemblyConfiguration(".NET 3.5 Debug")] -#elif NET_2_0 -[assembly: AssemblyConfiguration(".NET 2.0 Debug")] -#elif NET_1_1 -[assembly: AssemblyConfiguration(".NET 1.1 Debug")] -#elif NETCF_3_5 -[assembly: AssemblyConfiguration(".NET CF 3.5 Debug")] -#elif NETCF_2_0 -[assembly: AssemblyConfiguration(".NET CF 2.0 Debug")] -#elif SL_5_0 -[assembly: AssemblyConfiguration("Silverlight 5.0 Debug")] -#elif SL_4_0 -[assembly: AssemblyConfiguration("Silverlight 4.0 Debug")] -#elif SL_3_0 -[assembly: AssemblyConfiguration("Silverlight 3.0 Debug")] -#endif -#else -#if NET_4_5 -[assembly: AssemblyConfiguration(".NET 4.5")] -#elif NET_4_0 -[assembly: AssemblyConfiguration(".NET 4.0")] -#elif NET_3_5 -[assembly: AssemblyConfiguration(".NET 3.5")] -#elif NET_2_0 -[assembly: AssemblyConfiguration(".NET 2.0")] -#elif NET_1_1 -[assembly: AssemblyConfiguration(".NET 1.1")] -#elif NETCF_3_5 -[assembly: AssemblyConfiguration(".NET CF 3.5")] -#elif NETCF_2_0 -[assembly: AssemblyConfiguration(".NET CF 2.0")] -#elif SL_5_0 -[assembly: AssemblyConfiguration("Silverlight 5.0")] -#elif SL_4_0 -[assembly: AssemblyConfiguration("Silverlight 4.0")] -#elif SL_3_0 -[assembly: AssemblyConfiguration("Silverlight 3.0")] -#endif -#endif - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -[assembly: CLSCompliant(true)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("0be367fd-d825-4039-a70b-54a3557170ec")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -#if !PocketPC && !WindowsCE && !NETCF -[assembly: AssemblyFileVersion("1.0.0.0")] -#endif diff --git a/test/NUnitLite/src/framework/Assert.cs b/test/NUnitLite/src/framework/Assert.cs deleted file mode 100644 index 9f35e7250..000000000 --- a/test/NUnitLite/src/framework/Assert.cs +++ /dev/null @@ -1,1923 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.ComponentModel; -using NUnit.Framework.Constraints; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// Delegate used by tests that execute code and - /// capture any thrown exception. - /// - public delegate void TestDelegate(); - - /// - /// The Assert class contains a collection of static methods that - /// implement the most common assertions used in NUnit. - /// - public class Assert - { - #region Constructor - - /// - /// We don't actually want any instances of this object, but some people - /// like to inherit from it to add other static methods. Hence, the - /// protected constructor disallows any instances of this object. - /// - protected Assert() { } - - #endregion - - #region Equals and ReferenceEquals - -#if !NETCF - /// - /// The Equals method throws an AssertionException. This is done - /// to make sure there is no mistake by calling this function. - /// - /// - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static new bool Equals(object a, object b) - { - throw new InvalidOperationException("Assert.Equals should not be used for Assertions"); - } - - /// - /// override the default ReferenceEquals to throw an AssertionException. This - /// implementation makes sure there is no mistake in calling this function - /// as part of Assert. - /// - /// - /// - public static new void ReferenceEquals(object a, object b) - { - throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions"); - } -#endif - - #endregion - - #region Utility Asserts - - #region Pass - - /// - /// Throws a with the message and arguments - /// that are passed in. This allows a test to be cut short, with a result - /// of success returned to NUnit. - /// - /// The message to initialize the with. - /// Arguments to be used in formatting the message - static public void Pass(string message, params object[] args) - { - if (message == null) message = string.Empty; - else if (args != null && args.Length > 0) - message = string.Format(message, args); - - throw new SuccessException(message); - } - - /// - /// Throws a with the message and arguments - /// that are passed in. This allows a test to be cut short, with a result - /// of success returned to NUnit. - /// - /// The message to initialize the with. - static public void Pass(string message) - { - Assert.Pass(message, null); - } - - /// - /// Throws a with the message and arguments - /// that are passed in. This allows a test to be cut short, with a result - /// of success returned to NUnit. - /// - static public void Pass() - { - Assert.Pass(string.Empty, null); - } - - #endregion - - #region Fail - - /// - /// Throws an with the message and arguments - /// that are passed in. This is used by the other Assert functions. - /// - /// The message to initialize the with. - /// Arguments to be used in formatting the message - static public void Fail(string message, params object[] args) - { - if (message == null) message = string.Empty; - else if (args != null && args.Length > 0) - message = string.Format(message, args); - - throw new AssertionException(message); - } - - /// - /// Throws an with the message that is - /// passed in. This is used by the other Assert functions. - /// - /// The message to initialize the with. - static public void Fail(string message) - { - Assert.Fail(message, null); - } - - /// - /// Throws an . - /// This is used by the other Assert functions. - /// - static public void Fail() - { - Assert.Fail(string.Empty, null); - } - - #endregion - - #region Ignore - - /// - /// Throws an with the message and arguments - /// that are passed in. This causes the test to be reported as ignored. - /// - /// The message to initialize the with. - /// Arguments to be used in formatting the message - static public void Ignore(string message, params object[] args) - { - if (message == null) message = string.Empty; - else if (args != null && args.Length > 0) - message = string.Format(message, args); - - throw new IgnoreException(message); - } - - /// - /// Throws an with the message that is - /// passed in. This causes the test to be reported as ignored. - /// - /// The message to initialize the with. - static public void Ignore(string message) - { - Assert.Ignore(message, null); - } - - /// - /// Throws an . - /// This causes the test to be reported as ignored. - /// - static public void Ignore() - { - Assert.Ignore(string.Empty, null); - } - - #endregion - - #region InConclusive - - /// - /// Throws an with the message and arguments - /// that are passed in. This causes the test to be reported as inconclusive. - /// - /// The message to initialize the with. - /// Arguments to be used in formatting the message - static public void Inconclusive(string message, params object[] args) - { - if (message == null) message = string.Empty; - else if (args != null && args.Length > 0) - message = string.Format(message, args); - - throw new InconclusiveException(message); - } - - /// - /// Throws an with the message that is - /// passed in. This causes the test to be reported as inconclusive. - /// - /// The message to initialize the with. - static public void Inconclusive(string message) - { - Assert.Inconclusive(message, null); - } - - /// - /// Throws an . - /// This causes the test to be reported as Inconclusive. - /// - static public void Inconclusive() - { - Assert.Inconclusive(string.Empty, null); - } - - #endregion - - #endregion - - #region Assert.That - - #region Object - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - static public void That(object actual, IResolveConstraint expression) - { - Assert.That(actual, expression, null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - static public void That(object actual, IResolveConstraint expression, string message) - { - Assert.That(actual, expression, message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(object actual, IResolveConstraint expression, string message, params object[] args) - { - Constraint constraint = expression.Resolve(); - - IncrementAssertCount(); - if (!constraint.Matches(actual)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new AssertionException(writer.ToString()); - } - } - - #endregion - - #region Boolean - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display if the condition is false - /// Arguments to be used in formatting the message - static public void That(bool condition, string message, params object[] args) - { - Assert.That(condition, Is.True, message, args); - } - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display if the condition is false - static public void That(bool condition, string message) - { - Assert.That(condition, Is.True, message, null); - } - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - static public void That(bool condition) - { - Assert.That(condition, Is.True, null, null); - } - - #endregion - - #region ref Boolean - -#if !CLR_2_0 && !CLR_4_0 - /// - /// Apply a constraint to a referenced boolean, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - static public void That(ref bool actual, IResolveConstraint constraint) - { - Assert.That(ref actual, constraint.Resolve(), null, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - static public void That(ref bool actual, IResolveConstraint constraint, string message) - { - Assert.That(ref actual, constraint.Resolve(), message, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ref bool actual, IResolveConstraint expression, string message, params object[] args) - { - Constraint constraint = expression.Resolve(); - - IncrementAssertCount(); - if (!constraint.Matches(ref actual)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new AssertionException(writer.ToString()); - } - } -#endif - - #endregion - - #region ActualValueDelegate - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - static public void That(ActualValueDelegate del, IResolveConstraint expr) - { - Assert.That(del, expr.Resolve(), null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message) - { - Assert.That(del, expr.Resolve(), message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args) - { - Constraint constraint = expr.Resolve(); - - IncrementAssertCount(); - if (!constraint.Matches(del)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new AssertionException(writer.ToString()); - } - } -#else - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - static public void That(ActualValueDelegate del, IResolveConstraint expr) - { - Assert.That(del, expr.Resolve(), null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message) - { - Assert.That(del, expr.Resolve(), message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args) - { - Constraint constraint = expr.Resolve(); - - IncrementAssertCount(); - if (!constraint.Matches(del)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new AssertionException(writer.ToString()); - } - } -#endif - - #endregion - - #region ref Object - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - static public void That(ref T actual, IResolveConstraint expression) - { - Assert.That(ref actual, expression, null, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - static public void That(ref T actual, IResolveConstraint expression, string message) - { - Assert.That(ref actual, expression, message, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ref T actual, IResolveConstraint expression, string message, params object[] args) - { - Constraint constraint = expression.Resolve(); - - IncrementAssertCount(); - if (!constraint.Matches(ref actual)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new AssertionException(writer.ToString()); - } - } -#endif - - #endregion - - #region TestDelegate - - /// - /// Asserts that the code represented by a delegate throws an exception - /// that satisfies the constraint provided. - /// - /// A TestDelegate to be executed - /// A ThrowsConstraint used in the test - static public void That(TestDelegate code, IResolveConstraint constraint) - { - Assert.That((object)code, constraint); - } - - #endregion - - #endregion - - #region Assert.ByVal - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// Used as a synonym for That in rare cases where a private setter - /// causes a Visual Basic compilation error. - /// - /// The actual value to test - /// A Constraint to be applied - static public void ByVal(object actual, IResolveConstraint expression) - { - Assert.That(actual, expression, null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// Used as a synonym for That in rare cases where a private setter - /// causes a Visual Basic compilation error. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - static public void ByVal(object actual, IResolveConstraint expression, string message) - { - Assert.That(actual, expression, message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// Used as a synonym for That in rare cases where a private setter - /// causes a Visual Basic compilation error. - /// - /// - /// This method is provided for use by VB developers needing to test - /// the value of properties with private setters. - /// - /// The actual value to test - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void ByVal(object actual, IResolveConstraint expression, string message, params object[] args) - { - Assert.That(actual, expression, message, args); - } - - #endregion - - #region Throws, Catch and DoesNotThrow - - #region Throws - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// A constraint to be satisfied by the exception - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message, params object[] args) - { - Exception caughtException = null; - -#if NET_4_5 - if (AsyncInvocationRegion.IsAsyncOperation(code)) - { - using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(code)) - { - code(); - - try - { - region.WaitForPendingOperationsToComplete(null); - } - catch (Exception e) - { - caughtException = e; - } - } - } - else -#endif - try - { - code(); - } - catch (Exception ex) - { - caughtException = ex; - } - - Assert.That(caughtException, expression, message, args); - - return caughtException; - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// A constraint to be satisfied by the exception - /// A TestDelegate - /// The message that will be displayed on failure - public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message) - { - return Throws(expression, code, message, null); - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// A constraint to be satisfied by the exception - /// A TestDelegate - public static Exception Throws(IResolveConstraint expression, TestDelegate code) - { - return Throws(expression, code, string.Empty, null); - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// The exception Type expected - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static Exception Throws(Type expectedExceptionType, TestDelegate code, string message, params object[] args) - { - return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, message, args); - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// The exception Type expected - /// A TestDelegate - /// The message that will be displayed on failure - public static Exception Throws(Type expectedExceptionType, TestDelegate code, string message) - { - return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, message, null); - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// The exception Type expected - /// A TestDelegate - public static Exception Throws(Type expectedExceptionType, TestDelegate code) - { - return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null); - } - - #endregion - - #region Throws - -#if CLR_2_0 || CLR_4_0 - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// Type of the expected exception - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static T Throws(TestDelegate code, string message, params object[] args) where T : Exception - { - return (T)Throws(typeof(T), code, message, args); - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// Type of the expected exception - /// A TestDelegate - /// The message that will be displayed on failure - public static T Throws(TestDelegate code, string message) where T : Exception - { - return Throws(code, message, null); - } - - /// - /// Verifies that a delegate throws a particular exception when called. - /// - /// Type of the expected exception - /// A TestDelegate - public static T Throws(TestDelegate code) where T : Exception - { - return Throws(code, string.Empty, null); - } -#endif - - #endregion - - #region Catch - /// - /// Verifies that a delegate throws an exception when called - /// and returns it. - /// - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static Exception Catch(TestDelegate code, string message, params object[] args) - { - return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args); - } - - /// - /// Verifies that a delegate throws an exception when called - /// and returns it. - /// - /// A TestDelegate - /// The message that will be displayed on failure - public static Exception Catch(TestDelegate code, string message) - { - return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code, message); - } - - /// - /// Verifies that a delegate throws an exception when called - /// and returns it. - /// - /// A TestDelegate - public static Exception Catch(TestDelegate code) - { - return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code); - } - - /// - /// Verifies that a delegate throws an exception of a certain Type - /// or one derived from it when called and returns it. - /// - /// The expected Exception Type - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static Exception Catch(Type expectedExceptionType, TestDelegate code, string message, params object[] args) - { - return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args); - } - - /// - /// Verifies that a delegate throws an exception of a certain Type - /// or one derived from it when called and returns it. - /// - /// The expected Exception Type - /// A TestDelegate - /// The message that will be displayed on failure - public static Exception Catch(Type expectedExceptionType, TestDelegate code, string message) - { - return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code, message); - } - - /// - /// Verifies that a delegate throws an exception of a certain Type - /// or one derived from it when called and returns it. - /// - /// The expected Exception Type - /// A TestDelegate - public static Exception Catch(Type expectedExceptionType, TestDelegate code) - { - return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code); - } - #endregion - - #region Catch - -#if CLR_2_0 || CLR_4_0 - /// - /// Verifies that a delegate throws an exception of a certain Type - /// or one derived from it when called and returns it. - /// - /// The expected Exception Type - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static T Catch(TestDelegate code, string message, params object[] args) where T : System.Exception - { - return (T)Throws(new InstanceOfTypeConstraint(typeof(T)), code, message, args); - } - - /// - /// Verifies that a delegate throws an exception of a certain Type - /// or one derived from it when called and returns it. - /// - /// The expected Exception Type - /// A TestDelegate - /// The message that will be displayed on failure - public static T Catch(TestDelegate code, string message) where T : System.Exception - { - return (T)Throws(new InstanceOfTypeConstraint(typeof(T)), code, message); - } - - /// - /// Verifies that a delegate throws an exception of a certain Type - /// or one derived from it when called and returns it. - /// - /// The expected Exception Type - /// A TestDelegate - public static T Catch(TestDelegate code) where T : System.Exception - { - return (T)Throws(new InstanceOfTypeConstraint(typeof(T)), code); - } -#endif - - #endregion - - #region DoesNotThrow - - /// - /// Verifies that a delegate does not throw an exception - /// - /// A TestDelegate - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public static void DoesNotThrow(TestDelegate code, string message, params object[] args) - { - Assert.That(code, new ThrowsNothingConstraint(), message, args); - } - - /// - /// Verifies that a delegate does not throw an exception. - /// - /// A TestDelegate - /// The message that will be displayed on failure - public static void DoesNotThrow(TestDelegate code, string message) - { - DoesNotThrow(code, message, null); - } - - /// - /// Verifies that a delegate does not throw an exception. - /// - /// A TestDelegate - public static void DoesNotThrow(TestDelegate code) - { - DoesNotThrow(code, string.Empty, null); - } - - #endregion - - #endregion - - #region True - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void True(bool condition, string message, params object[] args) - { - Assert.That(condition, Is.True ,message, args); - } - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - public static void True(bool condition, string message) - { - Assert.That(condition, Is.True ,message, null); - } - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - public static void True(bool condition) - { - Assert.That(condition, Is.True ,null, null); - } - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void IsTrue(bool condition, string message, params object[] args) - { - Assert.That(condition, Is.True ,message, args); - } - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - public static void IsTrue(bool condition, string message) - { - Assert.That(condition, Is.True ,message, null); - } - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - public static void IsTrue(bool condition) - { - Assert.That(condition, Is.True ,null, null); - } - - #endregion - - #region False - - /// - /// Asserts that a condition is false. If the condition is true the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void False(bool condition, string message, params object[] args) - { - Assert.That(condition, Is.False ,message, args); - } - /// - /// Asserts that a condition is false. If the condition is true the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - public static void False(bool condition, string message) - { - Assert.That(condition, Is.False ,message, null); - } - /// - /// Asserts that a condition is false. If the condition is true the method throws - /// an . - /// - /// The evaluated condition - public static void False(bool condition) - { - Assert.That(condition, Is.False ,null, null); - } - - /// - /// Asserts that a condition is false. If the condition is true the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void IsFalse(bool condition, string message, params object[] args) - { - Assert.That(condition, Is.False ,message, args); - } - /// - /// Asserts that a condition is false. If the condition is true the method throws - /// an . - /// - /// The evaluated condition - /// The message to display in case of failure - public static void IsFalse(bool condition, string message) - { - Assert.That(condition, Is.False ,message, null); - } - /// - /// Asserts that a condition is false. If the condition is true the method throws - /// an . - /// - /// The evaluated condition - public static void IsFalse(bool condition) - { - Assert.That(condition, Is.False ,null, null); - } - - #endregion - - #region NotNull - - /// - /// Verifies that the object that is passed in is not equal to null - /// If the object is null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void NotNull(object anObject, string message, params object[] args) - { - Assert.That(anObject, Is.Not.Null ,message, args); - } - /// - /// Verifies that the object that is passed in is not equal to null - /// If the object is null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - public static void NotNull(object anObject, string message) - { - Assert.That(anObject, Is.Not.Null ,message, null); - } - /// - /// Verifies that the object that is passed in is not equal to null - /// If the object is null then an - /// is thrown. - /// - /// The object that is to be tested - public static void NotNull(object anObject) - { - Assert.That(anObject, Is.Not.Null ,null, null); - } - - /// - /// Verifies that the object that is passed in is not equal to null - /// If the object is null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void IsNotNull(object anObject, string message, params object[] args) - { - Assert.That(anObject, Is.Not.Null ,message, args); - } - /// - /// Verifies that the object that is passed in is not equal to null - /// If the object is null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - public static void IsNotNull(object anObject, string message) - { - Assert.That(anObject, Is.Not.Null ,message, null); - } - /// - /// Verifies that the object that is passed in is not equal to null - /// If the object is null then an - /// is thrown. - /// - /// The object that is to be tested - public static void IsNotNull(object anObject) - { - Assert.That(anObject, Is.Not.Null ,null, null); - } - - #endregion - - #region Null - - /// - /// Verifies that the object that is passed in is equal to null - /// If the object is not null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void Null(object anObject, string message, params object[] args) - { - Assert.That(anObject, Is.Null ,message, args); - } - /// - /// Verifies that the object that is passed in is equal to null - /// If the object is not null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - public static void Null(object anObject, string message) - { - Assert.That(anObject, Is.Null ,message, null); - } - /// - /// Verifies that the object that is passed in is equal to null - /// If the object is not null then an - /// is thrown. - /// - /// The object that is to be tested - public static void Null(object anObject) - { - Assert.That(anObject, Is.Null ,null, null); - } - - /// - /// Verifies that the object that is passed in is equal to null - /// If the object is not null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void IsNull(object anObject, string message, params object[] args) - { - Assert.That(anObject, Is.Null ,message, args); - } - /// - /// Verifies that the object that is passed in is equal to null - /// If the object is not null then an - /// is thrown. - /// - /// The object that is to be tested - /// The message to display in case of failure - public static void IsNull(object anObject, string message) - { - Assert.That(anObject, Is.Null ,message, null); - } - /// - /// Verifies that the object that is passed in is equal to null - /// If the object is not null then an - /// is thrown. - /// - /// The object that is to be tested - public static void IsNull(object anObject) - { - Assert.That(anObject, Is.Null ,null, null); - } - - #endregion - - #region AreEqual - - #region Ints - - /// - /// Verifies that two ints are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreEqual(int expected, int actual, string message, params object[] args) - { - Assert.That(actual, Is.EqualTo(expected), message, args); - } - /// - /// Verifies that two ints are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreEqual(int expected, int actual, string message) - { - Assert.That(actual, Is.EqualTo(expected), message, null); - } - /// - /// Verifies that two ints are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreEqual(int expected, int actual) - { - Assert.That(actual, Is.EqualTo(expected), null, null); - } - - #endregion - - #region Longs - - /// - /// Verifies that two longs are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreEqual(long expected, long actual, string message, params object[] args) - { - Assert.That(actual, Is.EqualTo(expected), message, args); - } - /// - /// Verifies that two longs are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreEqual(long expected, long actual, string message) - { - Assert.That(actual, Is.EqualTo(expected), message, null); - } - /// - /// Verifies that two longs are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreEqual(long expected, long actual) - { - Assert.That(actual, Is.EqualTo(expected), null, null); - } - - #endregion - - #region Unsigned Ints - - /// - /// Verifies that two unsigned ints are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - [CLSCompliant(false)] - public static void AreEqual(uint expected, uint actual, string message, params object[] args) - { - Assert.That(actual, Is.EqualTo(expected), message, args); - } - /// - /// Verifies that two unsigned ints are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - [CLSCompliant(false)] - public static void AreEqual(uint expected, uint actual, string message) - { - Assert.That(actual, Is.EqualTo(expected), message, null); - } - /// - /// Verifies that two unsigned ints are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - [CLSCompliant(false)] - public static void AreEqual(uint expected, uint actual) - { - Assert.That(actual, Is.EqualTo(expected), null, null); - } - - #endregion - - #region Unsigned Longs - - /// - /// Verifies that two unsigned longs are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - [CLSCompliant(false)] - public static void AreEqual(ulong expected, ulong actual, string message, params object[] args) - { - Assert.That(actual, Is.EqualTo(expected), message, args); - } - /// - /// Verifies that two unsigned longs are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - [CLSCompliant(false)] - public static void AreEqual(ulong expected, ulong actual, string message) - { - Assert.That(actual, Is.EqualTo(expected), message, null); - } - /// - /// Verifies that two unsigned longs are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - [CLSCompliant(false)] - public static void AreEqual(ulong expected, ulong actual) - { - Assert.That(actual, Is.EqualTo(expected), null, null); - } - - #endregion - - #region Decimals - - /// - /// Verifies that two decimals are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreEqual(decimal expected, decimal actual, string message, params object[] args) - { - Assert.That(actual, Is.EqualTo(expected), message, args); - } - /// - /// Verifies that two decimals are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreEqual(decimal expected, decimal actual, string message) - { - Assert.That(actual, Is.EqualTo(expected), message, null); - } - /// - /// Verifies that two decimals are equal. If they are not, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreEqual(decimal expected, decimal actual) - { - Assert.That(actual, Is.EqualTo(expected), null, null); - } - - #endregion - - #region Doubles - - /// - /// Verifies that two doubles are equal considering a delta. If the - /// expected value is infinity then the delta value is ignored. If - /// they are not equal then an is - /// thrown. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreEqual(double expected, double actual, double delta, string message, params object[] args) - { - AssertDoublesAreEqual(expected, actual, delta, message, args); - } - /// - /// Verifies that two doubles are equal considering a delta. If the - /// expected value is infinity then the delta value is ignored. If - /// they are not equal then an is - /// thrown. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - /// The message to display in case of failure - public static void AreEqual(double expected, double actual, double delta, string message) - { - AssertDoublesAreEqual(expected, actual, delta, message, null); - } - /// - /// Verifies that two doubles are equal considering a delta. If the - /// expected value is infinity then the delta value is ignored. If - /// they are not equal then an is - /// thrown. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - public static void AreEqual(double expected, double actual, double delta) - { - AssertDoublesAreEqual(expected, actual, delta, null, null); - } - -#if CLR_2_0 || CLR_4_0 - /// - /// Verifies that two doubles are equal considering a delta. If the - /// expected value is infinity then the delta value is ignored. If - /// they are not equal then an is - /// thrown. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreEqual(double expected, double? actual, double delta, string message, params object[] args) - { - AssertDoublesAreEqual(expected, (double)actual, delta, message, args); - } - /// - /// Verifies that two doubles are equal considering a delta. If the - /// expected value is infinity then the delta value is ignored. If - /// they are not equal then an is - /// thrown. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - /// The message to display in case of failure - public static void AreEqual(double expected, double? actual, double delta, string message) - { - AssertDoublesAreEqual(expected, (double)actual, delta, message, null); - } - /// - /// Verifies that two doubles are equal considering a delta. If the - /// expected value is infinity then the delta value is ignored. If - /// they are not equal then an is - /// thrown. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - public static void AreEqual(double expected, double? actual, double delta) - { - AssertDoublesAreEqual(expected, (double)actual, delta, null, null); - } -#endif - - #endregion - - #region Objects - - /// - /// Verifies that two objects are equal. Two objects are considered - /// equal if both are null, or if both have the same value. NUnit - /// has special semantics for some object types. - /// If they are not equal an is thrown. - /// - /// The value that is expected - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreEqual(object expected, object actual, string message, params object[] args) - { - Assert.That(actual, Is.EqualTo(expected), message, args); - } - /// - /// Verifies that two objects are equal. Two objects are considered - /// equal if both are null, or if both have the same value. NUnit - /// has special semantics for some object types. - /// If they are not equal an is thrown. - /// - /// The value that is expected - /// The actual value - /// The message to display in case of failure - public static void AreEqual(object expected, object actual, string message) - { - Assert.That(actual, Is.EqualTo(expected), message, null); - } - /// - /// Verifies that two objects are equal. Two objects are considered - /// equal if both are null, or if both have the same value. NUnit - /// has special semantics for some object types. - /// If they are not equal an is thrown. - /// - /// The value that is expected - /// The actual value - public static void AreEqual(object expected, object actual) - { - Assert.That(actual, Is.EqualTo(expected), null, null); - } - - #endregion - - #endregion - - #region AreNotEqual - - #region Ints - - /// - /// Verifies that two ints are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotEqual(int expected, int actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two ints are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreNotEqual(int expected, int actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two ints are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreNotEqual(int expected, int actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Longs - - /// - /// Verifies that two longs are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotEqual(long expected, long actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two longs are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreNotEqual(long expected, long actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two longs are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreNotEqual(long expected, long actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Unsigned Ints - - /// - /// Verifies that two unsigned ints are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - [CLSCompliant(false)] - public static void AreNotEqual(uint expected, uint actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two unsigned ints are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - [CLSCompliant(false)] - public static void AreNotEqual(uint expected, uint actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two unsigned ints are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - [CLSCompliant(false)] - public static void AreNotEqual(uint expected, uint actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Unsigned Longs - - /// - /// Verifies that two unsigned longs are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - [CLSCompliant(false)] - public static void AreNotEqual(ulong expected, ulong actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two unsigned longs are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - [CLSCompliant(false)] - public static void AreNotEqual(ulong expected, ulong actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two unsigned longs are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - [CLSCompliant(false)] - public static void AreNotEqual(ulong expected, ulong actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Decimals - - /// - /// Verifies that two decimals are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotEqual(decimal expected, decimal actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two decimals are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreNotEqual(decimal expected, decimal actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two decimals are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreNotEqual(decimal expected, decimal actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Floats - - /// - /// Verifies that two floats are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotEqual(float expected, float actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two floats are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreNotEqual(float expected, float actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two floats are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreNotEqual(float expected, float actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Doubles - - /// - /// Verifies that two doubles are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotEqual(double expected, double actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two doubles are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - /// The message to display in case of failure - public static void AreNotEqual(double expected, double actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two doubles are not equal. If they are equal, then an - /// is thrown. - /// - /// The expected value - /// The actual value - public static void AreNotEqual(double expected, double actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #region Objects - - /// - /// Verifies that two objects are not equal. Two objects are considered - /// equal if both are null, or if both have the same value. NUnit - /// has special semantics for some object types. - /// If they are equal an is thrown. - /// - /// The value that is expected - /// The actual value - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotEqual(object expected, object actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, args); - } - /// - /// Verifies that two objects are not equal. Two objects are considered - /// equal if both are null, or if both have the same value. NUnit - /// has special semantics for some object types. - /// If they are equal an is thrown. - /// - /// The value that is expected - /// The actual value - /// The message to display in case of failure - public static void AreNotEqual(object expected, object actual, string message) - { - Assert.That(actual, Is.Not.EqualTo(expected), message, null); - } - /// - /// Verifies that two objects are not equal. Two objects are considered - /// equal if both are null, or if both have the same value. NUnit - /// has special semantics for some object types. - /// If they are equal an is thrown. - /// - /// The value that is expected - /// The actual value - public static void AreNotEqual(object expected, object actual) - { - Assert.That(actual, Is.Not.EqualTo(expected), null, null); - } - - #endregion - - #endregion - - #region AreSame - - /// - /// Asserts that two objects refer to the same object. If they - /// are not the same an is thrown. - /// - /// The expected object - /// The actual object - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreSame(object expected, object actual, string message, params object[] args) - { - Assert.That(actual, Is.SameAs(expected), message, args); - } - /// - /// Asserts that two objects refer to the same object. If they - /// are not the same an is thrown. - /// - /// The expected object - /// The actual object - /// The message to display in case of failure - public static void AreSame(object expected, object actual, string message) - { - Assert.That(actual, Is.SameAs(expected), message, null); - } - /// - /// Asserts that two objects refer to the same object. If they - /// are not the same an is thrown. - /// - /// The expected object - /// The actual object - public static void AreSame(object expected, object actual) - { - Assert.That(actual, Is.SameAs(expected), null, null); - } - - #endregion - - #region AreNotSame - - /// - /// Asserts that two objects do not refer to the same object. If they - /// are the same an is thrown. - /// - /// The expected object - /// The actual object - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - public static void AreNotSame(object expected, object actual, string message, params object[] args) - { - Assert.That(actual, Is.Not.SameAs(expected), message, args); - } - /// - /// Asserts that two objects do not refer to the same object. If they - /// are the same an is thrown. - /// - /// The expected object - /// The actual object - /// The message to display in case of failure - public static void AreNotSame(object expected, object actual, string message) - { - Assert.That(actual, Is.Not.SameAs(expected), message, null); - } - /// - /// Asserts that two objects do not refer to the same object. If they - /// are the same an is thrown. - /// - /// The expected object - /// The actual object - public static void AreNotSame(object expected, object actual) - { - Assert.That(actual, Is.Not.SameAs(expected), null, null); - } - - #endregion - - #region Helper Methods - - /// - /// Helper for Assert.AreEqual(double expected, double actual, ...) - /// allowing code generation to work consistently. - /// - /// The expected value - /// The actual value - /// The maximum acceptable difference between the - /// the expected and the actual - /// The message to display in case of failure - /// Array of objects to be used in formatting the message - protected static void AssertDoublesAreEqual(double expected, double actual, double delta, string message, object[] args) - { - if (double.IsNaN(expected) || double.IsInfinity(expected)) - Assert.That(actual, Is.EqualTo(expected), message, args); - else - Assert.That(actual, Is.EqualTo(expected).Within(delta), message, args); - } - - private static void IncrementAssertCount() - { - TestExecutionContext.CurrentContext.IncrementAssertCount(); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/AssertionHelper.cs b/test/NUnitLite/src/framework/AssertionHelper.cs deleted file mode 100644 index 38869af5d..000000000 --- a/test/NUnitLite/src/framework/AssertionHelper.cs +++ /dev/null @@ -1,366 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Collections; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework -{ - /// - /// AssertionHelper is an optional base class for user tests, - /// allowing the use of shorter names for constraints and - /// asserts and avoiding conflict with the definition of - /// , from which it inherits much of its - /// behavior, in certain mock object frameworks. - /// - public class AssertionHelper : ConstraintFactory - { - #region Assert - //private Assertions assert = new Assertions(); - //public virtual Assertions Assert - //{ - // get { return assert; } - //} - #endregion - - #region Expect - - #region Object - -#if !CLR_2_0 && !CLR_4_0 - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. Works - /// identically to Assert.That. - /// - /// The actual value to test - /// A Constraint to be applied - public void Expect(object actual, IResolveConstraint expression) - { - Assert.That(actual, expression, null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. Works - /// identically to Assert.That. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message to be displayed in case of failure - public void Expect(object actual, IResolveConstraint expression, string message) - { - Assert.That(actual, expression, message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. Works - /// identically to Assert.That. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message to be displayed in case of failure - /// Arguments to use in formatting the message - public void Expect(object actual, IResolveConstraint expression, string message, params object[] args) - { - Assert.That(actual, expression, message, args); - } -#endif - - #endregion - - #region Boolean - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . Works Identically to - /// . - /// - /// The evaluated condition - /// The message to display if the condition is false - /// Arguments to be used in formatting the message - public void Expect(bool condition, string message, params object[] args) - { - Assert.That(condition, Is.True, message, args); - } - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . Works Identically to - /// . - /// - /// The evaluated condition - /// The message to display if the condition is false - public void Expect(bool condition, string message) - { - Assert.That(condition, Is.True, message, null); - } - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . Works Identically to . - /// - /// The evaluated condition - public void Expect(bool condition) - { - Assert.That(condition, Is.True, null, null); - } - - #endregion - - #region ref Boolean - -#if !CLR_2_0 && !CLR_4_0 - /// - /// Apply a constraint to a referenced boolean, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint to be applied - /// The actual value to test - public void Expect(ref bool actual, IResolveConstraint constraint) - { - Assert.That(ref actual, constraint.Resolve(), null, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint to be applied - /// The actual value to test - /// The message that will be displayed on failure - public void Expect(ref bool actual, IResolveConstraint constraint, string message) - { - Assert.That(ref actual, constraint.Resolve(), message, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public void Expect(ref bool actual, IResolveConstraint expression, string message, params object[] args) - { - Assert.That(ref actual, expression, message, args); - } -#endif - - #endregion - - #region ActualValueDelegate - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - public void Expect(ActualValueDelegate del, IResolveConstraint expr) - { - Assert.That(del, expr.Resolve(), null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - /// The message that will be displayed on failure - public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message) - { - Assert.That(del, expr.Resolve(), message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args) - { - Assert.That(del, expr, message, args); - } -#else - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - public void Expect(ActualValueDelegate del, IResolveConstraint expr) - { - Assert.That(del, expr.Resolve(), null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - /// The message that will be displayed on failure - public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message) - { - Assert.That(del, expr.Resolve(), message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args) - { - Assert.That(del, expr, message, args); - } -#endif - - #endregion - - #region ref Object - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - public void Expect(ref T actual, IResolveConstraint expression) - { - Assert.That(ref actual, expression, null, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - public void Expect(ref T actual, IResolveConstraint expression, string message) - { - Assert.That(ref actual, expression, message, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// The actual value to test - /// A Constraint to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - public void Expect(ref T actual, IResolveConstraint expression, string message, params object[] args) - { - Assert.That(ref actual, expression, message, args); - } -#endif - - #endregion - - #region TestDelegate - - /// - /// Asserts that the code represented by a delegate throws an exception - /// that satisfies the constraint provided. - /// - /// A TestDelegate to be executed - /// A ThrowsConstraint used in the test - public void Expect(TestDelegate code, IResolveConstraint constraint) - { - Assert.That((object)code, constraint); - } - - #endregion - - #endregion - - #region Expect - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint to be applied - /// The actual value to test - static public void Expect(T actual, IResolveConstraint expression) - { - Assert.That(actual, expression, null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint to be applied - /// The actual value to test - /// The message that will be displayed on failure - static public void Expect(T actual, IResolveConstraint expression, string message) - { - Assert.That(actual, expression, message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an assertion exception on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void Expect(T actual, IResolveConstraint expression, string message, params object[] args) - { - Assert.That(actual, expression, message, args); - } - -#endif - - #endregion - - #region Map - /// - /// Returns a ListMapper based on a collection. - /// - /// The original collection - /// - public ListMapper Map( ICollection original ) - { - return new ListMapper( original ); - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Assume.cs b/test/NUnitLite/src/framework/Assume.cs deleted file mode 100644 index d1581c420..000000000 --- a/test/NUnitLite/src/framework/Assume.cs +++ /dev/null @@ -1,360 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.ComponentModel; -using NUnit.Framework.Constraints; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// Provides static methods to express the assumptions - /// that must be met for a test to give a meaningful - /// result. If an assumption is not met, the test - /// should produce an inconclusive result. - /// - public class Assume - { - #region Equals and ReferenceEquals - - /// - /// The Equals method throws an AssertionException. This is done - /// to make sure there is no mistake by calling this function. - /// - /// - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static new bool Equals(object a, object b) - { - // TODO: This should probably be InvalidOperationException - throw new AssertionException("Assert.Equals should not be used for Assertions"); - } - - /// - /// override the default ReferenceEquals to throw an AssertionException. This - /// implementation makes sure there is no mistake in calling this function - /// as part of Assert. - /// - /// - /// - public static new void ReferenceEquals(object a, object b) - { - throw new AssertionException("Assert.ReferenceEquals should not be used for Assertions"); - } - - #endregion - - #region Assume.That - - #region Object - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - static public void That(object actual, IResolveConstraint expression) - { - Assume.That(actual, expression, null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - /// The message that will be displayed on failure - static public void That(object actual, IResolveConstraint expression, string message) - { - Assume.That(actual, expression, message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(object actual, IResolveConstraint expression, string message, params object[] args) - { - Constraint constraint = expression.Resolve(); - - if (!constraint.Matches(actual)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new InconclusiveException(writer.ToString()); - } - } - #endregion - - #region Boolean - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display if the condition is false - /// Arguments to be used in formatting the message - static public void That(bool condition, string message, params object[] args) - { - Assume.That(condition, Is.True, message, args); - } - - /// - /// Asserts that a condition is true. If the condition is false the method throws - /// an . - /// - /// The evaluated condition - /// The message to display if the condition is false - static public void That(bool condition, string message) - { - Assume.That(condition, Is.True, message, null); - } - - /// - /// Asserts that a condition is true. If the condition is false the - /// method throws an . - /// - /// The evaluated condition - static public void That(bool condition) - { - Assume.That(condition, Is.True, null, null); - } - - #endregion - - #region ref Boolean - -#if !CLR_2_0 && !CLR_4_0 - /// - /// Apply a constraint to a referenced boolean, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - static public void That(ref bool actual, IResolveConstraint expression) - { - Assume.That(ref actual, expression.Resolve(), null, null); - } - - /// - /// Apply a constraint to a referenced boolean, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - /// The message that will be displayed on failure - static public void That(ref bool actual, IResolveConstraint expression, string message) - { - Assume.That(ref actual, expression.Resolve(), message, null); - } - - /// - /// Apply a constraint to a referenced boolean, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// The actual value to test - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ref bool actual, IResolveConstraint expression, string message, params object[] args) - { - Constraint constraint = expression.Resolve(); - - if (!constraint.Matches(ref actual)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new InconclusiveException(writer.ToString()); - } - } -#endif - - #endregion - - #region ActualValueDelegate - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - static public void That(ActualValueDelegate del, IResolveConstraint expr) - { - Assume.That(del, expr.Resolve(), null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - /// The message that will be displayed on failure - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message) - { - Assume.That(del, expr.Resolve(), message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args) - { - Constraint constraint = expr.Resolve(); - - if (!constraint.Matches(del)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new InconclusiveException(writer.ToString()); - } - } -#else - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - static public void That(ActualValueDelegate del, IResolveConstraint expr) - { - Assume.That(del, expr.Resolve(), null, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// An ActualValueDelegate returning the value to be tested - /// The message that will be displayed on failure - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message) - { - Assume.That(del, expr.Resolve(), message, null); - } - - /// - /// Apply a constraint to an actual value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// An ActualValueDelegate returning the value to be tested - /// A Constraint expression to be applied - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args) - { - Constraint constraint = expr.Resolve(); - - if (!constraint.Matches(del)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new InconclusiveException(writer.ToString()); - } - } -#endif - - #endregion - - #region ref Object - -#if CLR_2_0 || CLR_4_0 - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - static public void That(ref T actual, IResolveConstraint expression) - { - Assume.That(ref actual, expression.Resolve(), null, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - /// The message that will be displayed on failure - static public void That(ref T actual, IResolveConstraint expression, string message) - { - Assume.That(ref actual, expression.Resolve(), message, null); - } - - /// - /// Apply a constraint to a referenced value, succeeding if the constraint - /// is satisfied and throwing an InconclusiveException on failure. - /// - /// A Constraint expression to be applied - /// The actual value to test - /// The message that will be displayed on failure - /// Arguments to be used in formatting the message - static public void That(ref T actual, IResolveConstraint expression, string message, params object[] args) - { - Constraint constraint = expression.Resolve(); - - if (!constraint.Matches(ref actual)) - { - MessageWriter writer = new TextMessageWriter(message, args); - constraint.WriteMessageTo(writer); - throw new InconclusiveException(writer.ToString()); - } - } -#endif - - #endregion - - #region TestDelegate - - /// - /// Asserts that the code represented by a delegate throws an exception - /// that satisfies the constraint provided. - /// - /// A TestDelegate to be executed - /// A ThrowsConstraint used in the test - static public void That(TestDelegate code, IResolveConstraint constraint) - { - Assume.That((object)code, constraint); - } - - #endregion - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/CategoryAttribute.cs b/test/NUnitLite/src/framework/Attributes/CategoryAttribute.cs deleted file mode 100644 index d859b4a63..000000000 --- a/test/NUnitLite/src/framework/Attributes/CategoryAttribute.cs +++ /dev/null @@ -1,95 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// Attribute used to apply a category to a test - /// - [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=true, Inherited=true)] - public class CategoryAttribute : NUnitAttribute, IApplyToTest - { - /// - /// The name of the category - /// - protected string categoryName; - - /// - /// Construct attribute for a given category based on - /// a name. The name may not contain the characters ',', - /// '+', '-' or '!'. However, this is not checked in the - /// constructor since it would cause an error to arise at - /// as the test was loaded without giving a clear indication - /// of where the problem is located. The error is handled - /// in NUnitFramework.cs by marking the test as not - /// runnable. - /// - /// The name of the category - public CategoryAttribute(string name) - { - this.categoryName = name.Trim(); - } - - /// - /// Protected constructor uses the Type name as the name - /// of the category. - /// - protected CategoryAttribute() - { - this.categoryName = this.GetType().Name; - if ( categoryName.EndsWith( "Attribute" ) ) - categoryName = categoryName.Substring( 0, categoryName.Length - 9 ); - } - - /// - /// The name of the category - /// - public string Name - { - get { return categoryName; } - } - - #region IApplyToTest Members - - /// - /// Modifies a test by adding a category to it. - /// - /// The test to modify - public void ApplyToTest(Test test) - { - test.Properties.Add(PropertyNames.Category, this.Name); - - if (this.Name.IndexOfAny(new char[] { ',', '!', '+', '-' }) >= 0) - { - test.RunState = RunState.NotRunnable; - test.Properties.Set(PropertyNames.SkipReason, "Category name must not contain ',', '!', '+' or '-'"); - } - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/ExpectedExceptionAttribute.cs b/test/NUnitLite/src/framework/Attributes/ExpectedExceptionAttribute.cs deleted file mode 100644 index 790cd1ce7..000000000 --- a/test/NUnitLite/src/framework/Attributes/ExpectedExceptionAttribute.cs +++ /dev/null @@ -1,175 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Api; - -namespace NUnit.Framework -{ - /// - /// ExpectedExceptionAttribute - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited=false)] - public class ExpectedExceptionAttribute : NUnitAttribute - { - private ExpectedExceptionData exceptionData = new ExpectedExceptionData(); - - /// - /// Constructor for a non-specific exception - /// - public ExpectedExceptionAttribute() - { - } - - /// - /// Constructor for a given type of exception - /// - /// The type of the expected exception - public ExpectedExceptionAttribute(Type exceptionType) - { - exceptionData.ExpectedExceptionType = exceptionType; - } - - /// - /// Constructor for a given exception name - /// - /// The full name of the expected exception - public ExpectedExceptionAttribute(string exceptionName) - { - exceptionData.ExpectedExceptionName = exceptionName; - } - - /// - /// Gets or sets the expected exception type - /// - public Type ExpectedException - { - get { return exceptionData.ExpectedExceptionType; } - set { exceptionData.ExpectedExceptionType = value; } - } - - /// - /// Gets or sets the full Type name of the expected exception - /// - public string ExpectedExceptionName - { - get { return exceptionData.ExpectedExceptionName; } - set { exceptionData.ExpectedExceptionName = value; } - } - - /// - /// Gets or sets the expected message text - /// - public string ExpectedMessage - { - get { return exceptionData.ExpectedMessage; } - set { exceptionData.ExpectedMessage = value; } - } - - /// - /// Gets or sets the user message displayed in case of failure - /// - public string UserMessage - { - get { return exceptionData.UserMessage; } - set { exceptionData.UserMessage = value; } - } - - /// - /// Gets or sets the type of match to be performed on the expected message - /// - public MessageMatch MatchType - { - get { return exceptionData.MatchType; } - set { exceptionData.MatchType = value; } - } - - /// - /// Gets the name of a method to be used as an exception handler - /// - public string Handler - { - get { return exceptionData.HandlerName; } - set { exceptionData.HandlerName = value; } - } - - /// - /// Gets all data about the expected exception. - /// - public ExpectedExceptionData ExceptionData - { - get { return exceptionData; } - } - - //#region IApplyToTest Members - - //void IApplyToTest.ApplyToTest(ITest test) - //{ - // TestMethod testMethod = test as TestMethod; - // if (testMethod != null) - // testMethod.CustomDecorators.Add(new ExpectedExceptionDecorator()); - //} - - //#endregion - } - - /// - /// ExpectedExceptionDecorator applies to a TestCommand and returns - /// a success result only if the expected exception is thrown. - /// Otherwise, an appropriate failure result is returned. - /// - public class ExpectedExceptionDecorator : ICommandDecorator - { - private ExpectedExceptionData exceptionData; - - /// - /// Construct an ExpectedExceptionDecorator using specified data. - /// - /// Data describing the expected exception - public ExpectedExceptionDecorator(ExpectedExceptionData exceptionData) - { - this.exceptionData = exceptionData; - } - - #region ICommandDecorator Members - - CommandStage ICommandDecorator.Stage - { - get { return CommandStage.BelowSetUpTearDown; } - } - - int ICommandDecorator.Priority - { - get { return 0; } - } - - TestCommand ICommandDecorator.Decorate(TestCommand command) - { - return new ExpectedExceptionCommand(command, exceptionData); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/ExplicitAttribute.cs b/test/NUnitLite/src/framework/Attributes/ExplicitAttribute.cs deleted file mode 100644 index 3c466dbd1..000000000 --- a/test/NUnitLite/src/framework/Attributes/ExplicitAttribute.cs +++ /dev/null @@ -1,75 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// ExplicitAttribute marks a test or test fixture so that it will - /// only be run if explicitly executed from the gui or command line - /// or if it is included by use of a filter. The test will not be - /// run simply because an enclosing suite is run. - /// - [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)] - public class ExplicitAttribute : NUnitAttribute, IApplyToTest - { - private string reason; - - /// - /// Default constructor - /// - public ExplicitAttribute() - { - this.reason = ""; - } - - /// - /// Constructor with a reason - /// - /// The reason test is marked explicit - public ExplicitAttribute(string reason) - { - this.reason = reason; - } - - #region IApplyToTest members - - /// - /// Modifies a test by marking it as explicit. - /// - /// The test to modify - public void ApplyToTest(Test test) - { - if (test.RunState != RunState.NotRunnable) - { - test.RunState = RunState.Explicit; - test.Properties.Set(PropertyNames.SkipReason, reason); - } - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/IgnoreAttribute.cs b/test/NUnitLite/src/framework/Attributes/IgnoreAttribute.cs deleted file mode 100644 index 48fdb5aa6..000000000 --- a/test/NUnitLite/src/framework/Attributes/IgnoreAttribute.cs +++ /dev/null @@ -1,75 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// Attribute used to mark a test that is to be ignored. - /// Ignored tests result in a warning message when the - /// tests are run. - /// - [AttributeUsage(AttributeTargets.Method|AttributeTargets.Class|AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)] - public class IgnoreAttribute : NUnitAttribute, IApplyToTest - { - private string reason; - - /// - /// Constructs the attribute without giving a reason - /// for ignoring the test. - /// - public IgnoreAttribute() - { - this.reason = ""; - } - - /// - /// Constructs the attribute giving a reason for ignoring the test - /// - /// The reason for ignoring the test - public IgnoreAttribute(string reason) - { - this.reason = reason; - } - - #region IApplyToTest members - - /// - /// Modifies a test by marking it as Ignored. - /// - /// The test to modify - public void ApplyToTest(Test test) - { - if (test.RunState != RunState.NotRunnable) - { - test.RunState = RunState.Ignored; - test.Properties.Set(PropertyNames.SkipReason, reason); - } - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/IncludeExcludeAttribute.cs b/test/NUnitLite/src/framework/Attributes/IncludeExcludeAttribute.cs deleted file mode 100644 index 762d911a6..000000000 --- a/test/NUnitLite/src/framework/Attributes/IncludeExcludeAttribute.cs +++ /dev/null @@ -1,83 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework -{ - /// - /// Abstract base for Attributes that are used to include tests - /// in the test run based on environmental settings. - /// - public abstract class IncludeExcludeAttribute : NUnitAttribute - { - private string include; - private string exclude; - private string reason; - - /// - /// Constructor with no included items specified, for use - /// with named property syntax. - /// - public IncludeExcludeAttribute() { } - - /// - /// Constructor taking one or more included items - /// - /// Comma-delimited list of included items - public IncludeExcludeAttribute( string include ) - { - this.include = include; - } - - /// - /// Name of the item that is needed in order for - /// a test to run. Multiple itemss may be given, - /// separated by a comma. - /// - public string Include - { - get { return this.include; } - set { include = value; } - } - - /// - /// Name of the item to be excluded. Multiple items - /// may be given, separated by a comma. - /// - public string Exclude - { - get { return this.exclude; } - set { this.exclude = value; } - } - - /// - /// The reason for including or excluding the test - /// - public string Reason - { - get { return reason; } - set { reason = value; } - } - } -} diff --git a/test/NUnitLite/src/framework/Attributes/MaxTimeAttribute.cs b/test/NUnitLite/src/framework/Attributes/MaxTimeAttribute.cs deleted file mode 100644 index 4e297225b..000000000 --- a/test/NUnitLite/src/framework/Attributes/MaxTimeAttribute.cs +++ /dev/null @@ -1,63 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// Summary description for MaxTimeAttribute. - /// - [AttributeUsage( AttributeTargets.Method, AllowMultiple=false, Inherited=false )] - public sealed class MaxTimeAttribute : PropertyAttribute, ICommandDecorator - { - /// - /// Construct a MaxTimeAttribute, given a time in milliseconds. - /// - /// The maximum elapsed time in milliseconds - public MaxTimeAttribute( int milliseconds ) - : base( milliseconds ) { } - - #region ICommandDecorator Members - - CommandStage ICommandDecorator.Stage - { - get { return CommandStage.AboveSetUpTearDown; } - } - - int ICommandDecorator.Priority - { - get { return 0; } - } - - TestCommand ICommandDecorator.Decorate(TestCommand command) - { - return new MaxTimeCommand(command); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/RandomAttribute.cs b/test/NUnitLite/src/framework/Attributes/RandomAttribute.cs deleted file mode 100644 index 33813fd59..000000000 --- a/test/NUnitLite/src/framework/Attributes/RandomAttribute.cs +++ /dev/null @@ -1,126 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// RandomAttribute is used to supply a set of random values - /// to a single parameter of a parameterized test. - /// - public class RandomAttribute : ValuesAttribute, IParameterDataSource - { - enum SampleType - { - Auto, - Raw, - IntRange, - DoubleRange - } - - SampleType sampleType; - private int count; - private int min, max; - private double dmin, dmax; - - /// - /// Construct a set of Enums if the type is an Enum otherwise - /// Construct a set of doubles from 0.0 to 1.0, - /// specifying only the count. - /// - /// - public RandomAttribute(int count) - { - this.count = count; - this.sampleType = SampleType.Raw; - } - - /// - /// Construct a set of doubles from min to max - /// - /// - /// - /// - public RandomAttribute(double min, double max, int count) - { - this.count = count; - this.dmin = min; - this.dmax = max; - this.sampleType = SampleType.DoubleRange; - } - - /// - /// Construct a set of ints from min to max - /// - /// - /// - /// - public RandomAttribute(int min, int max, int count) - { - this.count = count; - this.min = min; - this.max = max; - this.sampleType = SampleType.IntRange; - } - - /// - /// Get the collection of values to be used as arguments - /// - public new IEnumerable GetData(ParameterInfo parameter) - { - Randomizer r = Randomizer.GetRandomizer(parameter); - IList values; - - switch (sampleType) - { - default: - case SampleType.Raw: - if (parameter.ParameterType.IsEnum) - values = r.GetEnums(count,parameter.ParameterType); - else - values = r.GetDoubles(count); - break; - case SampleType.IntRange: - values = r.GetInts(min, max, count); - break; - case SampleType.DoubleRange: - values = r.GetDoubles(dmin, dmax, count); - break; - } - - // Copy the random values into the data array - // and call the base class which may need to - // convert them to another type. - this.data = new object[values.Count]; - for (int i = 0; i < values.Count; i++) - this.data[i] = values[i]; - - return base.GetData(parameter); - } - } -} diff --git a/test/NUnitLite/src/framework/Attributes/RangeAttribute.cs b/test/NUnitLite/src/framework/Attributes/RangeAttribute.cs deleted file mode 100644 index 04252980e..000000000 --- a/test/NUnitLite/src/framework/Attributes/RangeAttribute.cs +++ /dev/null @@ -1,104 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework -{ - /// - /// RangeAttribute is used to supply a range of values to an - /// individual parameter of a parameterized test. - /// - public class RangeAttribute : ValuesAttribute - { - /// - /// Construct a range of ints using default step of 1 - /// - /// - /// - public RangeAttribute(int from, int to) : this(from, to, 1) { } - - /// - /// Construct a range of ints specifying the step size - /// - /// - /// - /// - public RangeAttribute(int from, int to, int step) - { - int count = (to - from) / step + 1; - this.data = new object[count]; - int index = 0; - for (int val = from; index < count; val += step) - this.data[index++] = val; - } - - /// - /// Construct a range of longs - /// - /// - /// - /// - public RangeAttribute(long from, long to, long step) - { - long count = (to - from) / step + 1; - this.data = new object[count]; - int index = 0; - for (long val = from; index < count; val += step) - this.data[index++] = val; - } - - /// - /// Construct a range of doubles - /// - /// - /// - /// - public RangeAttribute(double from, double to, double step) - { - double tol = step / 1000; - int count = (int)((to - from) / step + tol + 1); - this.data = new object[count]; - int index = 0; - for (double val = from; index < count; val += step) - this.data[index++] = val; - } - - /// - /// Construct a range of floats - /// - /// - /// - /// - public RangeAttribute(float from, float to, float step) - { - float tol = step / 1000; - int count = (int)((to - from) / step + tol + 1); - this.data = new object[count]; - int index = 0; - for (float val = from; index < count; val += step) - this.data[index++] = val; - } - } -} diff --git a/test/NUnitLite/src/framework/Attributes/RepeatAttribute.cs b/test/NUnitLite/src/framework/Attributes/RepeatAttribute.cs deleted file mode 100644 index 91a7a7d9d..000000000 --- a/test/NUnitLite/src/framework/Attributes/RepeatAttribute.cs +++ /dev/null @@ -1,90 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if false -// TODO: Rework this -// RepeatAttribute should either -// 1) Apply at load time to create the exact number of tests, or -// 2) Apply at run time, generating tests or results dynamically -// -// #1 is feasible but doesn't provide much benefit -// #2 requires infrastructure for dynamic test cases first -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal.Commands; - -namespace NUnit.Framework -{ - /// - /// RepeatAttribute may be applied to test case in order - /// to run it multiple times. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)] - public class RepeatAttribute : PropertyAttribute, ICommandDecorator - { - /// - /// Construct a RepeatAttribute - /// - /// The number of times to run the test - public RepeatAttribute(int count) : base(count) { } - - //private int count; - - ///// - ///// Construct a RepeatAttribute - ///// - ///// The number of times to run the test - //public RepeatAttribute(int count) - //{ - // this.count = count; - //} - - ///// - ///// Gets the number of times to run the test. - ///// - //public int Count - //{ - // get { return count; } - //} - - #region ICommandDecorator Members - - CommandStage ICommandDecorator.Stage - { - get { return CommandStage.Repeat; } - } - - int ICommandDecorator.Priority - { - get { return 0; } - } - - TestCommand ICommandDecorator.Decorate(TestCommand command) - { - return new RepeatedTestCommand(command); - } - - #endregion - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Attributes/TestAttribute.cs b/test/NUnitLite/src/framework/Attributes/TestAttribute.cs deleted file mode 100644 index b92e45e26..000000000 --- a/test/NUnitLite/src/framework/Attributes/TestAttribute.cs +++ /dev/null @@ -1,79 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework -{ - using System; - using NUnit.Framework.Api; - using NUnit.Framework.Internal; - - /// - /// Adding this attribute to a method within a - /// class makes the method callable from the NUnit test runner. There is a property - /// called Description which is optional which you can provide a more detailed test - /// description. This class cannot be inherited. - /// - /// - /// - /// [TestFixture] - /// public class Fixture - /// { - /// [Test] - /// public void MethodToTest() - /// {} - /// - /// [Test(Description = "more detailed description")] - /// publc void TestDescriptionMethod() - /// {} - /// } - /// - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] - public class TestAttribute : NUnitAttribute, IApplyToTest - { - private string description; - - /// - /// Descriptive text for this test - /// - public string Description - { - get { return description; } - set { description = value; } - } - - #region IApplyToTest Members - - /// - /// Modifies a test by adding a description, if not already set. - /// - /// The test to modify - public void ApplyToTest(Test test) - { - if (!test.Properties.ContainsKey(PropertyNames.Description) && description != null) - test.Properties.Set(PropertyNames.Description, description); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/TestCaseAttribute.cs b/test/NUnitLite/src/framework/Attributes/TestCaseAttribute.cs deleted file mode 100644 index 92e86a79d..000000000 --- a/test/NUnitLite/src/framework/Attributes/TestCaseAttribute.cs +++ /dev/null @@ -1,446 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// TestCaseAttribute is used to mark parameterized test cases - /// and provide them with their arguments. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)] - public class TestCaseAttribute : DataAttribute, ITestCaseData, ITestCaseSource - { - #region Instance variables - - private object[] arguments; - // NOTE: Ignore unsupressed warning about exceptionData in .NET 1.1 build - private ExpectedExceptionData exceptionData; - private object expectedResult; - private bool hasExpectedResult; - private IPropertyBag properties; - private RunState runState; - - #endregion - - #region Constructors - - /// - /// Construct a TestCaseAttribute with a list of arguments. - /// This constructor is not CLS-Compliant - /// - /// - public TestCaseAttribute(params object[] arguments) - { - this.runState = RunState.Runnable; - - if (arguments == null) - this.arguments = new object[] { null }; - else - this.arguments = arguments; - } - - /// - /// Construct a TestCaseAttribute with a single argument - /// - /// - public TestCaseAttribute(object arg) - { - this.runState = RunState.Runnable; - this.arguments = new object[] { arg }; - } - - /// - /// Construct a TestCaseAttribute with a two arguments - /// - /// - /// - public TestCaseAttribute(object arg1, object arg2) - { - this.runState = RunState.Runnable; - this.arguments = new object[] { arg1, arg2 }; - } - - /// - /// Construct a TestCaseAttribute with a three arguments - /// - /// - /// - /// - public TestCaseAttribute(object arg1, object arg2, object arg3) - { - this.runState = RunState.Runnable; - this.arguments = new object[] { arg1, arg2, arg3 }; - } - - #endregion - - #region Properties - - /// - /// Gets the list of arguments to a test case - /// - public object[] Arguments - { - get { return arguments; } - } - - /// - /// Gets or sets the expected result. - /// - /// The result. - public object ExpectedResult - { - get { return expectedResult; } - set - { - expectedResult = value; - hasExpectedResult = true; - } - } - - /// - /// Gets the expected result (alias for use - /// by NUnit 2.6.x runners and for use - /// in legacy code. Remove the setter - /// after a time.) - /// - [Obsolete("Use ExpectedResult")] - public object Result - { - get { return ExpectedResult; } - set { ExpectedResult = value; } - } - - /// - /// Returns true if the expected result has been set - /// - public bool HasExpectedResult - { - get { return hasExpectedResult; } - } - - /// - /// Gets data about any expected exception for this test case. - /// - public ExpectedExceptionData ExceptionData - { - get { return exceptionData; } - } - - /// - /// Gets or sets the expected exception. - /// - /// The expected exception. - public Type ExpectedException - { - get { return exceptionData.ExpectedExceptionType; } - set { exceptionData.ExpectedExceptionType = value; } - } - - /// - /// Gets or sets the name the expected exception. - /// - /// The expected name of the exception. - public string ExpectedExceptionName - { - get { return exceptionData.ExpectedExceptionName; } - set { exceptionData.ExpectedExceptionName = value; } - } - - /// - /// Gets or sets the expected message of the expected exception - /// - /// The expected message of the exception. - public string ExpectedMessage - { - get { return exceptionData.ExpectedMessage; } - set { exceptionData.ExpectedMessage = value; } - } - - /// - /// Gets or sets the type of match to be performed on the expected message - /// - public MessageMatch MatchType - { - get { return exceptionData.MatchType; } - set { exceptionData.MatchType = value; } - } - - /// - /// Gets or sets the description. - /// - /// The description. - public string Description - { - get { return this.Properties.Get(PropertyNames.Description) as string; } - set { this.Properties.Set(PropertyNames.Description, value); } - } - - private string testName; - /// - /// Gets or sets the name of the test. - /// - /// The name of the test. - public string TestName - { - get { return testName; } - set { testName = value; } - } - - /// - /// Gets or sets the ignored status of the test - /// - public bool Ignore - { - get { return this.RunState == RunState.Ignored; } - set { this.runState = value ? RunState.Ignored : RunState.Runnable; } - } - - /// - /// Gets or sets a value indicating whether this is explicit. - /// - /// - /// true if explicit; otherwise, false. - /// - public bool Explicit - { - get { return this.RunState == RunState.Explicit; } - set { this.runState = value ? RunState.Explicit : RunState.Runnable; } - } - - /// - /// Gets the RunState of this test case. - /// - public RunState RunState - { - get { return runState; } - } - - /// - /// Gets or sets the reason for not running the test. - /// - /// The reason. - public string Reason - { - get { return this.Properties.Get(PropertyNames.SkipReason) as string; } - set { this.Properties.Set(PropertyNames.SkipReason, value); } - } - - /// - /// Gets or sets the ignore reason. When set to a non-null - /// non-empty value, the test is marked as ignored. - /// - /// The ignore reason. - public string IgnoreReason - { - get { return this.Reason; } - set - { - this.runState = RunState.Ignored; - this.Reason = value; - } - } - - /// - /// Gets and sets the category for this fixture. - /// May be a comma-separated list of categories. - /// - public string Category - { - get { return Properties.Get(PropertyNames.Category) as string; } - set - { - foreach (string cat in value.Split(new char[] { ',' }) ) - Properties.Add(PropertyNames.Category, cat); - } - } - - /// - /// Gets a list of categories for this fixture - /// - public IList Categories - { - get { return Properties[PropertyNames.Category] as IList; } - } - - /// - /// NYI - /// - public IPropertyBag Properties - { - get - { - if (properties == null) - properties = new PropertyBag(); - - return properties; - } - } - - #endregion - - #region ITestCaseSource Members - - /// - /// Returns an collection containing a single ITestCaseData item, - /// constructed from the arguments provided in the constructor and - /// possibly converted to match the specified method. - /// - /// The method for which data is being provided - /// -#if CLR_2_0 || CLR_4_0 - public System.Collections.Generic.IEnumerable GetTestCasesFor(System.Reflection.MethodInfo method) -#else - public System.Collections.IEnumerable GetTestCasesFor(System.Reflection.MethodInfo method) -#endif - { - ParameterSet parms; - - try - { - ParameterInfo[] parameters = method.GetParameters(); - int argsNeeded = parameters.Length; - int argsProvided = Arguments.Length; - - parms = new ParameterSet(this); - - // Special handling for params arguments - if (argsNeeded > 0 && argsProvided >= argsNeeded - 1) - { - ParameterInfo lastParameter = parameters[argsNeeded - 1]; - Type lastParameterType = lastParameter.ParameterType; - Type elementType = lastParameterType.GetElementType(); - - if (lastParameterType.IsArray && lastParameter.IsDefined(typeof(ParamArrayAttribute), false)) - { - if (argsProvided == argsNeeded) - { - Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType(); - if (!lastParameterType.IsAssignableFrom(lastArgumentType)) - { - Array array = Array.CreateInstance(elementType, 1); - array.SetValue(parms.Arguments[argsProvided - 1], 0); - parms.Arguments[argsProvided - 1] = array; - } - } - else - { - object[] newArglist = new object[argsNeeded]; - for (int i = 0; i < argsNeeded && i < argsProvided; i++) - newArglist[i] = parms.Arguments[i]; - - int length = argsProvided - argsNeeded + 1; - Array array = Array.CreateInstance(elementType, length); - for (int i = 0; i < length; i++) - array.SetValue(parms.Arguments[argsNeeded + i - 1], i); - - newArglist[argsNeeded - 1] = array; - parms.Arguments = newArglist; - argsProvided = argsNeeded; - } - } - } - - //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) - // parms.Arguments = new object[]{parms.Arguments}; - - // Special handling when sole argument is an object[] - if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) - { - if (argsProvided > 1 || - argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[])) - { - parms.Arguments = new object[] { parms.Arguments }; - } - } - - if (argsProvided == argsNeeded) - PerformSpecialConversions(parms.Arguments, parameters); - } - catch (Exception ex) - { - parms = new ParameterSet(ex); - } - - return new ITestCaseData[] { parms }; - } - - #endregion - - #region Helper Methods - /// - /// Performs several special conversions allowed by NUnit in order to - /// permit arguments with types that cannot be used in the constructor - /// of an Attribute such as TestCaseAttribute or to simplify their use. - /// - /// The arguments to be converted - /// The ParameterInfo array for the method - private static void PerformSpecialConversions(object[] arglist, ParameterInfo[] parameters) - { - for (int i = 0; i < arglist.Length; i++) - { - object arg = arglist[i]; - Type targetType = parameters[i].ParameterType; - - if (arg == null) - continue; - - if (arg is SpecialValue && (SpecialValue)arg == SpecialValue.Null) - { - arglist[i] = null; - continue; - } - - if (targetType.IsAssignableFrom(arg.GetType())) - continue; - - if (arg is DBNull) - { - arglist[i] = null; - continue; - } - - bool convert = false; - - if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte)) - convert = arg is int; - else - if (targetType == typeof(decimal)) - convert = arg is double || arg is string || arg is int; - else - if (targetType == typeof(DateTime) || targetType == typeof(TimeSpan)) - convert = arg is string; - - if (convert) - arglist[i] = Convert.ChangeType(arg, targetType, System.Globalization.CultureInfo.InvariantCulture); - } - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/TestCaseSourceAttribute.cs b/test/NUnitLite/src/framework/Attributes/TestCaseSourceAttribute.cs deleted file mode 100644 index a2e9ef530..000000000 --- a/test/NUnitLite/src/framework/Attributes/TestCaseSourceAttribute.cs +++ /dev/null @@ -1,212 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// TestCaseSourceAttribute indicates the source to be used to - /// provide test cases for a test method. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] - public class TestCaseSourceAttribute : DataAttribute, ITestCaseSource - { - private readonly string sourceName; - private readonly Type sourceType; - - /// - /// Construct with the name of the method, property or field that will prvide data - /// - /// The name of the method, property or field that will provide data - public TestCaseSourceAttribute(string sourceName) - { - this.sourceName = sourceName; - } - - /// - /// Construct with a Type and name - /// - /// The Type that will provide data - /// The name of the method, property or field that will provide data - public TestCaseSourceAttribute(Type sourceType, string sourceName) - { - this.sourceType = sourceType; - this.sourceName = sourceName; - } - - /// - /// Construct with a Type - /// - /// The type that will provide data - public TestCaseSourceAttribute(Type sourceType) - { - this.sourceType = sourceType; - } - - /// - /// The name of a the method, property or fiend to be used as a source - /// - public string SourceName - { - get { return sourceName; } - } - - /// - /// A Type to be used as a source - /// - public Type SourceType - { - get { return sourceType; } - } - - private string category; - /// - /// Gets or sets the category associated with this test. - /// May be a single category or a comma-separated list. - /// - public string Category - { - get { return category; } - set { category = value; } - } - - #region ITestCaseSource Members - /// - /// Returns a set of ITestCaseDataItems for use as arguments - /// to a parameterized test method. - /// - /// The method for which data is needed. - /// -#if CLR_2_0 || CLR_4_0 - public IEnumerable GetTestCasesFor(MethodInfo method) - { - List data = new List(); -#else - public IEnumerable GetTestCasesFor(MethodInfo method) - { - ArrayList data = new ArrayList(); -#endif - IEnumerable source = GetTestCaseSource(method); - - if (source != null) - { - ParameterInfo[] parameters = method.GetParameters(); - - foreach (object item in source) - { - ParameterSet parms = new ParameterSet(); - ITestCaseData testCaseData = item as ITestCaseData; - - if (testCaseData != null) - parms = new ParameterSet(testCaseData); - else if (item is object[]) - { - object[] array = item as object[]; - parms.Arguments = array.Length == parameters.Length - ? array - : new object[] { item }; - } - //else if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(item.GetType())) - //{ - // parms.Arguments = new object[] { item }; - //} - else if (item is Array) - { - Array array = item as Array; - - if (array.Rank == 1 && array.Length == parameters.Length) - { - parms.Arguments = new object[array.Length]; - for (int i = 0; i < array.Length; i++) - parms.Arguments[i] = (object)array.GetValue(i); - } - else - { - parms.Arguments = new object[] { item }; - } - } - else - { - parms.Arguments = new object[] { item }; - } - - if (this.Category != null) - foreach (string cat in this.Category.Split(new char[] { ',' })) - parms.Properties.Add(PropertyNames.Category, cat); - - data.Add(parms); - } - } - - return data; - } - - private IEnumerable GetTestCaseSource(MethodInfo method) - { - IEnumerable source = null; - - Type sourceType = this.sourceType; - if (sourceType == null) - sourceType = method.ReflectedType; - - if (this.sourceName == null) - { - return Reflect.Construct(sourceType) as IEnumerable; - } - - MemberInfo[] members = sourceType.GetMember(sourceName, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); - if (members.Length == 1) - { - MemberInfo member = members[0]; - object sourceobject = Internal.Reflect.Construct(sourceType); - switch (member.MemberType) - { - case MemberTypes.Field: - FieldInfo field = member as FieldInfo; - source = (IEnumerable)field.GetValue(sourceobject); - break; - case MemberTypes.Property: - PropertyInfo property = member as PropertyInfo; - source = (IEnumerable)property.GetValue(sourceobject, null); - break; - case MemberTypes.Method: - MethodInfo m = member as MethodInfo; - source = (IEnumerable)m.Invoke(sourceobject, null); - break; - } - } - return source; - } - #endregion - - } -} diff --git a/test/NUnitLite/src/framework/Attributes/TestFixtureAttribute.cs b/test/NUnitLite/src/framework/Attributes/TestFixtureAttribute.cs deleted file mode 100644 index 25f6dd7dd..000000000 --- a/test/NUnitLite/src/framework/Attributes/TestFixtureAttribute.cs +++ /dev/null @@ -1,202 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// [TestFixture] - /// public class ExampleClass - /// {} - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)] - public class TestFixtureAttribute : NUnitAttribute, IApplyToTest - { - private string description; - - private object[] originalArgs; - private object[] constructorArgs; - private Type[] typeArgs; - private bool argsInitialized; - - private bool isIgnored; - private string ignoreReason; - private string category; - - /// - /// Default constructor - /// - public TestFixtureAttribute() : this( null ) { } - - /// - /// Construct with a object[] representing a set of arguments. - /// In .NET 2.0, the arguments may later be separated into - /// type arguments and constructor arguments. - /// - /// - public TestFixtureAttribute(params object[] arguments) - { - this.originalArgs = arguments == null - ? new object[0] - : arguments; - this.constructorArgs = this.originalArgs; - this.typeArgs = new Type[0]; - } - - /// - /// Descriptive text for this fixture - /// - public string Description - { - get { return description; } - set { description = value; } - } - - /// - /// The arguments originally provided to the attribute - /// - public object[] Arguments - { - get - { - if (!argsInitialized) - InitializeArgs(); - return constructorArgs; - } - } - - /// - /// Gets or sets a value indicating whether this should be ignored. - /// - /// true if ignore; otherwise, false. - public bool Ignore - { - get { return isIgnored; } - set { isIgnored = value; } - } - - /// - /// Gets or sets the ignore reason. May set Ignored as a side effect. - /// - /// The ignore reason. - public string IgnoreReason - { - get { return ignoreReason; } - set - { - ignoreReason = value; - isIgnored = ignoreReason != null && ignoreReason != string.Empty; - } - } - - /// - /// Get or set the type arguments. If not set - /// explicitly, any leading arguments that are - /// Types are taken as type arguments. - /// - public Type[] TypeArgs - { - get - { - if (!argsInitialized) - InitializeArgs(); - return typeArgs; - } - set - { - typeArgs = value; - argsInitialized = true; - } - } - - /// - /// Gets and sets the category for this fixture. - /// May be a comma-separated list of categories. - /// - public string Category - { - get { return category; } - set { category = value; } - } - - /// - /// Gets a list of categories for this fixture - /// - public IList Categories - { - get { return category == null ? null : category.Split(','); } - } - - /// - /// Helper method to split the original argument list - /// into type arguments and constructor arguments. - /// This action has to be delayed rather than done in - /// the constructor, since TypeArgs may be set by - /// menas of a named parameter. - /// - private void InitializeArgs() - { - int typeArgCount = 0; - - if (this.originalArgs != null) - { - foreach (object o in this.originalArgs) - if (o is Type) typeArgCount++; - else break; - } - - this.typeArgs = new Type[typeArgCount]; - for (int i = 0; i < typeArgCount; i++) - this.typeArgs[i] = (Type)this.originalArgs[i]; - - int constructorArgCount = originalArgs.Length - typeArgCount; - this.constructorArgs = new object[constructorArgCount]; - for (int i = 0; i < constructorArgCount; i++) - this.constructorArgs[i] = this.originalArgs[typeArgCount + i]; - - argsInitialized = true; - } - - #region IApplyToTest Members - - /// - /// Modifies a test by adding a description, if not already set. - /// - /// The test to modify - public void ApplyToTest(Test test) - { - if (!test.Properties.ContainsKey(PropertyNames.Description) && description != null) - test.Properties.Set(PropertyNames.Description, description); - - if (category != null) - foreach (string cat in category.Split(new char[] { ',' }) ) - test.Properties.Add(PropertyNames.Category, cat); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Attributes/TestFixtureTearDownAttribute.cs b/test/NUnitLite/src/framework/Attributes/TestFixtureTearDownAttribute.cs deleted file mode 100644 index 27feb8460..000000000 --- a/test/NUnitLite/src/framework/Attributes/TestFixtureTearDownAttribute.cs +++ /dev/null @@ -1,37 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework -{ - using System; - - /// - /// Attribute used to identify a method that is called after - /// all the tests in a fixture have run. The method is - /// guaranteed to be called, even if an exception is thrown. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] - public class TestFixtureTearDownAttribute : NUnitAttribute - { - } -} diff --git a/test/NUnitLite/src/framework/Attributes/ValueSourceAttribute.cs b/test/NUnitLite/src/framework/Attributes/ValueSourceAttribute.cs deleted file mode 100644 index 24d3d966e..000000000 --- a/test/NUnitLite/src/framework/Attributes/ValueSourceAttribute.cs +++ /dev/null @@ -1,146 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// ValueSourceAttribute indicates the source to be used to - /// provide data for one parameter of a test method. - /// - [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] - public class ValueSourceAttribute : DataAttribute, Api.IParameterDataSource - { - private readonly string sourceName; - private readonly Type sourceType; - - /// - /// Construct with the name of the factory - for use with languages - /// that don't support params arrays. - /// - /// The name of the data source to be used - public ValueSourceAttribute(string sourceName) - { - this.sourceName = sourceName; - } - - /// - /// Construct with a Type and name - for use with languages - /// that don't support params arrays. - /// - /// The Type that will provide data - /// The name of the method, property or field that will provide data - public ValueSourceAttribute(Type sourceType, string sourceName) - { - this.sourceType = sourceType; - this.sourceName = sourceName; - } - - /// - /// The name of a the method, property or fiend to be used as a source - /// - public string SourceName - { - get { return sourceName; } - } - - /// - /// A Type to be used as a source - /// - public Type SourceType - { - get { return sourceType; } - } - - #region IParameterDataSource Members - - /// - /// Gets an enumeration of data items for use as arguments - /// for a test method parameter. - /// - /// The parameter for which data is needed - /// - /// An enumeration containing individual data items - /// - public IEnumerable GetData(ParameterInfo parameter) - { - ObjectList data = new ObjectList(); - IEnumerable source = GetDataSource(parameter); - - if (source != null) - foreach (object item in source) - data.Add(item); - - return source; - } - - #endregion - - #region Helper Methods - - private IEnumerable GetDataSource(ParameterInfo parameter) - { - IEnumerable source = null; - - Type sourceType = this.sourceType; - if (sourceType == null) - sourceType = parameter.Member.ReflectedType; - - // TODO: Test this - if (this.sourceName == null) - { - return Reflect.Construct(sourceType) as IEnumerable; - } - - MemberInfo[] members = sourceType.GetMember(sourceName, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); - if (members.Length == 1) - { - MemberInfo member = members[0]; - object sourceobject = Internal.Reflect.Construct(sourceType); - switch (member.MemberType) - { - case MemberTypes.Field: - FieldInfo field = member as FieldInfo; - source = (IEnumerable)field.GetValue(sourceobject); - break; - case MemberTypes.Property: - PropertyInfo property = member as PropertyInfo; - source = (IEnumerable)property.GetValue(sourceobject, null); - break; - case MemberTypes.Method: - MethodInfo m = member as MethodInfo; - source = (IEnumerable)m.Invoke(sourceobject, null); - break; - } - } - return source; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Compatibility/SerializableAttribute.cs b/test/NUnitLite/src/framework/Compatibility/SerializableAttribute.cs deleted file mode 100644 index 87b53d5ae..000000000 --- a/test/NUnitLite/src/framework/Compatibility/SerializableAttribute.cs +++ /dev/null @@ -1,35 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if NETCF_1_0 || SILVERLIGHT -namespace System -{ - /// - /// Replacement for the SerializableAttribute so we compile - /// under Silverlight. - /// - public class SerializableAttribute : Attribute - { - } -} -#endif diff --git a/test/NUnitLite/src/framework/Constraints/AllItemsConstraint.cs b/test/NUnitLite/src/framework/Constraints/AllItemsConstraint.cs deleted file mode 100644 index c940f3f06..000000000 --- a/test/NUnitLite/src/framework/Constraints/AllItemsConstraint.cs +++ /dev/null @@ -1,75 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// AllItemsConstraint applies another constraint to each - /// item in a collection, succeeding if they all succeed. - /// - public class AllItemsConstraint : PrefixConstraint - { - /// - /// Construct an AllItemsConstraint on top of an existing constraint - /// - /// - public AllItemsConstraint(Constraint itemConstraint) - : base(itemConstraint) - { - this.DisplayName = "all"; - } - - /// - /// Apply the item constraint to each item in the collection, - /// failing if any item fails. - /// - /// - /// - public override bool Matches(object actual) - { - this.actual = actual; - - if (!(actual is IEnumerable)) - throw new ArgumentException("The actual value must be an IEnumerable", "actual"); - - foreach (object item in (IEnumerable)actual) - if (!baseConstraint.Matches(item)) - return false; - - return true; - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("all items"); - baseConstraint.WriteDescriptionTo(writer); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/AndConstraint.cs b/test/NUnitLite/src/framework/Constraints/AndConstraint.cs deleted file mode 100644 index 818e078a3..000000000 --- a/test/NUnitLite/src/framework/Constraints/AndConstraint.cs +++ /dev/null @@ -1,100 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// AndConstraint succeeds only if both members succeed. - /// - public class AndConstraint : BinaryConstraint - { - private enum FailurePoint - { - None, - Left, - Right - }; - - private FailurePoint failurePoint; - - /// - /// Create an AndConstraint from two other constraints - /// - /// The first constraint - /// The second constraint - public AndConstraint(Constraint left, Constraint right) : base(left, right) { } - - /// - /// Apply both member constraints to an actual value, succeeding - /// succeeding only if both of them succeed. - /// - /// The actual value - /// True if the constraints both succeeded - public override bool Matches(object actual) - { - this.actual = actual; - - failurePoint = left.Matches(actual) - ? right.Matches(actual) - ? FailurePoint.None - : FailurePoint.Right - : FailurePoint.Left; - - return failurePoint == FailurePoint.None; - } - - /// - /// Write a description for this contraint to a MessageWriter - /// - /// The MessageWriter to receive the description - public override void WriteDescriptionTo(MessageWriter writer) - { - left.WriteDescriptionTo(writer); - writer.WriteConnector("and"); - right.WriteDescriptionTo(writer); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - switch (failurePoint) - { - case FailurePoint.Left: - left.WriteActualValueTo(writer); - break; - case FailurePoint.Right: - right.WriteActualValueTo(writer); - break; - default: - base.WriteActualValueTo(writer); - break; - } - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/AssignableFromConstraint.cs b/test/NUnitLite/src/framework/Constraints/AssignableFromConstraint.cs deleted file mode 100644 index d674b0252..000000000 --- a/test/NUnitLite/src/framework/Constraints/AssignableFromConstraint.cs +++ /dev/null @@ -1,61 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// AssignableFromConstraint is used to test that an object - /// can be assigned from a given Type. - /// - public class AssignableFromConstraint : TypeConstraint - { - /// - /// Construct an AssignableFromConstraint for the type provided - /// - /// - public AssignableFromConstraint(Type type) : base(type) { } - - /// - /// Test whether an object can be assigned from the specified type - /// - /// The object to be tested - /// True if the object can be assigned a value of the expected Type, otherwise false. - public override bool Matches(object actual) - { - this.actual = actual; - return actual != null && actual.GetType().IsAssignableFrom(expectedType); - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// The MessageWriter to use - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("assignable from"); - writer.WriteExpectedValue(expectedType); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/AssignableToConstraint.cs b/test/NUnitLite/src/framework/Constraints/AssignableToConstraint.cs deleted file mode 100644 index 66b3ffd6f..000000000 --- a/test/NUnitLite/src/framework/Constraints/AssignableToConstraint.cs +++ /dev/null @@ -1,61 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// AssignableToConstraint is used to test that an object - /// can be assigned to a given Type. - /// - public class AssignableToConstraint : TypeConstraint - { - /// - /// Construct an AssignableToConstraint for the type provided - /// - /// - public AssignableToConstraint(Type type) : base(type) { } - - /// - /// Test whether an object can be assigned to the specified type - /// - /// The object to be tested - /// True if the object can be assigned a value of the expected Type, otherwise false. - public override bool Matches(object actual) - { - this.actual = actual; - return actual != null && expectedType.IsAssignableFrom(actual.GetType()); - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// The MessageWriter to use - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("assignable to"); - writer.WriteExpectedValue(expectedType); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/AttributeConstraint.cs b/test/NUnitLite/src/framework/Constraints/AttributeConstraint.cs deleted file mode 100644 index 8773357aa..000000000 --- a/test/NUnitLite/src/framework/Constraints/AttributeConstraint.cs +++ /dev/null @@ -1,106 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// AttributeConstraint tests that a specified attribute is present - /// on a Type or other provider and that the value of the attribute - /// satisfies some other constraint. - /// - public class AttributeConstraint : PrefixConstraint - { - private readonly Type expectedType; - private Attribute attrFound; - - /// - /// Constructs an AttributeConstraint for a specified attriute - /// Type and base constraint. - /// - /// - /// - public AttributeConstraint(Type type, Constraint baseConstraint) - : base(baseConstraint) - { - this.expectedType = type; - - if (!typeof(Attribute).IsAssignableFrom(expectedType)) - throw new ArgumentException(string.Format( - "Type {0} is not an attribute", expectedType), "type"); - } - - /// - /// Determines whether the Type or other provider has the - /// expected attribute and if its value matches the - /// additional constraint specified. - /// - public override bool Matches(object actual) - { - this.actual = actual; - System.Reflection.ICustomAttributeProvider attrProvider = - actual as System.Reflection.ICustomAttributeProvider; - - if (attrProvider == null) - throw new ArgumentException(string.Format("Actual value {0} does not implement ICustomAttributeProvider", actual), "actual"); - - Attribute[] attrs = (Attribute[])attrProvider.GetCustomAttributes(expectedType, true); - if (attrs.Length == 0) - throw new ArgumentException(string.Format("Attribute {0} was not found", expectedType), "actual"); - - attrFound = attrs[0]; - return baseConstraint.Matches(attrFound); - } - - /// - /// Writes a description of the attribute to the specified writer. - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("attribute " + expectedType.FullName); - if (baseConstraint != null) - { - if (baseConstraint is EqualConstraint) - writer.WritePredicate("equal to"); - baseConstraint.WriteDescriptionTo(writer); - } - } - - /// - /// Writes the actual value supplied to the specified writer. - /// - public override void WriteActualValueTo(MessageWriter writer) - { - writer.WriteActualValue(attrFound); - } - - /// - /// Returns a string representation of the constraint. - /// - protected override string GetStringRepresentation() - { - return string.Format("", expectedType, baseConstraint); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/AttributeExistsConstraint.cs b/test/NUnitLite/src/framework/Constraints/AttributeExistsConstraint.cs deleted file mode 100644 index 5e1109f79..000000000 --- a/test/NUnitLite/src/framework/Constraints/AttributeExistsConstraint.cs +++ /dev/null @@ -1,76 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// AttributeExistsConstraint tests for the presence of a - /// specified attribute on a Type. - /// - public class AttributeExistsConstraint : Constraint - { - private Type expectedType; - - /// - /// Constructs an AttributeExistsConstraint for a specific attribute Type - /// - /// - public AttributeExistsConstraint(Type type) - : base(type) - { - this.expectedType = type; - - if (!typeof(Attribute).IsAssignableFrom(expectedType)) - throw new ArgumentException(string.Format( - "Type {0} is not an attribute", expectedType), "type"); - } - - /// - /// Tests whether the object provides the expected attribute. - /// - /// A Type, MethodInfo, or other ICustomAttributeProvider - /// True if the expected attribute is present, otherwise false - public override bool Matches(object actual) - { - this.actual = actual; - System.Reflection.ICustomAttributeProvider attrProvider = - actual as System.Reflection.ICustomAttributeProvider; - - if (attrProvider == null) - throw new ArgumentException(string.Format("Actual value {0} does not implement ICustomAttributeProvider", actual), "actual"); - - return attrProvider.GetCustomAttributes(expectedType, true).Length > 0; - } - - /// - /// Writes the description of the constraint to the specified writer - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("type with attribute"); - writer.WriteExpectedValue(expectedType); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/BasicConstraint.cs b/test/NUnitLite/src/framework/Constraints/BasicConstraint.cs deleted file mode 100644 index 383a790bd..000000000 --- a/test/NUnitLite/src/framework/Constraints/BasicConstraint.cs +++ /dev/null @@ -1,73 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// BasicConstraint is the abstract base for constraints that - /// perform a simple comparison to a constant value. - /// - public abstract class BasicConstraint : Constraint - { - private readonly object expected; - private readonly string description; - - /// - /// Initializes a new instance of the class. - /// - /// The expected. - /// The description. - protected BasicConstraint(object expected, string description) - { - this.expected = expected; - this.description = description; - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (actual == null && expected == null) - return true; - - if (actual == null || expected == null) - return false; - - return expected.Equals(actual); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write(description); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/BinarySerializableConstraint.cs b/test/NUnitLite/src/framework/Constraints/BinarySerializableConstraint.cs deleted file mode 100644 index 916c570f1..000000000 --- a/test/NUnitLite/src/framework/Constraints/BinarySerializableConstraint.cs +++ /dev/null @@ -1,100 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if !NETCF && !SILVERLIGHT -using System; -using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; - -namespace NUnit.Framework.Constraints -{ - /// - /// BinarySerializableConstraint tests whether - /// an object is serializable in binary format. - /// - public class BinarySerializableConstraint : Constraint - { - readonly BinaryFormatter serializer = new BinaryFormatter(); - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (actual == null) - throw new ArgumentException(); - - MemoryStream stream = new MemoryStream(); - - try - { - serializer.Serialize(stream, actual); - - stream.Seek(0, SeekOrigin.Begin); - - object value = serializer.Deserialize(stream); - - return value != null; - } - catch (SerializationException) - { - return false; - } - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write("binary serializable"); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - writer.Write("<{0}>", actual.GetType().Name); - } - - /// - /// Returns the string representation - /// - protected override string GetStringRepresentation() - { - return ""; - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/CollectionContainsConstraint.cs b/test/NUnitLite/src/framework/Constraints/CollectionContainsConstraint.cs deleted file mode 100644 index 0ba8c3249..000000000 --- a/test/NUnitLite/src/framework/Constraints/CollectionContainsConstraint.cs +++ /dev/null @@ -1,71 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// CollectionContainsConstraint is used to test whether a collection - /// contains an expected object as a member. - /// - public class CollectionContainsConstraint : CollectionItemsEqualConstraint - { - private readonly object expected; - - /// - /// Construct a CollectionContainsConstraint - /// - /// - public CollectionContainsConstraint(object expected) - : base(expected) - { - this.expected = expected; - this.DisplayName = "contains"; - } - - /// - /// Test whether the expected item is contained in the collection - /// - /// - /// - protected override bool doMatch(IEnumerable actual) - { - foreach (object obj in actual) - if (ItemsEqual(obj, expected)) - return true; - - return false; - } - - /// - /// Write a descripton of the constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("collection containing"); - writer.WriteExpectedValue(expected); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/CollectionEquivalentConstraint.cs b/test/NUnitLite/src/framework/Constraints/CollectionEquivalentConstraint.cs deleted file mode 100644 index 81a021502..000000000 --- a/test/NUnitLite/src/framework/Constraints/CollectionEquivalentConstraint.cs +++ /dev/null @@ -1,73 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// CollectionEquivalentCOnstraint is used to determine whether two - /// collections are equivalent. - /// - public class CollectionEquivalentConstraint : CollectionItemsEqualConstraint - { - private readonly IEnumerable expected; - - /// - /// Construct a CollectionEquivalentConstraint - /// - /// - public CollectionEquivalentConstraint(IEnumerable expected) - : base(expected) - { - this.expected = expected; - this.DisplayName = "equivalent"; - } - - /// - /// Test whether two collections are equivalent - /// - /// - /// - protected override bool doMatch(IEnumerable actual) - { - // This is just an optimization - if (expected is ICollection && actual is ICollection) - if (((ICollection)actual).Count != ((ICollection)expected).Count) - return false; - - CollectionTally tally = Tally(expected); - return tally.TryRemove(actual) && tally.Count == 0; - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("equivalent to"); - writer.WriteExpectedValue(expected); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/CollectionOrderedConstraint.cs b/test/NUnitLite/src/framework/Constraints/CollectionOrderedConstraint.cs deleted file mode 100644 index f8c62b031..000000000 --- a/test/NUnitLite/src/framework/Constraints/CollectionOrderedConstraint.cs +++ /dev/null @@ -1,185 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using System.Text; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - /// - /// CollectionOrderedConstraint is used to test whether a collection is ordered. - /// - public class CollectionOrderedConstraint : CollectionConstraint - { - private ComparisonAdapter comparer = ComparisonAdapter.Default; - private string comparerName; - private string propertyName; - private bool descending; - - /// - /// Construct a CollectionOrderedConstraint - /// - public CollectionOrderedConstraint() - { - this.DisplayName = "ordered"; - } - - /// - /// If used performs a reverse comparison - /// - public CollectionOrderedConstraint Descending - { - get - { - descending = true; - return this; - } - } - - /// - /// Modifies the constraint to use an IComparer and returns self. - /// - public CollectionOrderedConstraint Using(IComparer comparer) - { - this.comparer = ComparisonAdapter.For(comparer); - this.comparerName = comparer.GetType().FullName; - return this; - } - -#if CLR_2_0 || CLR_4_0 - /// - /// Modifies the constraint to use an IComparer<T> and returns self. - /// - public CollectionOrderedConstraint Using(IComparer comparer) - { - this.comparer = ComparisonAdapter.For(comparer); - this.comparerName = comparer.GetType().FullName; - return this; - } - - /// - /// Modifies the constraint to use a Comparison<T> and returns self. - /// - public CollectionOrderedConstraint Using(Comparison comparer) - { - this.comparer = ComparisonAdapter.For(comparer); - this.comparerName = comparer.GetType().FullName; - return this; - } -#endif - - /// - /// Modifies the constraint to test ordering by the value of - /// a specified property and returns self. - /// - public CollectionOrderedConstraint By(string propertyName) - { - this.propertyName = propertyName; - return this; - } - - /// - /// Test whether the collection is ordered - /// - /// - /// - protected override bool doMatch(IEnumerable actual) - { - object previous = null; - int index = 0; - foreach (object obj in actual) - { - object objToCompare = obj; - if (obj == null) - throw new ArgumentNullException("actual", "Null value at index " + index.ToString()); - - if (this.propertyName != null) - { - PropertyInfo prop = obj.GetType().GetProperty(propertyName); - objToCompare = prop.GetValue(obj, null); - if (objToCompare == null) - throw new ArgumentNullException("actual", "Null property value at index " + index.ToString()); - } - - if (previous != null) - { - //int comparisonResult = comparer.Compare(al[i], al[i + 1]); - int comparisonResult = comparer.Compare(previous, objToCompare); - - if (descending && comparisonResult < 0) - return false; - if (!descending && comparisonResult > 0) - return false; - } - - previous = objToCompare; - index++; - } - - return true; - } - - /// - /// Write a description of the constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - if (propertyName == null) - writer.Write("collection ordered"); - else - { - writer.WritePredicate("collection ordered by"); - writer.WriteExpectedValue(propertyName); - } - - if (descending) - writer.WriteModifier("descending"); - } - - /// - /// Returns the string representation of the constraint. - /// - /// - protected override string GetStringRepresentation() - { - StringBuilder sb = new StringBuilder(""); - - return sb.ToString(); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/CollectionSubsetConstraint.cs b/test/NUnitLite/src/framework/Constraints/CollectionSubsetConstraint.cs deleted file mode 100644 index 2cbb0daeb..000000000 --- a/test/NUnitLite/src/framework/Constraints/CollectionSubsetConstraint.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// CollectionSubsetConstraint is used to determine whether - /// one collection is a subset of another - /// - public class CollectionSubsetConstraint : CollectionItemsEqualConstraint - { - private IEnumerable expected; - - /// - /// Construct a CollectionSubsetConstraint - /// - /// The collection that the actual value is expected to be a subset of - public CollectionSubsetConstraint(IEnumerable expected) : base(expected) - { - this.expected = expected; - this.DisplayName = "subsetof"; - } - - /// - /// Test whether the actual collection is a subset of - /// the expected collection provided. - /// - /// - /// - protected override bool doMatch(IEnumerable actual) - { - return Tally(expected).TryRemove( actual ); - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate( "subset of" ); - writer.WriteExpectedValue(expected); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/ComparisonConstraint.cs b/test/NUnitLite/src/framework/Constraints/ComparisonConstraint.cs deleted file mode 100644 index 8b7d67893..000000000 --- a/test/NUnitLite/src/framework/Constraints/ComparisonConstraint.cs +++ /dev/null @@ -1,83 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - /// - /// Abstract base class for constraints that compare values to - /// determine if one is greater than, equal to or less than - /// the other. This class supplies the Using modifiers. - /// - public abstract class ComparisonConstraint : Constraint - { - /// - /// ComparisonAdapter to be used in making the comparison - /// - protected ComparisonAdapter comparer = ComparisonAdapter.Default; - - /// - /// Initializes a new instance of the class. - /// - public ComparisonConstraint(object arg) : base(arg) { } - - /// - /// Initializes a new instance of the class. - /// - public ComparisonConstraint(object arg1, object arg2) : base(arg1, arg2) { } - - /// - /// Modifies the constraint to use an IComparer and returns self - /// - public ComparisonConstraint Using(IComparer comparer) - { - this.comparer = ComparisonAdapter.For(comparer); - return this; - } - -#if CLR_2_0 || CLR_4_0 - /// - /// Modifies the constraint to use an IComparer<T> and returns self - /// - public ComparisonConstraint Using(IComparer comparer) - { - this.comparer = ComparisonAdapter.For(comparer); - return this; - } - - /// - /// Modifies the constraint to use a Comparison<T> and returns self - /// - public ComparisonConstraint Using(Comparison comparer) - { - this.comparer = ComparisonAdapter.For(comparer); - return this; - } -#endif - } -} diff --git a/test/NUnitLite/src/framework/Constraints/Constraint.cs b/test/NUnitLite/src/framework/Constraints/Constraint.cs deleted file mode 100644 index bbbb498d7..000000000 --- a/test/NUnitLite/src/framework/Constraints/Constraint.cs +++ /dev/null @@ -1,416 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Collections; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints -{ - /// - /// Delegate used to delay evaluation of the actual value - /// to be used in evaluating a constraint - /// -#if CLR_2_0 || CLR_4_0 - public delegate T ActualValueDelegate(); -#else - public delegate object ActualValueDelegate(); -#endif - - /// - /// The Constraint class is the base of all built-in constraints - /// within NUnit. It provides the operator overloads used to combine - /// constraints. - /// - public abstract class Constraint : IResolveConstraint - { - #region UnsetObject Class - /// - /// Class used to detect any derived constraints - /// that fail to set the actual value in their - /// Matches override. - /// - private class UnsetObject - { - public override string ToString() - { - return "UNSET"; - } - } - #endregion - - #region Static and Instance Fields - /// - /// Static UnsetObject used to detect derived constraints - /// failing to set the actual value. - /// - protected static object UNSET = new UnsetObject(); - - /// - /// The actual value being tested against a constraint - /// - protected object actual = UNSET; - - /// - /// The display name of this Constraint for use by ToString() - /// - private string displayName; - - /// - /// Argument fields used by ToString(); - /// - private readonly int argcnt; - private readonly object arg1; - private readonly object arg2; - - /// - /// The builder holding this constraint - /// - private ConstraintBuilder builder; - #endregion - - #region Constructors - /// - /// Construct a constraint with no arguments - /// - protected Constraint() - { - argcnt = 0; - } - - /// - /// Construct a constraint with one argument - /// - protected Constraint(object arg) - { - argcnt = 1; - this.arg1 = arg; - } - - /// - /// Construct a constraint with two arguments - /// - protected Constraint(object arg1, object arg2) - { - argcnt = 2; - this.arg1 = arg1; - this.arg2 = arg2; - } - #endregion - - #region Set Containing ConstraintBuilder - /// - /// Sets the ConstraintBuilder holding this constraint - /// - internal void SetBuilder(ConstraintBuilder builder) - { - this.builder = builder; - } - #endregion - - #region Properties - /// - /// The display name of this Constraint for use by ToString(). - /// The default value is the name of the constraint with - /// trailing "Constraint" removed. Derived classes may set - /// this to another name in their constructors. - /// - protected string DisplayName - { - get - { - if (displayName == null) - { - displayName = this.GetType().Name.ToLower(); - if (displayName.EndsWith("`1") || displayName.EndsWith("`2")) - displayName = displayName.Substring(0, displayName.Length - 2); - if (displayName.EndsWith("constraint")) - displayName = displayName.Substring(0, displayName.Length - 10); - } - - return displayName; - } - - set { displayName = value; } - } - #endregion - - #region Abstract and Virtual Methods - /// - /// Write the failure message to the MessageWriter provided - /// as an argument. The default implementation simply passes - /// the constraint and the actual value to the writer, which - /// then displays the constraint description and the value. - /// - /// Constraints that need to provide additional details, - /// such as where the error occured can override this. - /// - /// The MessageWriter on which to display the message - public virtual void WriteMessageTo(MessageWriter writer) - { - writer.DisplayDifferences(this); - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public abstract bool Matches(object actual); - -#if CLR_2_0 || CLR_4_0 - /// - /// Test whether the constraint is satisfied by an - /// ActualValueDelegate that returns the value to be tested. - /// The default implementation simply evaluates the delegate - /// but derived classes may override it to provide for delayed - /// processing. - /// - /// An - /// True for success, false for failure - public virtual bool Matches(ActualValueDelegate del) - { -#if NET_4_5 - if (AsyncInvocationRegion.IsAsyncOperation(del)) - using (var region = AsyncInvocationRegion.Create(del)) - return Matches(region.WaitForPendingOperationsToComplete(del())); -#endif - return Matches(del()); - } -#else - /// - /// Test whether the constraint is satisfied by an - /// ActualValueDelegate that returns the value to be tested. - /// The default implementation simply evaluates the delegate - /// but derived classes may override it to provide for delayed - /// processing. - /// - /// An - /// True for success, false for failure - public virtual bool Matches(ActualValueDelegate del) - { - return Matches(del()); - } -#endif - - /// - /// Test whether the constraint is satisfied by a given reference. - /// The default implementation simply dereferences the value but - /// derived classes may override it to provide for delayed processing. - /// - /// A reference to the value to be tested - /// True for success, false for failure -#if CLR_2_0 || CLR_4_0 - public virtual bool Matches(ref T actual) -#else - public virtual bool Matches(ref bool actual) -#endif - { - return Matches(actual); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public abstract void WriteDescriptionTo(MessageWriter writer); - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public virtual void WriteActualValueTo(MessageWriter writer) - { - writer.WriteActualValue(actual); - } - #endregion - - #region ToString Override - /// - /// Default override of ToString returns the constraint DisplayName - /// followed by any arguments within angle brackets. - /// - /// - public override string ToString() - { - string rep = GetStringRepresentation(); - - return this.builder == null ? rep : string.Format("", rep); - } - - /// - /// Returns the string representation of this constraint - /// - protected virtual string GetStringRepresentation() - { - switch (argcnt) - { - default: - case 0: - return string.Format("<{0}>", DisplayName); - case 1: - return string.Format("<{0} {1}>", DisplayName, _displayable(arg1)); - case 2: - return string.Format("<{0} {1} {2}>", DisplayName, _displayable(arg1), _displayable(arg2)); - } - } - - private static string _displayable(object o) - { - if (o == null) return "null"; - - string fmt = o is string ? "\"{0}\"" : "{0}"; - return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o); - } - #endregion - - #region Operator Overloads - /// - /// This operator creates a constraint that is satisfied only if both - /// argument constraints are satisfied. - /// - public static Constraint operator &(Constraint left, Constraint right) - { - IResolveConstraint l = (IResolveConstraint)left; - IResolveConstraint r = (IResolveConstraint)right; - return new AndConstraint(l.Resolve(), r.Resolve()); - } - - /// - /// This operator creates a constraint that is satisfied if either - /// of the argument constraints is satisfied. - /// - public static Constraint operator |(Constraint left, Constraint right) - { - IResolveConstraint l = (IResolveConstraint)left; - IResolveConstraint r = (IResolveConstraint)right; - return new OrConstraint(l.Resolve(), r.Resolve()); - } - - /// - /// This operator creates a constraint that is satisfied if the - /// argument constraint is not satisfied. - /// - public static Constraint operator !(Constraint constraint) - { - IResolveConstraint r = constraint as IResolveConstraint; - return new NotConstraint(r == null ? new NullConstraint() : r.Resolve()); - } - #endregion - - #region Binary Operators - /// - /// Returns a ConstraintExpression by appending And - /// to the current constraint. - /// - public ConstraintExpression And - { - get - { - ConstraintBuilder builder = this.builder; - if (builder == null) - { - builder = new ConstraintBuilder(); - builder.Append(this); - } - - builder.Append(new AndOperator()); - - return new ConstraintExpression(builder); - } - } - - /// - /// Returns a ConstraintExpression by appending And - /// to the current constraint. - /// - public ConstraintExpression With - { - get { return this.And; } - } - - /// - /// Returns a ConstraintExpression by appending Or - /// to the current constraint. - /// - public ConstraintExpression Or - { - get - { - ConstraintBuilder builder = this.builder; - if (builder == null) - { - builder = new ConstraintBuilder(); - builder.Append(this); - } - - builder.Append(new OrOperator()); - - return new ConstraintExpression(builder); - } - } - #endregion - - #region After Modifier - -#if !SILVERLIGHT - /// - /// Returns a DelayedConstraint with the specified delay time. - /// - /// The delay in milliseconds. - /// - public DelayedConstraint After(int delayInMilliseconds) - { - return new DelayedConstraint( - builder == null ? this : builder.Resolve(), - delayInMilliseconds); - } - - /// - /// Returns a DelayedConstraint with the specified delay time - /// and polling interval. - /// - /// The delay in milliseconds. - /// The interval at which to test the constraint. - /// - public DelayedConstraint After(int delayInMilliseconds, int pollingInterval) - { - return new DelayedConstraint( - builder == null ? this : builder.Resolve(), - delayInMilliseconds, - pollingInterval); - } -#endif - - #endregion - - #region IResolveConstraint Members - Constraint IResolveConstraint.Resolve() - { - return builder == null ? this : builder.Resolve(); - } - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/ConstraintExpressionBase.cs b/test/NUnitLite/src/framework/Constraints/ConstraintExpressionBase.cs deleted file mode 100644 index bbd892e06..000000000 --- a/test/NUnitLite/src/framework/Constraints/ConstraintExpressionBase.cs +++ /dev/null @@ -1,115 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// ConstraintExpressionBase is the abstract base class for the - /// ConstraintExpression class, which represents a - /// compound constraint in the process of being constructed - /// from a series of syntactic elements. - /// - /// NOTE: ConstraintExpressionBase is separate because the - /// ConstraintExpression class was generated in earlier - /// versions of NUnit. The two classes may be combined - /// in a future version. - /// - public abstract class ConstraintExpressionBase - { - #region Instance Fields - /// - /// The ConstraintBuilder holding the elements recognized so far - /// - protected ConstraintBuilder builder; - #endregion - - #region Constructors - /// - /// Initializes a new instance of the class. - /// - public ConstraintExpressionBase() - { - this.builder = new ConstraintBuilder(); - } - - /// - /// Initializes a new instance of the - /// class passing in a ConstraintBuilder, which may be pre-populated. - /// - /// The builder. - public ConstraintExpressionBase(ConstraintBuilder builder) - { - this.builder = builder; - } - #endregion - - #region ToString() - /// - /// Returns a string representation of the expression as it - /// currently stands. This should only be used for testing, - /// since it has the side-effect of resolving the expression. - /// - /// - public override string ToString() - { - return builder.Resolve().ToString(); - } - #endregion - - #region Append Methods - /// - /// Appends an operator to the expression and returns the - /// resulting expression itself. - /// - public ConstraintExpression Append(ConstraintOperator op) - { - builder.Append(op); - return (ConstraintExpression)this; - } - - /// - /// Appends a self-resolving operator to the expression and - /// returns a new ResolvableConstraintExpression. - /// - public ResolvableConstraintExpression Append(SelfResolvingOperator op) - { - builder.Append(op); - return new ResolvableConstraintExpression(builder); - } - - /// - /// Appends a constraint to the expression and returns that - /// constraint, which is associated with the current state - /// of the expression being built. - /// - public Constraint Append(Constraint constraint) - { - builder.Append(constraint); - return constraint; - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Constraints/ContainsConstraint.cs b/test/NUnitLite/src/framework/Constraints/ContainsConstraint.cs deleted file mode 100644 index da8012a46..000000000 --- a/test/NUnitLite/src/framework/Constraints/ContainsConstraint.cs +++ /dev/null @@ -1,183 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - // TODO Needs tests - /// - /// ContainsConstraint tests a whether a string contains a substring - /// or a collection contains an object. It postpones the decision of - /// which test to use until the type of the actual argument is known. - /// This allows testing whether a string is contained in a collection - /// or as a substring of another string using the same syntax. - /// - public class ContainsConstraint : Constraint - { - readonly object expected; - Constraint realConstraint; - bool ignoreCase; - -#if CLR_2_0 || CLR_4_0 - private List equalityAdapters = new List(); -#else - private ArrayList equalityAdapters = new ArrayList(); -#endif - - private Constraint RealConstraint - { - get - { - if ( realConstraint == null ) - { - if (actual is string) - { - StringConstraint constraint = new SubstringConstraint((string)expected); - if (this.ignoreCase) - constraint = constraint.IgnoreCase; - this.realConstraint = constraint; - } - else - { - CollectionItemsEqualConstraint constraint = new CollectionContainsConstraint(expected); - - foreach (EqualityAdapter adapter in equalityAdapters) - constraint = constraint.Using(adapter); - - this.realConstraint = constraint; - } - } - - return realConstraint; - } - set - { - realConstraint = value; - } - } - - /// - /// Initializes a new instance of the class. - /// - /// The expected. - public ContainsConstraint( object expected ) : base(expected) - { - this.expected = expected; - } - - /// - /// Flag the constraint to ignore case and return self. - /// - public ContainsConstraint IgnoreCase - { - get { this.ignoreCase = true; return this; } - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - return this.RealConstraint.Matches( actual ); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - this.RealConstraint.WriteDescriptionTo(writer); - } - - /// - /// Flag the constraint to use the supplied IComparer object. - /// - /// The IComparer object to use. - /// Self. - public ContainsConstraint Using(IComparer comparer) - { - return AddAdapter(EqualityAdapter.For(comparer)); - } - -#if CLR_2_0 || CLR_4_0 - /// - /// Flag the constraint to use the supplied IComparer object. - /// - /// The IComparer object to use. - /// Self. - public ContainsConstraint Using(IComparer comparer) - { - return AddAdapter(EqualityAdapter.For(comparer)); - } - - /// - /// Flag the constraint to use the supplied Comparison object. - /// - /// The IComparer object to use. - /// Self. - public ContainsConstraint Using(Comparison comparer) - { - return AddAdapter(EqualityAdapter.For(comparer)); - } - - /// - /// Flag the constraint to use the supplied IEqualityComparer object. - /// - /// The IComparer object to use. - /// Self. - public ContainsConstraint Using(IEqualityComparer comparer) - { - return AddAdapter(EqualityAdapter.For(comparer)); - } - - /// - /// Flag the constraint to use the supplied IEqualityComparer object. - /// - /// The IComparer object to use. - /// Self. - public ContainsConstraint Using(IEqualityComparer comparer) - { - return AddAdapter(EqualityAdapter.For(comparer)); - } -#endif - - #region Helper Methods - - private ContainsConstraint AddAdapter(EqualityAdapter adapter) - { - this.equalityAdapters.Add(adapter); - return this; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Constraints/DelayedConstraint.cs b/test/NUnitLite/src/framework/Constraints/DelayedConstraint.cs deleted file mode 100644 index 24d41fe47..000000000 --- a/test/NUnitLite/src/framework/Constraints/DelayedConstraint.cs +++ /dev/null @@ -1,232 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Threading; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints -{ - /// - /// Applies a delay to the match so that a match can be evaluated in the future. - /// - public class DelayedConstraint : PrefixConstraint - { - private readonly int delayInMilliseconds; - private readonly int pollingInterval; - - /// - /// Creates a new DelayedConstraint - /// - ///The inner constraint two decorate - ///The time interval after which the match is performed - ///If the value of is less than 0 - public DelayedConstraint(Constraint baseConstraint, int delayInMilliseconds) - : this(baseConstraint, delayInMilliseconds, 0) { } - - /// - /// Creates a new DelayedConstraint - /// - ///The inner constraint two decorate - ///The time interval after which the match is performed - ///The time interval used for polling - ///If the value of is less than 0 - public DelayedConstraint(Constraint baseConstraint, int delayInMilliseconds, int pollingInterval) - : base(baseConstraint) - { - if (delayInMilliseconds < 0) - throw new ArgumentException("Cannot check a condition in the past", "delayInMilliseconds"); - - this.delayInMilliseconds = delayInMilliseconds; - this.pollingInterval = pollingInterval; - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for if the base constraint fails, false if it succeeds - public override bool Matches(object actual) - { - int remainingDelay = delayInMilliseconds; - - while (pollingInterval > 0 && pollingInterval < remainingDelay) - { - remainingDelay -= pollingInterval; - Thread.Sleep(pollingInterval); - this.actual = actual; - if (baseConstraint.Matches(actual)) - return true; - } - - if (remainingDelay > 0) - Thread.Sleep(remainingDelay); - this.actual = actual; - return baseConstraint.Matches(actual); - } - - /// - /// Test whether the constraint is satisfied by a delegate - /// - /// The delegate whose value is to be tested - /// True for if the base constraint fails, false if it succeeds -#if CLR_2_0 || CLR_4_0 - public override bool Matches(ActualValueDelegate del) -#else - public override bool Matches(ActualValueDelegate del) -#endif - { - int remainingDelay = delayInMilliseconds; - - while (pollingInterval > 0 && pollingInterval < remainingDelay) - { - remainingDelay -= pollingInterval; - Thread.Sleep(pollingInterval); - this.actual = InvokeDelegate(del); - - try - { - if (baseConstraint.Matches(actual)) - return true; - } - catch - { - // Ignore any exceptions when polling - } - } - - if (remainingDelay > 0) - Thread.Sleep(remainingDelay); - this.actual = InvokeDelegate(del); - return baseConstraint.Matches(actual); - } - -#if CLR_2_0 || CLR_4_0 - private static object InvokeDelegate(ActualValueDelegate del) - { -#if NET_4_5 - if (AsyncInvocationRegion.IsAsyncOperation(del)) - using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(del)) - return region.WaitForPendingOperationsToComplete(del()); -#endif - - return del(); - } -#else - private static object InvokeDelegate(ActualValueDelegate del) - { - return del(); - } -#endif - -#if CLR_2_0 || CLR_4_0 - /// - /// Test whether the constraint is satisfied by a given reference. - /// Overridden to wait for the specified delay period before - /// calling the base constraint with the dereferenced value. - /// - /// A reference to the value to be tested - /// True for success, false for failure - public override bool Matches(ref T actual) - { - int remainingDelay = delayInMilliseconds; - - while (pollingInterval > 0 && pollingInterval < remainingDelay) - { - remainingDelay -= pollingInterval; - Thread.Sleep(pollingInterval); - this.actual = actual; - - try - { - if (baseConstraint.Matches(actual)) - return true; - } - catch (Exception) - { - // Ignore any exceptions when polling - } - } - - if (remainingDelay > 0) - Thread.Sleep(remainingDelay); - this.actual = actual; - return baseConstraint.Matches(actual); - } -#else - /// - /// Test whether the constraint is satisfied by a given boolean reference. - /// Overridden to wait for the specified delay period before - /// calling the base constraint with the dereferenced value. - /// - /// A reference to the value to be tested - /// True for success, false for failure - public override bool Matches(ref bool actual) - { - int remainingDelay = delayInMilliseconds; - - while (pollingInterval > 0 && pollingInterval < remainingDelay) - { - remainingDelay -= pollingInterval; - Thread.Sleep(pollingInterval); - this.actual = actual; - - if (baseConstraint.Matches(actual)) - return true; - } - - if (remainingDelay > 0) - Thread.Sleep(remainingDelay); - this.actual = actual; - return baseConstraint.Matches(actual); - } -#endif - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - baseConstraint.WriteDescriptionTo(writer); - writer.Write(string.Format(" after {0} millisecond delay", delayInMilliseconds)); - } - - /// - /// Write the actual value for a failing constraint test to a MessageWriter. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - baseConstraint.WriteActualValueTo(writer); - } - - /// - /// Returns the string representation of the constraint. - /// - protected override string GetStringRepresentation() - { - return string.Format("", delayInMilliseconds, baseConstraint); - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/EmptyConstraint.cs b/test/NUnitLite/src/framework/Constraints/EmptyConstraint.cs deleted file mode 100644 index 28779d2ff..000000000 --- a/test/NUnitLite/src/framework/Constraints/EmptyConstraint.cs +++ /dev/null @@ -1,72 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// EmptyConstraint tests a whether a string or collection is empty, - /// postponing the decision about which test is applied until the - /// type of the actual argument is known. - /// - public class EmptyConstraint : Constraint - { - private Constraint RealConstraint - { - get - { - if (actual is string) - return new EmptyStringConstraint(); - else if (actual is System.IO.DirectoryInfo) - return new EmptyDirectoryConstraint(); - else - return new EmptyCollectionConstraint(); - } - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (actual == null) - throw new ArgumentException("The actual value must be a non-null string, IEnumerable or DirectoryInfo", "actual"); - - return this.RealConstraint.Matches( actual ); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - this.RealConstraint.WriteDescriptionTo( writer ); - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/EmptyDirectoryConstraint.cs b/test/NUnitLite/src/framework/Constraints/EmptyDirectoryConstraint.cs deleted file mode 100644 index 092aa617a..000000000 --- a/test/NUnitLite/src/framework/Constraints/EmptyDirectoryConstraint.cs +++ /dev/null @@ -1,91 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; - -namespace NUnit.Framework.Constraints -{ - /// - /// EmptyDirectoryConstraint is used to test that a directory is empty - /// - public class EmptyDirectoryConstraint : Constraint - { - private int files = 0; - private int subdirs = 0; - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - DirectoryInfo dirInfo = actual as DirectoryInfo; - if (dirInfo == null) - throw new ArgumentException("The actual value must be a DirectoryInfo", "actual"); - -#if SL_4_0 || SL_5_0 - foreach (FileInfo file in dirInfo.EnumerateFiles()) - files++; - foreach (DirectoryInfo dir in dirInfo.EnumerateDirectories()) - subdirs++; -#else - files = dirInfo.GetFiles().Length; - subdirs = dirInfo.GetDirectories().Length; -#endif - - return files == 0 && subdirs == 0; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write( "An empty directory" ); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - DirectoryInfo dir = actual as DirectoryInfo; - if (dir == null) - base.WriteActualValueTo(writer); - else - { - writer.WriteActualValue(dir); - writer.Write(" with {0} files and {1} directories", files, subdirs); - } - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/EqualConstraint.cs b/test/NUnitLite/src/framework/Constraints/EqualConstraint.cs deleted file mode 100644 index e791c3ebc..000000000 --- a/test/NUnitLite/src/framework/Constraints/EqualConstraint.cs +++ /dev/null @@ -1,565 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - /// - /// EqualConstraint is able to compare an actual value with the - /// expected value provided in its constructor. Two objects are - /// considered equal if both are null, or if both have the same - /// value. NUnit has special semantics for some object types. - /// - public class EqualConstraint : Constraint - { - #region Static and Instance Fields - - private readonly object expected; - - private Tolerance tolerance = Tolerance.Empty; - - /// - /// If true, strings in error messages will be clipped - /// - private bool clipStrings = true; - - /// - /// NUnitEqualityComparer used to test equality. - /// - private NUnitEqualityComparer comparer = new NUnitEqualityComparer(); - - #region Message Strings - private static readonly string StringsDiffer_1 = - "String lengths are both {0}. Strings differ at index {1}."; - private static readonly string StringsDiffer_2 = - "Expected string length {0} but was {1}. Strings differ at index {2}."; - private static readonly string StreamsDiffer_1 = - "Stream lengths are both {0}. Streams differ at offset {1}."; - private static readonly string StreamsDiffer_2 = - "Expected Stream length {0} but was {1}.";// Streams differ at offset {2}."; - private static readonly string CollectionType_1 = - "Expected and actual are both {0}"; - private static readonly string CollectionType_2 = - "Expected is {0}, actual is {1}"; - private static readonly string ValuesDiffer_1 = - "Values differ at index {0}"; - private static readonly string ValuesDiffer_2 = - "Values differ at expected index {0}, actual index {1}"; - #endregion - - #endregion - - #region Constructor - /// - /// Initializes a new instance of the class. - /// - /// The expected value. - public EqualConstraint(object expected) : base(expected) - { - this.expected = expected; - } - #endregion - - #region Constraint Modifiers - /// - /// Flag the constraint to ignore case and return self. - /// - public EqualConstraint IgnoreCase - { - get - { - comparer.IgnoreCase = true; - return this; - } - } - - /// - /// Flag the constraint to suppress string clipping - /// and return self. - /// - public EqualConstraint NoClip - { - get - { - clipStrings = false; - return this; - } - } - - /// - /// Flag the constraint to compare arrays as collections - /// and return self. - /// - public EqualConstraint AsCollection - { - get - { - comparer.CompareAsCollection = true; - return this; - } - } - - /// - /// Flag the constraint to use a tolerance when determining equality. - /// - /// Tolerance value to be used - /// Self. - public EqualConstraint Within(object amount) - { - if (!tolerance.IsEmpty) - throw new InvalidOperationException("Within modifier may appear only once in a constraint expression"); - - tolerance = new Tolerance(amount); - return this; - } - - /// - /// Switches the .Within() modifier to interpret its tolerance as - /// a distance in representable values (see remarks). - /// - /// Self. - /// - /// Ulp stands for "unit in the last place" and describes the minimum - /// amount a given value can change. For any integers, an ulp is 1 whole - /// digit. For floating point values, the accuracy of which is better - /// for smaller numbers and worse for larger numbers, an ulp depends - /// on the size of the number. Using ulps for comparison of floating - /// point results instead of fixed tolerances is safer because it will - /// automatically compensate for the added inaccuracy of larger numbers. - /// - public EqualConstraint Ulps - { - get - { - tolerance = tolerance.Ulps; - return this; - } - } - - /// - /// Switches the .Within() modifier to interpret its tolerance as - /// a percentage that the actual values is allowed to deviate from - /// the expected value. - /// - /// Self - public EqualConstraint Percent - { - get - { - tolerance = tolerance.Percent; - return this; - } - } - - /// - /// Causes the tolerance to be interpreted as a TimeSpan in days. - /// - /// Self - public EqualConstraint Days - { - get - { - tolerance = tolerance.Days; - return this; - } - } - - /// - /// Causes the tolerance to be interpreted as a TimeSpan in hours. - /// - /// Self - public EqualConstraint Hours - { - get - { - tolerance = tolerance.Hours; - return this; - } - } - - /// - /// Causes the tolerance to be interpreted as a TimeSpan in minutes. - /// - /// Self - public EqualConstraint Minutes - { - get - { - tolerance = tolerance.Minutes; - return this; - } - } - - /// - /// Causes the tolerance to be interpreted as a TimeSpan in seconds. - /// - /// Self - public EqualConstraint Seconds - { - get - { - tolerance = tolerance.Seconds; - return this; - } - } - - /// - /// Causes the tolerance to be interpreted as a TimeSpan in milliseconds. - /// - /// Self - public EqualConstraint Milliseconds - { - get - { - tolerance = tolerance.Milliseconds; - return this; - } - } - - /// - /// Causes the tolerance to be interpreted as a TimeSpan in clock ticks. - /// - /// Self - public EqualConstraint Ticks - { - get - { - tolerance = tolerance.Ticks; - return this; - } - } - - /// - /// Flag the constraint to use the supplied IComparer object. - /// - /// The IComparer object to use. - /// Self. - public EqualConstraint Using(IComparer comparer) - { - this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); - return this; - } - -#if CLR_2_0 || CLR_4_0 - /// - /// Flag the constraint to use the supplied IComparer object. - /// - /// The IComparer object to use. - /// Self. - public EqualConstraint Using(IComparer comparer) - { - this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); - return this; - } - - /// - /// Flag the constraint to use the supplied Comparison object. - /// - /// The IComparer object to use. - /// Self. - public EqualConstraint Using(Comparison comparer) - { - this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); - return this; - } - - /// - /// Flag the constraint to use the supplied IEqualityComparer object. - /// - /// The IComparer object to use. - /// Self. - public EqualConstraint Using(IEqualityComparer comparer) - { - this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); - return this; - } - - /// - /// Flag the constraint to use the supplied IEqualityComparer object. - /// - /// The IComparer object to use. - /// Self. - public EqualConstraint Using(IEqualityComparer comparer) - { - this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); - return this; - } -#endif - - #endregion - - #region Public Methods - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - return comparer.AreEqual(expected, actual, ref tolerance); - } - - /// - /// Write a failure message. Overridden to provide custom - /// failure messages for EqualConstraint. - /// - /// The MessageWriter to write to - public override void WriteMessageTo(MessageWriter writer) - { - DisplayDifferences(writer, expected, actual, 0); - } - - - /// - /// Write description of this constraint - /// - /// The MessageWriter to write to - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WriteExpectedValue(expected); - - if (tolerance != null && !tolerance.IsEmpty) - { - writer.WriteConnector("+/-"); - writer.WriteExpectedValue(tolerance.Value); - if (tolerance.Mode != ToleranceMode.Linear) - writer.Write(" {0}", tolerance.Mode); - } - - if (comparer.IgnoreCase) - writer.WriteModifier("ignoring case"); - } - - private void DisplayDifferences(MessageWriter writer, object expected, object actual, int depth) - { - if (expected is string && actual is string) - DisplayStringDifferences(writer, (string)expected, (string)actual); - else if (expected is ICollection && actual is ICollection) - DisplayCollectionDifferences(writer, (ICollection)expected, (ICollection)actual, depth); - else if (expected is IEnumerable && actual is IEnumerable) - DisplayEnumerableDifferences(writer, (IEnumerable)expected, (IEnumerable)actual, depth); - else if (expected is Stream && actual is Stream) - DisplayStreamDifferences(writer, (Stream)expected, (Stream)actual, depth); - else if (tolerance != null) - writer.DisplayDifferences(expected, actual, tolerance); - else - writer.DisplayDifferences(expected, actual); - } - #endregion - - #region DisplayStringDifferences - private void DisplayStringDifferences(MessageWriter writer, string expected, string actual) - { - int mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, comparer.IgnoreCase); - - if (expected.Length == actual.Length) - writer.WriteMessageLine(StringsDiffer_1, expected.Length, mismatch); - else - writer.WriteMessageLine(StringsDiffer_2, expected.Length, actual.Length, mismatch); - - writer.DisplayStringDifferences(expected, actual, mismatch, comparer.IgnoreCase, clipStrings); - } - #endregion - - #region DisplayStreamDifferences - private void DisplayStreamDifferences(MessageWriter writer, Stream expected, Stream actual, int depth) - { - if (expected.Length == actual.Length) - { - FailurePoint fp = (FailurePoint)comparer.FailurePoints[depth]; - long offset = fp.Position; - writer.WriteMessageLine(StreamsDiffer_1, expected.Length, offset); - } - else - writer.WriteMessageLine(StreamsDiffer_2, expected.Length, actual.Length); - } - #endregion - - #region DisplayCollectionDifferences - /// - /// Display the failure information for two collections that did not match. - /// - /// The MessageWriter on which to display - /// The expected collection. - /// The actual collection - /// The depth of this failure in a set of nested collections - private void DisplayCollectionDifferences(MessageWriter writer, ICollection expected, ICollection actual, int depth) - { - DisplayTypesAndSizes(writer, expected, actual, depth); - - if (comparer.FailurePoints.Count > depth) - { - FailurePoint failurePoint = (FailurePoint)comparer.FailurePoints[depth]; - - DisplayFailurePoint(writer, expected, actual, failurePoint, depth); - - if (failurePoint.ExpectedHasData && failurePoint.ActualHasData) - DisplayDifferences( - writer, - failurePoint.ExpectedValue, - failurePoint.ActualValue, - ++depth); - else if (failurePoint.ActualHasData) - { - writer.Write(" Extra: "); - writer.WriteCollectionElements(actual, failurePoint.Position, 3); - } - else - { - writer.Write(" Missing: "); - writer.WriteCollectionElements(expected, failurePoint.Position, 3); - } - } - } - - /// - /// Displays a single line showing the types and sizes of the expected - /// and actual enumerations, collections or arrays. If both are identical, - /// the value is only shown once. - /// - /// The MessageWriter on which to display - /// The expected collection or array - /// The actual collection or array - /// The indentation level for the message line - private void DisplayTypesAndSizes(MessageWriter writer, IEnumerable expected, IEnumerable actual, int indent) - { - string sExpected = MsgUtils.GetTypeRepresentation(expected); - if (expected is ICollection && !(expected is Array)) - sExpected += string.Format(" with {0} elements", ((ICollection)expected).Count); - - string sActual = MsgUtils.GetTypeRepresentation(actual); - if (actual is ICollection && !(actual is Array)) - sActual += string.Format(" with {0} elements", ((ICollection)actual).Count); - - if (sExpected == sActual) - writer.WriteMessageLine(indent, CollectionType_1, sExpected); - else - writer.WriteMessageLine(indent, CollectionType_2, sExpected, sActual); - } - - /// - /// Displays a single line showing the point in the expected and actual - /// arrays at which the comparison failed. If the arrays have different - /// structures or dimensions, both values are shown. - /// - /// The MessageWriter on which to display - /// The expected array - /// The actual array - /// Index of the failure point in the underlying collections - /// The indentation level for the message line - private void DisplayFailurePoint(MessageWriter writer, IEnumerable expected, IEnumerable actual, FailurePoint failurePoint, int indent) - { - Array expectedArray = expected as Array; - Array actualArray = actual as Array; - - int expectedRank = expectedArray != null ? expectedArray.Rank : 1; - int actualRank = actualArray != null ? actualArray.Rank : 1; - - bool useOneIndex = expectedRank == actualRank; - - if (expectedArray != null && actualArray != null) - for (int r = 1; r < expectedRank && useOneIndex; r++) - if (expectedArray.GetLength(r) != actualArray.GetLength(r)) - useOneIndex = false; - - int[] expectedIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(expected, failurePoint.Position); - if (useOneIndex) - { - writer.WriteMessageLine(indent, ValuesDiffer_1, MsgUtils.GetArrayIndicesAsString(expectedIndices)); - } - else - { - int[] actualIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(actual, failurePoint.Position); - writer.WriteMessageLine(indent, ValuesDiffer_2, - MsgUtils.GetArrayIndicesAsString(expectedIndices), MsgUtils.GetArrayIndicesAsString(actualIndices)); - } - } - - private static object GetValueFromCollection(ICollection collection, int index) - { - Array array = collection as Array; - - if (array != null && array.Rank > 1) - return array.GetValue(MsgUtils.GetArrayIndicesFromCollectionIndex(array, index)); - - if (collection is IList) - return ((IList)collection)[index]; - - foreach (object obj in collection) - if (--index < 0) - return obj; - - return null; - } - #endregion - - #region DisplayEnumerableDifferences - - /// - /// Display the failure information for two IEnumerables that did not match. - /// - /// The MessageWriter on which to display - /// The expected enumeration. - /// The actual enumeration - /// The depth of this failure in a set of nested collections - private void DisplayEnumerableDifferences(MessageWriter writer, IEnumerable expected, IEnumerable actual, int depth) - { - DisplayTypesAndSizes(writer, expected, actual, depth); - - if (comparer.FailurePoints.Count > depth) - { - FailurePoint failurePoint = (FailurePoint)comparer.FailurePoints[depth]; - - DisplayFailurePoint(writer, expected, actual, failurePoint, depth); - - if (failurePoint.ExpectedHasData && failurePoint.ActualHasData) - DisplayDifferences( - writer, - failurePoint.ExpectedValue, - failurePoint.ActualValue, - ++depth); - //else if (failurePoint.ActualHasData) - //{ - // writer.Write(" Extra: "); - // writer.WriteCollectionElements(actual, failurePoint.Position, 3); - //} - //else - //{ - // writer.Write(" Missing: "); - // writer.WriteCollectionElements(expected, failurePoint.Position, 3); - //} - } - } - - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/EqualityAdapter.cs b/test/NUnitLite/src/framework/Constraints/EqualityAdapter.cs deleted file mode 100644 index 04d103c7f..000000000 --- a/test/NUnitLite/src/framework/Constraints/EqualityAdapter.cs +++ /dev/null @@ -1,241 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - /// - /// EqualityAdapter class handles all equality comparisons - /// that use an IEqualityComparer, IEqualityComparer<T> - /// or a ComparisonAdapter. - /// - public abstract class EqualityAdapter - { - /// - /// Compares two objects, returning true if they are equal - /// - public abstract bool AreEqual(object x, object y); - - /// - /// Returns true if the two objects can be compared by this adapter. - /// The base adapter cannot handle IEnumerables except for strings. - /// - public virtual bool CanCompare(object x, object y) - { - if (x is string && y is string) - return true; - - if (x is IEnumerable || y is IEnumerable) - return false; - - return true; - } - - #region Nested IComparer Adapter - - /// - /// Returns an EqualityAdapter that wraps an IComparer. - /// - public static EqualityAdapter For(IComparer comparer) - { - return new ComparerAdapter(comparer); - } - - /// - /// EqualityAdapter that wraps an IComparer. - /// - class ComparerAdapter : EqualityAdapter - { - private IComparer comparer; - - public ComparerAdapter(IComparer comparer) - { - this.comparer = comparer; - } - - public override bool AreEqual(object x, object y) - { - return comparer.Compare(x, y) == 0; - } - } - - #endregion - -#if CLR_2_0 || CLR_4_0 - #region Nested IEqualityComparer Adapter - - /// - /// Returns an EqualityAdapter that wraps an IEqualityComparer. - /// - public static EqualityAdapter For(IEqualityComparer comparer) - { - return new EqualityComparerAdapter(comparer); - } - - class EqualityComparerAdapter : EqualityAdapter - { - private IEqualityComparer comparer; - - public EqualityComparerAdapter(IEqualityComparer comparer) - { - this.comparer = comparer; - } - - public override bool AreEqual(object x, object y) - { - return comparer.Equals(x, y); - } - } - - #endregion - - #region Nested GenericEqualityAdapter - - abstract class GenericEqualityAdapter : EqualityAdapter - { - /// - /// Returns true if the two objects can be compared by this adapter. - /// Generic adapter requires objects of the specified type. - /// - public override bool CanCompare(object x, object y) - { - return typeof(T).IsAssignableFrom(x.GetType()) - && typeof(T).IsAssignableFrom(y.GetType()); - } - - protected void ThrowIfNotCompatible(object x, object y) - { - if (!typeof(T).IsAssignableFrom(x.GetType())) - throw new ArgumentException("Cannot compare " + x.ToString()); - - if (!typeof(T).IsAssignableFrom(y.GetType())) - throw new ArgumentException("Cannot compare " + y.ToString()); - } - } - - #endregion - - #region Nested IEqualityComparer Adapter - - /// - /// Returns an EqualityAdapter that wraps an IEqualityComparer<T>. - /// - public static EqualityAdapter For(IEqualityComparer comparer) - { - return new EqualityComparerAdapter(comparer); - } - - class EqualityComparerAdapter : GenericEqualityAdapter - { - private IEqualityComparer comparer; - - public EqualityComparerAdapter(IEqualityComparer comparer) - { - this.comparer = comparer; - } - - public override bool AreEqual(object x, object y) - { - ThrowIfNotCompatible(x, y); - return comparer.Equals((T)x, (T)y); - } - } - - #endregion - - #region Nested IComparer Adapter - - /// - /// Returns an EqualityAdapter that wraps an IComparer<T>. - /// - public static EqualityAdapter For(IComparer comparer) - { - return new ComparerAdapter(comparer); - } - - /// - /// EqualityAdapter that wraps an IComparer. - /// - class ComparerAdapter : GenericEqualityAdapter - { - private IComparer comparer; - - public ComparerAdapter(IComparer comparer) - { - this.comparer = comparer; - } - - public override bool AreEqual(object x, object y) - { - ThrowIfNotCompatible(x, y); - return comparer.Compare((T)x, (T)y) == 0; - } - } - - #endregion - - #region Nested Comparison Adapter - - /// - /// Returns an EqualityAdapter that wraps a Comparison<T>. - /// - public static EqualityAdapter For(Comparison comparer) - { - return new ComparisonAdapter(comparer); - } - - class ComparisonAdapter : GenericEqualityAdapter - { - private Comparison comparer; - - public ComparisonAdapter(Comparison comparer) - { - this.comparer = comparer; - } - - public override bool AreEqual(object x, object y) - { - ThrowIfNotCompatible(x, y); - return comparer.Invoke((T)x, (T)y) == 0; - } - } - - #endregion -#endif - } - - /// - /// EqualityAdapterList represents a list of EqualityAdapters - /// in a common class across platforms. - /// -#if CLR_2_0 || CLR_4_0 - class EqualityAdapterList : System.Collections.Generic.List { } -#else - class EqualityAdapterList : ArrayList { } -#endif -} diff --git a/test/NUnitLite/src/framework/Constraints/ExactCountConstraint.cs b/test/NUnitLite/src/framework/Constraints/ExactCountConstraint.cs deleted file mode 100644 index 2c85e7ccf..000000000 --- a/test/NUnitLite/src/framework/Constraints/ExactCountConstraint.cs +++ /dev/null @@ -1,94 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// ExactCountConstraint applies another constraint to each - /// item in a collection, succeeding only if a specified - /// number of items succeed. - /// - public class ExactCountConstraint : PrefixConstraint - { - private int expectedCount; - - /// - /// Construct an ExactCountConstraint on top of an existing constraint - /// - /// - /// - public ExactCountConstraint(int expectedCount, Constraint itemConstraint) - : base(itemConstraint) - { - this.DisplayName = "one"; - this.expectedCount = expectedCount; - } - - /// - /// Apply the item constraint to each item in the collection, - /// succeeding only if the expected number of items pass. - /// - /// - /// - public override bool Matches(object actual) - { - this.actual = actual; - - if (!(actual is IEnumerable)) - throw new ArgumentException("The actual value must be an IEnumerable", "actual"); - - int count = 0; - foreach (object item in (IEnumerable)actual) - if (baseConstraint.Matches(item)) - count++; - - return count == expectedCount; - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - switch(expectedCount) - { - case 0: - writer.WritePredicate("no item"); - break; - case 1: - writer.WritePredicate("exactly one item"); - break; - default: - writer.WritePredicate("exactly " + expectedCount.ToString() + " items"); - break; - } - - baseConstraint.WriteDescriptionTo(writer); - } - } -} - diff --git a/test/NUnitLite/src/framework/Constraints/ExactTypeConstraint.cs b/test/NUnitLite/src/framework/Constraints/ExactTypeConstraint.cs deleted file mode 100644 index fda8e726a..000000000 --- a/test/NUnitLite/src/framework/Constraints/ExactTypeConstraint.cs +++ /dev/null @@ -1,64 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// ExactTypeConstraint is used to test that an object - /// is of the exact type provided in the constructor - /// - public class ExactTypeConstraint : TypeConstraint - { - /// - /// Construct an ExactTypeConstraint for a given Type - /// - /// The expected Type. - public ExactTypeConstraint(Type type) - : base(type) - { - this.DisplayName = "typeof"; - } - - /// - /// Test that an object is of the exact type specified - /// - /// The actual value. - /// True if the tested object is of the exact type provided, otherwise false. - public override bool Matches(object actual) - { - this.actual = actual; - return actual != null && actual.GetType() == this.expectedType; - } - - /// - /// Write the description of this constraint to a MessageWriter - /// - /// The MessageWriter to use - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WriteExpectedValue(expectedType); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/ExceptionTypeConstraint.cs b/test/NUnitLite/src/framework/Constraints/ExceptionTypeConstraint.cs deleted file mode 100644 index 2d62db5a1..000000000 --- a/test/NUnitLite/src/framework/Constraints/ExceptionTypeConstraint.cs +++ /dev/null @@ -1,59 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// ExceptionTypeConstraint is a special version of ExactTypeConstraint - /// used to provided detailed info about the exception thrown in - /// an error message. - /// - public class ExceptionTypeConstraint : ExactTypeConstraint - { - /// - /// Constructs an ExceptionTypeConstraint - /// - public ExceptionTypeConstraint(Type type) : base(type) { } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. Overriden to write additional information - /// in the case of an Exception. - /// - /// The MessageWriter to use - public override void WriteActualValueTo(MessageWriter writer) - { - Exception ex = actual as Exception; - base.WriteActualValueTo(writer); - - if (ex != null) - { - writer.WriteLine(" ({0})", ex.Message); - writer.Write(ex.StackTrace); - } - } - } -} - diff --git a/test/NUnitLite/src/framework/Constraints/FailurePoint.cs b/test/NUnitLite/src/framework/Constraints/FailurePoint.cs deleted file mode 100644 index f726ce919..000000000 --- a/test/NUnitLite/src/framework/Constraints/FailurePoint.cs +++ /dev/null @@ -1,68 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// FailurePoint class represents one point of failure - /// in an equality test. - /// - public class FailurePoint - { - /// - /// The location of the failure - /// - public int Position; - - /// - /// The expected value - /// - public object ExpectedValue; - - /// - /// The actual value - /// - public object ActualValue; - - /// - /// Indicates whether the expected value is valid - /// - public bool ExpectedHasData; - - /// - /// Indicates whether the actual value is valid - /// - public bool ActualHasData; - } - - /// - /// FailurePointList represents a set of FailurePoints - /// in a cross-platform way. - /// -#if CLR_2_0 || CLR_4_0 - class FailurePointList : System.Collections.Generic.List { } -#else - class FailurePointList : System.Collections.ArrayList { } -#endif - -} diff --git a/test/NUnitLite/src/framework/Constraints/FalseConstraint.cs b/test/NUnitLite/src/framework/Constraints/FalseConstraint.cs deleted file mode 100644 index 64b82dea2..000000000 --- a/test/NUnitLite/src/framework/Constraints/FalseConstraint.cs +++ /dev/null @@ -1,36 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// FalseConstraint tests that the actual value is false - /// - public class FalseConstraint : BasicConstraint - { - /// - /// Initializes a new instance of the class. - /// - public FalseConstraint() : base(false, "False") { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/GreaterThanConstraint.cs b/test/NUnitLite/src/framework/Constraints/GreaterThanConstraint.cs deleted file mode 100644 index bcf4aeff1..000000000 --- a/test/NUnitLite/src/framework/Constraints/GreaterThanConstraint.cs +++ /dev/null @@ -1,73 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// Tests whether a value is greater than the value supplied to its constructor - /// - public class GreaterThanConstraint : ComparisonConstraint - { - /// - /// The value against which a comparison is to be made - /// - private object expected; - - /// - /// Initializes a new instance of the class. - /// - /// The expected value. - public GreaterThanConstraint(object expected) - : base(expected) - { - this.expected = expected; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("greater than"); - writer.WriteExpectedValue(expected); - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (expected == null || actual == null) - throw new ArgumentException("Cannot compare using a null reference"); - - return comparer.Compare(actual, expected) > 0; - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/GreaterThanOrEqualConstraint.cs b/test/NUnitLite/src/framework/Constraints/GreaterThanOrEqualConstraint.cs deleted file mode 100644 index a885858b4..000000000 --- a/test/NUnitLite/src/framework/Constraints/GreaterThanOrEqualConstraint.cs +++ /dev/null @@ -1,73 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// Tests whether a value is greater than or equal to the value supplied to its constructor - /// - public class GreaterThanOrEqualConstraint : ComparisonConstraint - { - /// - /// The value against which a comparison is to be made - /// - private object expected; - - /// - /// Initializes a new instance of the class. - /// - /// The expected value. - public GreaterThanOrEqualConstraint(object expected) - : base(expected) - { - this.expected = expected; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("greater than or equal to"); - writer.WriteExpectedValue(expected); - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (expected == null || actual == null) - throw new ArgumentException("Cannot compare using a null reference"); - - return comparer.Compare(actual, expected) >= 0; - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/InstanceOfTypeConstraint.cs b/test/NUnitLite/src/framework/Constraints/InstanceOfTypeConstraint.cs deleted file mode 100644 index 435e08193..000000000 --- a/test/NUnitLite/src/framework/Constraints/InstanceOfTypeConstraint.cs +++ /dev/null @@ -1,65 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// InstanceOfTypeConstraint is used to test that an object - /// is of the same type provided or derived from it. - /// - public class InstanceOfTypeConstraint : TypeConstraint - { - /// - /// Construct an InstanceOfTypeConstraint for the type provided - /// - /// The expected Type - public InstanceOfTypeConstraint(Type type) - : base(type) - { - this.DisplayName = "instanceof"; - } - - /// - /// Test whether an object is of the specified type or a derived type - /// - /// The object to be tested - /// True if the object is of the provided type or derives from it, otherwise false. - public override bool Matches(object actual) - { - this.actual = actual; - return actual != null && expectedType.IsInstanceOfType(actual); - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// The MessageWriter to use - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("instance of"); - writer.WriteExpectedValue(expectedType); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/LessThanConstraint.cs b/test/NUnitLite/src/framework/Constraints/LessThanConstraint.cs deleted file mode 100644 index 87651a93d..000000000 --- a/test/NUnitLite/src/framework/Constraints/LessThanConstraint.cs +++ /dev/null @@ -1,73 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// Tests whether a value is less than the value supplied to its constructor - /// - public class LessThanConstraint : ComparisonConstraint - { - /// - /// The value against which a comparison is to be made - /// - private object expected; - - /// - /// Initializes a new instance of the class. - /// - /// The expected value. - public LessThanConstraint(object expected) - : base(expected) - { - this.expected = expected; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("less than"); - writer.WriteExpectedValue(expected); - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (expected == null || actual == null) - throw new ArgumentException("Cannot compare using a null reference"); - - return comparer.Compare(actual, expected) < 0; - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/LessThanOrEqualConstraint.cs b/test/NUnitLite/src/framework/Constraints/LessThanOrEqualConstraint.cs deleted file mode 100644 index 829e62e76..000000000 --- a/test/NUnitLite/src/framework/Constraints/LessThanOrEqualConstraint.cs +++ /dev/null @@ -1,73 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// Tests whether a value is less than or equal to the value supplied to its constructor - /// - public class LessThanOrEqualConstraint : ComparisonConstraint - { - /// - /// The value against which a comparison is to be made - /// - private object expected; - - /// - /// Initializes a new instance of the class. - /// - /// The expected value. - public LessThanOrEqualConstraint(object expected) - : base(expected) - { - this.expected = expected; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("less than or equal to"); - writer.WriteExpectedValue(expected); - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (expected == null || actual == null) - throw new ArgumentException("Cannot compare using a null reference"); - - return comparer.Compare(actual, expected) <= 0; - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/MsgUtils.cs b/test/NUnitLite/src/framework/Constraints/MsgUtils.cs deleted file mode 100644 index c6e1fe122..000000000 --- a/test/NUnitLite/src/framework/Constraints/MsgUtils.cs +++ /dev/null @@ -1,282 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Text; -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// Static methods used in creating messages - /// - public class MsgUtils - { - /// - /// Static string used when strings are clipped - /// - private const string ELLIPSIS = "..."; - - /// - /// Returns the representation of a type as used in NUnitLite. - /// This is the same as Type.ToString() except for arrays, - /// which are displayed with their declared sizes. - /// - /// - /// - public static string GetTypeRepresentation(object obj) - { - Array array = obj as Array; - if (array == null) - return string.Format("<{0}>", obj.GetType()); - - StringBuilder sb = new StringBuilder(); - Type elementType = array.GetType(); - int nest = 0; - while (elementType.IsArray) - { - elementType = elementType.GetElementType(); - ++nest; - } - sb.Append(elementType.ToString()); - sb.Append('['); - for (int r = 0; r < array.Rank; r++) - { - if (r > 0) sb.Append(','); - sb.Append(array.GetLength(r)); - } - sb.Append(']'); - - while (--nest > 0) - sb.Append("[]"); - - return string.Format("<{0}>", sb.ToString()); - } - /// - /// Converts any control characters in a string - /// to their escaped representation. - /// - /// The string to be converted - /// The converted string - public static string EscapeControlChars(string s) - { - if (s != null) - { - StringBuilder sb = new StringBuilder(); - - foreach (char c in s) - { - switch (c) - { - //case '\'': - // sb.Append("\\\'"); - // break; - //case '\"': - // sb.Append("\\\""); - // break; - case '\\': - sb.Append("\\\\"); - break; - case '\0': - sb.Append("\\0"); - break; - case '\a': - sb.Append("\\a"); - break; - case '\b': - sb.Append("\\b"); - break; - case '\f': - sb.Append("\\f"); - break; - case '\n': - sb.Append("\\n"); - break; - case '\r': - sb.Append("\\r"); - break; - case '\t': - sb.Append("\\t"); - break; - case '\v': - sb.Append("\\v"); - break; - - case '\x0085': - case '\x2028': - case '\x2029': - sb.Append(string.Format("\\x{0:X4}", (int)c)); - break; - - default: - sb.Append(c); - break; - } - } - - s = sb.ToString(); - } - - return s; - } - - /// - /// Return the a string representation for a set of indices into an array - /// - /// Array of indices for which a string is needed - public static string GetArrayIndicesAsString(int[] indices) - { - StringBuilder sb = new StringBuilder(); - sb.Append('['); - for (int r = 0; r < indices.Length; r++) - { - if (r > 0) sb.Append(','); - sb.Append(indices[r].ToString()); - } - sb.Append(']'); - return sb.ToString(); - } - - /// - /// Get an array of indices representing the point in a enumerable, - /// collection or array corresponding to a single int index into the - /// collection. - /// - /// The collection to which the indices apply - /// Index in the collection - /// Array of indices - public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, int index) - { - Array array = collection as Array; - - int rank = array == null ? 1 : array.Rank; - int[] result = new int[rank]; - - for (int r = rank; --r > 0; ) - { - int l = array.GetLength(r); - result[r] = index % l; - index /= l; - } - - result[0] = index; - return result; - } - - /// - /// Clip a string to a given length, starting at a particular offset, returning the clipped - /// string with ellipses representing the removed parts - /// - /// The string to be clipped - /// The maximum permitted length of the result string - /// The point at which to start clipping - /// The clipped string - public static string ClipString(string s, int maxStringLength, int clipStart) - { - int clipLength = maxStringLength; - StringBuilder sb = new StringBuilder(); - - if (clipStart > 0) - { - clipLength -= ELLIPSIS.Length; - sb.Append(ELLIPSIS); - } - - if (s.Length - clipStart > clipLength) - { - clipLength -= ELLIPSIS.Length; - sb.Append(s.Substring(clipStart, clipLength)); - sb.Append(ELLIPSIS); - } - else if (clipStart > 0) - sb.Append(s.Substring(clipStart)); - else - sb.Append(s); - - return sb.ToString(); - } - - /// - /// Clip the expected and actual strings in a coordinated fashion, - /// so that they may be displayed together. - /// - /// - /// - /// - /// - public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch) - { - // Case 1: Both strings fit on line - int maxStringLength = Math.Max(expected.Length, actual.Length); - if (maxStringLength <= maxDisplayLength) - return; - - // Case 2: Assume that the tail of each string fits on line - int clipLength = maxDisplayLength - ELLIPSIS.Length; - int clipStart = maxStringLength - clipLength; - - // Case 3: If it doesn't, center the mismatch position - if (clipStart > mismatch) - clipStart = Math.Max(0, mismatch - clipLength / 2); - - expected = ClipString(expected, maxDisplayLength, clipStart); - actual = ClipString(actual, maxDisplayLength, clipStart); - } - - /// - /// Shows the position two strings start to differ. Comparison - /// starts at the start index. - /// - /// The expected string - /// The actual string - /// The index in the strings at which comparison should start - /// Boolean indicating whether case should be ignored - /// -1 if no mismatch found, or the index where mismatch found - static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase) - { - int length = Math.Min(expected.Length, actual.Length); - - string s1 = ignoreCase ? expected.ToLower() : expected; - string s2 = ignoreCase ? actual.ToLower() : actual; - - for (int i = istart; i < length; i++) - { - if (s1[i] != s2[i]) - return i; - } - - // - // Strings have same content up to the length of the shorter string. - // Mismatch occurs because string lengths are different, so show - // that they start differing where the shortest string ends - // - if (expected.Length != actual.Length) - return length; - - // - // Same strings : We shouldn't get here - // - return -1; - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/NUnitEqualityComparer.cs b/test/NUnitLite/src/framework/Constraints/NUnitEqualityComparer.cs deleted file mode 100644 index d3bc1bd04..000000000 --- a/test/NUnitLite/src/framework/Constraints/NUnitEqualityComparer.cs +++ /dev/null @@ -1,482 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using System.Collections; -using System.Reflection; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - /// - /// NUnitEqualityComparer encapsulates NUnit's handling of - /// equality tests between objects. - /// - public class NUnitEqualityComparer - { - #region Static and Instance Fields - - /// - /// If true, all string comparisons will ignore case - /// - private bool caseInsensitive; - - /// - /// If true, arrays will be treated as collections, allowing - /// those of different dimensions to be compared - /// - private bool compareAsCollection; - - /// - /// Comparison objects used in comparisons for some constraints. - /// - private EqualityAdapterList externalComparers = new EqualityAdapterList(); - - /// - /// List of points at which a failure occured. - /// - private FailurePointList failurePoints; - - /// - /// RecursionDetector used to check for recursion when - /// evaluating self-referencing enumerables. - /// - private RecursionDetector recursionDetector; - - private static readonly int BUFFER_SIZE = 4096; - - #endregion - - #region Properties - - /// - /// Returns the default NUnitEqualityComparer - /// - public static NUnitEqualityComparer Default - { - get { return new NUnitEqualityComparer(); } - } - /// - /// Gets and sets a flag indicating whether case should - /// be ignored in determining equality. - /// - public bool IgnoreCase - { - get { return caseInsensitive; } - set { caseInsensitive = value; } - } - - /// - /// Gets and sets a flag indicating that arrays should be - /// compared as collections, without regard to their shape. - /// - public bool CompareAsCollection - { - get { return compareAsCollection; } - set { compareAsCollection = value; } - } - - /// - /// Gets the list of external comparers to be used to - /// test for equality. They are applied to members of - /// collections, in place of NUnit's own logic. - /// -#if CLR_2_0 || CLR_4_0 - public IList ExternalComparers -#else - public IList ExternalComparers -#endif - { - get { return externalComparers; } - } - - /// - /// Gets the list of failure points for the last Match performed. - /// The list consists of objects to be interpreted by the caller. - /// This generally means that the caller may only make use of - /// objects it has placed on the list at a particular depthy. - /// -#if CLR_2_0 || CLR_4_0 - public IList FailurePoints -#else - public IList FailurePoints -#endif - { - get { return failurePoints; } - } - #endregion - - #region Public Methods - /// - /// Compares two objects for equality within a tolerance, setting - /// the tolerance to the actual tolerance used if an empty - /// tolerance is supplied. - /// - public bool AreEqual(object expected, object actual, ref Tolerance tolerance) - { - this.failurePoints = new FailurePointList(); - this.recursionDetector = new RecursionDetector(); - - return ObjectsEqual(expected, actual, ref tolerance); - } - - #endregion - - #region Helper Methods - - private bool ObjectsEqual(object expected, object actual, ref Tolerance tolerance) - { - if (expected == null && actual == null) - return true; - - if (expected == null || actual == null) - return false; - - if (object.ReferenceEquals(expected, actual)) - return true; - - Type xType = expected.GetType(); - Type yType = actual.GetType(); - - EqualityAdapter externalComparer = GetExternalComparer(expected, actual); - if (externalComparer != null) - return externalComparer.AreEqual(expected, actual); - - if (xType.IsArray && yType.IsArray && !compareAsCollection) - return ArraysEqual((Array)expected, (Array)actual, ref tolerance); - - if (expected is IDictionary && actual is IDictionary) - return DictionariesEqual((IDictionary)expected, (IDictionary)actual, ref tolerance); - - if (expected is IEnumerable && actual is IEnumerable && !(expected is string && actual is string)) - return EnumerablesEqual((IEnumerable)expected, (IEnumerable)actual, ref tolerance); - - if (expected is string && actual is string) - return StringsEqual((string)expected, (string)actual); - - if (expected is Stream && actual is Stream) - return StreamsEqual((Stream)expected, (Stream)actual); - - if (expected is DirectoryInfo && actual is DirectoryInfo) - return DirectoriesEqual((DirectoryInfo)expected, (DirectoryInfo)actual); - - if (Numerics.IsNumericType(expected) && Numerics.IsNumericType(actual)) - return Numerics.AreEqual(expected, actual, ref tolerance); - - if (tolerance != null && tolerance.Value is TimeSpan) - { - TimeSpan amount = (TimeSpan)tolerance.Value; - - if (expected is DateTime && actual is DateTime) - return ((DateTime)expected - (DateTime)actual).Duration() <= amount; - - if (expected is TimeSpan && actual is TimeSpan) - return ((TimeSpan)expected - (TimeSpan)actual).Duration() <= amount; - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF - if (FirstImplementsIEquatableOfSecond(xType, yType)) - return InvokeFirstIEquatableEqualsSecond(expected, actual); - else if (FirstImplementsIEquatableOfSecond(yType, xType)) - return InvokeFirstIEquatableEqualsSecond(actual, expected); -#endif - - return expected.Equals(actual); - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF - private static bool FirstImplementsIEquatableOfSecond(Type first, Type second) - { - Type[] equatableArguments = GetEquatableGenericArguments(first); - - foreach (var xEquatableArgument in equatableArguments) - if (xEquatableArgument.Equals(second)) - return true; - - return false; - } - - private static Type[] GetEquatableGenericArguments(Type type) - { - foreach (Type @interface in type.GetInterfaces()) - if (@interface.IsGenericType && @interface.GetGenericTypeDefinition().Equals(typeof(IEquatable<>))) - return @interface.GetGenericArguments(); - - return new Type[0]; - } - - private static bool InvokeFirstIEquatableEqualsSecond(object first, object second) - { - MethodInfo equals = typeof(IEquatable<>).MakeGenericType(second.GetType()).GetMethod("Equals"); - - return (bool)equals.Invoke(first, new object[] { second }); - } -#endif - - private EqualityAdapter GetExternalComparer(object x, object y) - { - foreach (EqualityAdapter adapter in externalComparers) - if (adapter.CanCompare(x, y)) - return adapter; - - return null; - } - - /// - /// Helper method to compare two arrays - /// - private bool ArraysEqual(Array expected, Array actual, ref Tolerance tolerance) - { - int rank = expected.Rank; - - if (rank != actual.Rank) - return false; - - for (int r = 1; r < rank; r++) - if (expected.GetLength(r) != actual.GetLength(r)) - return false; - - return EnumerablesEqual((IEnumerable)expected, (IEnumerable)actual, ref tolerance); - } - - private bool DictionariesEqual(IDictionary expected, IDictionary actual, ref Tolerance tolerance) - { - if (expected.Count != actual.Count) - return false; - - CollectionTally tally = new CollectionTally(this, expected.Keys); - if (!tally.TryRemove(actual.Keys) || tally.Count > 0) - return false; - - foreach (object key in expected.Keys) - if (!ObjectsEqual(expected[key], actual[key], ref tolerance)) - return false; - - return true; - } - - private bool StringsEqual(string expected, string actual) - { - string s1 = caseInsensitive ? expected.ToLower() : expected; - string s2 = caseInsensitive ? actual.ToLower() : actual; - - return s1.Equals(s2); - } - - private bool EnumerablesEqual(IEnumerable expected, IEnumerable actual, ref Tolerance tolerance) - { - if (recursionDetector.CheckRecursion(expected, actual)) - return false; - - IEnumerator expectedEnum = expected.GetEnumerator(); - IEnumerator actualEnum = actual.GetEnumerator(); - - int count; - for (count = 0; ; count++) - { - bool expectedHasData = expectedEnum.MoveNext(); - bool actualHasData = actualEnum.MoveNext(); - - if (!expectedHasData && !actualHasData) - return true; - - if (expectedHasData != actualHasData || - !ObjectsEqual(expectedEnum.Current, actualEnum.Current, ref tolerance)) - { - FailurePoint fp = new FailurePoint(); - fp.Position = count; - fp.ExpectedHasData = expectedHasData; - if (expectedHasData) - fp.ExpectedValue = expectedEnum.Current; - fp.ActualHasData = actualHasData; - if (actualHasData) - fp.ActualValue = actualEnum.Current; - failurePoints.Insert(0, fp); - return false; - } - } - } - - /// - /// Method to compare two DirectoryInfo objects - /// - /// first directory to compare - /// second directory to compare - /// true if equivalent, false if not - private static bool DirectoriesEqual(DirectoryInfo expected, DirectoryInfo actual) - { - // Do quick compares first - if (expected.Attributes != actual.Attributes || - expected.CreationTime != actual.CreationTime || - expected.LastAccessTime != actual.LastAccessTime) - { - return false; - } - - // TODO: Find a cleaner way to do this - return new SamePathConstraint(expected.FullName).Matches(actual.FullName); - } - - private bool StreamsEqual(Stream expected, Stream actual) - { - if (expected == actual) return true; - - if (!expected.CanRead) - throw new ArgumentException("Stream is not readable", "expected"); - if (!actual.CanRead) - throw new ArgumentException("Stream is not readable", "actual"); - if (!expected.CanSeek) - throw new ArgumentException("Stream is not seekable", "expected"); - if (!actual.CanSeek) - throw new ArgumentException("Stream is not seekable", "actual"); - - if (expected.Length != actual.Length) return false; - - byte[] bufferExpected = new byte[BUFFER_SIZE]; - byte[] bufferActual = new byte[BUFFER_SIZE]; - - BinaryReader binaryReaderExpected = new BinaryReader(expected); - BinaryReader binaryReaderActual = new BinaryReader(actual); - - long expectedPosition = expected.Position; - long actualPosition = actual.Position; - - try - { - binaryReaderExpected.BaseStream.Seek(0, SeekOrigin.Begin); - binaryReaderActual.BaseStream.Seek(0, SeekOrigin.Begin); - - for (long readByte = 0; readByte < expected.Length; readByte += BUFFER_SIZE) - { - binaryReaderExpected.Read(bufferExpected, 0, BUFFER_SIZE); - binaryReaderActual.Read(bufferActual, 0, BUFFER_SIZE); - - for (int count = 0; count < BUFFER_SIZE; ++count) - { - if (bufferExpected[count] != bufferActual[count]) - { - FailurePoint fp = new FailurePoint(); - fp.Position = (int)readByte + count; - failurePoints.Insert(0, fp); - return false; - } - } - } - } - finally - { - expected.Position = expectedPosition; - actual.Position = actualPosition; - } - - return true; - } - - #endregion - - #region Nested RecursionDetector class - - /// - /// RecursionDetector detects when a comparison - /// between two enumerables has reached a point - /// where the same objects that were previously - /// compared are again being compared. This allows - /// the caller to stop the comparison if desired. - /// - class RecursionDetector - { -#if CLR_2_0 || CLR_4_0 - readonly Dictionary table = new Dictionary(); -#else - readonly Hashtable table = new Hashtable(); -#endif - - /// - /// Check whether two objects have previously - /// been compared, returning true if they have. - /// The two objects are remembered, so that a - /// second call will always return true. - /// - public bool CheckRecursion(IEnumerable expected, IEnumerable actual) - { - UnorderedReferencePair pair = new UnorderedReferencePair(expected, actual); - - if (ContainsPair(pair)) - return true; - - table.Add(pair, null); - return false; - } - - private bool ContainsPair(UnorderedReferencePair pair) - { -#if CLR_2_0 || CLR_4_0 - return table.ContainsKey(pair); -#else - return table.Contains(pair); -#endif - } - -#if CLR_2_0 || CLR_4_0 - class UnorderedReferencePair : IEquatable -#else - class UnorderedReferencePair -#endif - { - private readonly object first; - private readonly object second; - - public UnorderedReferencePair(object first, object second) - { - this.first = first; - this.second = second; - } - - public bool Equals(UnorderedReferencePair other) - { - return (Equals(first, other.first) && Equals(second, other.second)) || - (Equals(first, other.second) && Equals(second, other.first)); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is UnorderedReferencePair && Equals((UnorderedReferencePair)obj); - } - - public override int GetHashCode() - { - unchecked - { - return ((first != null ? first.GetHashCode() : 0) * 397) ^ ((second != null ? second.GetHashCode() : 0) * 397); - } - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/NoItemConstraint.cs b/test/NUnitLite/src/framework/Constraints/NoItemConstraint.cs deleted file mode 100644 index 94311446a..000000000 --- a/test/NUnitLite/src/framework/Constraints/NoItemConstraint.cs +++ /dev/null @@ -1,75 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Constraints -{ - /// - /// NoItemConstraint applies another constraint to each - /// item in a collection, failing if any of them succeeds. - /// - public class NoItemConstraint : PrefixConstraint - { - /// - /// Construct a NoItemConstraint on top of an existing constraint - /// - /// - public NoItemConstraint(Constraint itemConstraint) - : base(itemConstraint) - { - this.DisplayName = "none"; - } - - /// - /// Apply the item constraint to each item in the collection, - /// failing if any item fails. - /// - /// - /// - public override bool Matches(object actual) - { - this.actual = actual; - - if (!(actual is IEnumerable)) - throw new ArgumentException("The actual value must be an IEnumerable", "actual"); - - foreach (object item in (IEnumerable)actual) - if (baseConstraint.Matches(item)) - return false; - - return true; - } - - /// - /// Write a description of this constraint to a MessageWriter - /// - /// - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("no item"); - baseConstraint.WriteDescriptionTo(writer); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/NotConstraint.cs b/test/NUnitLite/src/framework/Constraints/NotConstraint.cs deleted file mode 100644 index 36f1196bb..000000000 --- a/test/NUnitLite/src/framework/Constraints/NotConstraint.cs +++ /dev/null @@ -1,68 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// NotConstraint negates the effect of some other constraint - /// - public class NotConstraint : PrefixConstraint - { - /// - /// Initializes a new instance of the class. - /// - /// The base constraint to be negated. - public NotConstraint(Constraint baseConstraint) - : base(baseConstraint) { } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for if the base constraint fails, false if it succeeds - public override bool Matches(object actual) - { - this.actual = actual; - return !baseConstraint.Matches(actual); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("not"); - baseConstraint.WriteDescriptionTo(writer); - } - - /// - /// Write the actual value for a failing constraint test to a MessageWriter. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - baseConstraint.WriteActualValueTo(writer); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/NullConstraint.cs b/test/NUnitLite/src/framework/Constraints/NullConstraint.cs deleted file mode 100644 index a8bfe0448..000000000 --- a/test/NUnitLite/src/framework/Constraints/NullConstraint.cs +++ /dev/null @@ -1,36 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// NullConstraint tests that the actual value is null - /// - public class NullConstraint : BasicConstraint - { - /// - /// Initializes a new instance of the class. - /// - public NullConstraint() : base(null, "null") { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/NullOrEmptyStringConstraint.cs b/test/NUnitLite/src/framework/Constraints/NullOrEmptyStringConstraint.cs deleted file mode 100644 index 7731d7449..000000000 --- a/test/NUnitLite/src/framework/Constraints/NullOrEmptyStringConstraint.cs +++ /dev/null @@ -1,72 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// NullEmptyStringConstraint tests whether a string is either null or empty. - /// - public class NullOrEmptyStringConstraint : Constraint - { - /// - /// Constructs a new NullOrEmptyStringConstraint - /// - public NullOrEmptyStringConstraint() - { - this.DisplayName = "nullorempty"; - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - // NOTE: Do not change this to use string.IsNullOrEmpty - // since that won't work in earlier versions of .NET - - this.actual = actual; - - if (actual == null) return true; - - string actualAsString = actual as string; - - if (actualAsString == null) - throw new ArgumentException("Actual value must be a string", "actual"); - - return actualAsString == string.Empty; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write("null or empty string"); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/PathConstraint.cs b/test/NUnitLite/src/framework/Constraints/PathConstraint.cs deleted file mode 100644 index 786d52a2a..000000000 --- a/test/NUnitLite/src/framework/Constraints/PathConstraint.cs +++ /dev/null @@ -1,181 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints -{ - /// - /// PathConstraint serves as the abstract base of constraints - /// that operate on paths and provides several helper methods. - /// - public abstract class PathConstraint : Constraint - { - private static readonly char[] DirectorySeparatorChars = new char[] { '\\', '/' }; - - /// - /// The expected path used in the constraint - /// - protected string expectedPath; - - /// - /// Flag indicating whether a caseInsensitive comparison should be made - /// - protected bool caseInsensitive = Path.DirectorySeparatorChar == '\\'; - - /// - /// Construct a PathConstraint for a give expected path - /// - /// The expected path - protected PathConstraint(string expectedPath) : base(expectedPath) - { - this.expectedPath = expectedPath; - } - - /// - /// Modifies the current instance to be case-insensitve - /// and returns it. - /// - public PathConstraint IgnoreCase - { - get { caseInsensitive = true; return this; } - } - - /// - /// Modifies the current instance to be case-sensitve - /// and returns it. - /// - public PathConstraint RespectCase - { - get { caseInsensitive = false; return this; } - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - string actualPath = actual as string; - - return actualPath != null && IsMatch(expectedPath, actualPath); - } - - /// - /// Returns true if the expected path and actual path match - /// - protected abstract bool IsMatch(string expectedPath, string actualPath); - - /// - /// Returns the string representation of this constraint - /// - protected override string GetStringRepresentation() - { - return string.Format("<{0} \"{1}\" {2}>", DisplayName, expectedPath, caseInsensitive ? "ignorecase" : "respectcase"); - } - - #region Static Helper Methods - - /// - /// Transform the provided path to its canonical form so that it - /// may be more easily be compared with other paths. - /// - /// The original path - /// The path in canonical form - protected static string Canonicalize(string path) - { - if (Path.DirectorySeparatorChar != Path.AltDirectorySeparatorChar) - path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); - string leadingSeparators = ""; - foreach (char c in path) - { - if (c == Path.DirectorySeparatorChar) - leadingSeparators += c; - else break; - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF - string[] parts = path.Split(DirectorySeparatorChars, StringSplitOptions.RemoveEmptyEntries); -#else - string[] parts = path.Split(DirectorySeparatorChars); -#endif - int count = 0; - bool shifting = false; - foreach (string part in parts) - { - switch (part) - { - case "": - case ".": - shifting = true; - break; - - case "..": - shifting = true; - if (count > 0) - --count; - break; - - default: - if (shifting) - parts[count] = part; - ++count; - break; - } - } - - return leadingSeparators + String.Join(Path.DirectorySeparatorChar.ToString(), parts, 0, count); - } - - /// - /// Test whether one path in canonical form is under another. - /// - /// The first path - supposed to be the parent path - /// The second path - supposed to be the child path - /// Indicates whether case should be ignored - /// - protected static bool IsSubPath(string path1, string path2, bool ignoreCase) - { - int length1 = path1.Length; - int length2 = path2.Length; - - // if path1 is longer or equal, then path2 can't be under it - if (length1 >= length2) - return false; - - // path 2 is longer than path 1: see if initial parts match - if (!StringUtil.StringsEqual(path1, path2.Substring(0, length1), ignoreCase)) - return false; - - // must match through or up to a directory separator boundary - return path2[length1 - 1] == Path.DirectorySeparatorChar || - length2 > length1 && path2[length1] == Path.DirectorySeparatorChar; - } - - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/PrefixConstraint.cs b/test/NUnitLite/src/framework/Constraints/PrefixConstraint.cs deleted file mode 100644 index 7d5a52759..000000000 --- a/test/NUnitLite/src/framework/Constraints/PrefixConstraint.cs +++ /dev/null @@ -1,46 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// Abstract base class used for prefixes - /// - public abstract class PrefixConstraint : Constraint - { - /// - /// The base constraint - /// - protected Constraint baseConstraint; - - /// - /// Construct given a base constraint - /// - /// - protected PrefixConstraint(IResolveConstraint resolvable) : base(resolvable) - { - if (resolvable != null) - this.baseConstraint = resolvable.Resolve(); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/PropertyConstraint.cs b/test/NUnitLite/src/framework/Constraints/PropertyConstraint.cs deleted file mode 100644 index e862f2031..000000000 --- a/test/NUnitLite/src/framework/Constraints/PropertyConstraint.cs +++ /dev/null @@ -1,110 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Constraints -{ - /// - /// PropertyConstraint extracts a named property and uses - /// its value as the actual value for a chained constraint. - /// - public class PropertyConstraint : PrefixConstraint - { - private readonly string name; - private object propValue; - - /// - /// Initializes a new instance of the class. - /// - /// The name. - /// The constraint to apply to the property. - public PropertyConstraint(string name, Constraint baseConstraint) - : base(baseConstraint) - { - this.name = name; - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - Guard.ArgumentNotNull(actual, "actual"); - - Type actualType = actual as Type; - if (actualType == null) - actualType = actual.GetType(); - - PropertyInfo property = actualType.GetProperty(name, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty); - - if (property == null) - throw new ArgumentException(string.Format("Property {0} was not found", name), "name"); - - propValue = property.GetGetMethod().Invoke(actual, null); - return baseConstraint.Matches(propValue); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("property " + name); - if (baseConstraint != null) - { - if (baseConstraint is EqualConstraint) - writer.WritePredicate("equal to"); - baseConstraint.WriteDescriptionTo(writer); - } - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - writer.WriteActualValue(propValue); - } - - /// - /// Returns the string representation of the constraint. - /// - /// - protected override string GetStringRepresentation() - { - return string.Format("", name, baseConstraint); - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/PropertyExistsConstraint.cs b/test/NUnitLite/src/framework/Constraints/PropertyExistsConstraint.cs deleted file mode 100644 index d863cf25e..000000000 --- a/test/NUnitLite/src/framework/Constraints/PropertyExistsConstraint.cs +++ /dev/null @@ -1,102 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Constraints -{ - /// - /// PropertyExistsConstraint tests that a named property - /// exists on the object provided through Match. - /// - /// Originally, PropertyConstraint provided this feature - /// in addition to making optional tests on the vaue - /// of the property. The two constraints are now separate. - /// - public class PropertyExistsConstraint : Constraint - { - private readonly string name; - - Type actualType; - - /// - /// Initializes a new instance of the class. - /// - /// The name of the property. - public PropertyExistsConstraint(string name) - : base(name) - { - this.name = name; - } - - /// - /// Test whether the property exists for a given object - /// - /// The object to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - Guard.ArgumentNotNull(actual, "actual"); - - this.actualType = actual as Type; - if (actualType == null) - actualType = actual.GetType(); - - PropertyInfo property = actualType.GetProperty(name, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty); - - return property != null; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write("property " + name); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - writer.WriteActualValue(actualType); - } - - /// - /// Returns the string representation of the constraint. - /// - /// - protected override string GetStringRepresentation() - { - return string.Format("", name); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/RangeConstraint.cs b/test/NUnitLite/src/framework/Constraints/RangeConstraint.cs deleted file mode 100644 index 7eb7cd159..000000000 --- a/test/NUnitLite/src/framework/Constraints/RangeConstraint.cs +++ /dev/null @@ -1,124 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints -{ - /// - /// RangeConstraint tests whether two values are within a - /// specified range. - /// -#if CLR_2_0 || CLR_4_0 - public class RangeConstraint : ComparisonConstraint where T : IComparable - { - private readonly T from; - private readonly T to; - - /// - /// Initializes a new instance of the class. - /// - /// From. - /// To. - public RangeConstraint(T from, T to) - : base(from, to) - { - this.from = from; - this.to = to; - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if (from == null || to == null || actual == null) - throw new ArgumentException("Cannot compare using a null reference", "actual"); - - return comparer.Compare(from, actual) <= 0 && - comparer.Compare(to, actual) >= 0; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - - writer.Write("in range ({0},{1})", from, to); - } - } -#else - public class RangeConstraint : ComparisonConstraint - { - private readonly IComparable from; - private readonly IComparable to; - - /// - /// Initializes a new instance of the class. - /// - /// From. - /// To. - public RangeConstraint(IComparable from, IComparable to) : base( from, to ) - { - this.from = from; - this.to = to; - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if ( from == null || to == null || actual == null) - throw new ArgumentException( "Cannot compare using a null reference", "actual" ); - - return comparer.Compare(from, actual) <= 0 && - comparer.Compare(to, actual) >= 0; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - - writer.Write("in range ({0},{1})", from, to); - } - } -#endif -} diff --git a/test/NUnitLite/src/framework/Constraints/ResolvableConstraintExpression.cs b/test/NUnitLite/src/framework/Constraints/ResolvableConstraintExpression.cs deleted file mode 100644 index 25d7f3fb0..000000000 --- a/test/NUnitLite/src/framework/Constraints/ResolvableConstraintExpression.cs +++ /dev/null @@ -1,153 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// ResolvableConstraintExpression is used to represent a compound - /// constraint being constructed at a point where the last operator - /// may either terminate the expression or may have additional - /// qualifying constraints added to it. - /// - /// It is used, for example, for a Property element or for - /// an Exception element, either of which may be optionally - /// followed by constraints that apply to the property or - /// exception. - /// - public class ResolvableConstraintExpression : ConstraintExpression, IResolveConstraint - { - /// - /// Create a new instance of ResolvableConstraintExpression - /// - public ResolvableConstraintExpression() { } - - /// - /// Create a new instance of ResolvableConstraintExpression, - /// passing in a pre-populated ConstraintBuilder. - /// - public ResolvableConstraintExpression(ConstraintBuilder builder) - : base(builder) { } - - /// - /// Appends an And Operator to the expression - /// - public ConstraintExpression And - { - get { return this.Append(new AndOperator()); } - } - - /// - /// Appends an Or operator to the expression. - /// - public ConstraintExpression Or - { - get { return this.Append(new OrOperator()); } - } - - #region IResolveConstraint Members - /// - /// Resolve the current expression to a Constraint - /// - Constraint IResolveConstraint.Resolve() - { - return builder.Resolve(); - } - #endregion - - #region Operator Overloads - /// - /// This operator creates a constraint that is satisfied only if both - /// argument constraints are satisfied. - /// - public static Constraint operator &(ResolvableConstraintExpression left, ResolvableConstraintExpression right) - { - return OperatorAndImplementation(left, right); - } - - /// - /// This operator creates a constraint that is satisfied only if both - /// argument constraints are satisfied. - /// - public static Constraint operator &(Constraint left, ResolvableConstraintExpression right) - { - return OperatorAndImplementation(left, right); - } - - /// - /// This operator creates a constraint that is satisfied only if both - /// argument constraints are satisfied. - /// - public static Constraint operator &(ResolvableConstraintExpression left, Constraint right) - { - return OperatorAndImplementation(left, right); - } - - private static Constraint OperatorAndImplementation(IResolveConstraint left, IResolveConstraint right) - { - return new AndConstraint(left.Resolve(), right.Resolve()); - } - - /// - /// This operator creates a constraint that is satisfied if either - /// of the argument constraints is satisfied. - /// - public static Constraint operator |(ResolvableConstraintExpression left, ResolvableConstraintExpression right) - { - return OperatorOrImplementation(left, right); - } - - /// - /// This operator creates a constraint that is satisfied if either - /// of the argument constraints is satisfied. - /// - public static Constraint operator |(ResolvableConstraintExpression left, Constraint right) - { - return OperatorOrImplementation(left, right); - } - - /// - /// This operator creates a constraint that is satisfied if either - /// of the argument constraints is satisfied. - /// - public static Constraint operator |(Constraint left, ResolvableConstraintExpression right) - { - return OperatorOrImplementation(left, right); - } - - private static Constraint OperatorOrImplementation(IResolveConstraint left, IResolveConstraint right) - { - return new OrConstraint(left.Resolve(), right.Resolve()); - } - - /// - /// This operator creates a constraint that is satisfied if the - /// argument constraint is not satisfied. - /// - public static Constraint operator !(ResolvableConstraintExpression constraint) - { - IResolveConstraint r = constraint as IResolveConstraint; - return new NotConstraint(r == null ? new NullConstraint() : r.Resolve()); - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Constraints/SamePathConstraint.cs b/test/NUnitLite/src/framework/Constraints/SamePathConstraint.cs deleted file mode 100644 index a64097916..000000000 --- a/test/NUnitLite/src/framework/Constraints/SamePathConstraint.cs +++ /dev/null @@ -1,60 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints -{ - /// - /// Summary description for SamePathConstraint. - /// - public class SamePathConstraint : PathConstraint - { - /// - /// Initializes a new instance of the class. - /// - /// The expected path - public SamePathConstraint(string expected) : base(expected) { } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The expected path - /// The actual path - /// True for success, false for failure - protected override bool IsMatch(string expectedPath, string actualPath) - { - return StringUtil.StringsEqual(Canonicalize(expectedPath), Canonicalize(actualPath), caseInsensitive); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("Path matching"); - writer.WriteExpectedValue(expectedPath); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/SamePathOrUnderConstraint.cs b/test/NUnitLite/src/framework/Constraints/SamePathOrUnderConstraint.cs deleted file mode 100644 index bb0321f2b..000000000 --- a/test/NUnitLite/src/framework/Constraints/SamePathOrUnderConstraint.cs +++ /dev/null @@ -1,62 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints -{ - /// - /// SamePathOrUnderConstraint tests that one path is under another - /// - public class SamePathOrUnderConstraint : PathConstraint - { - /// - /// Initializes a new instance of the class. - /// - /// The expected path - public SamePathOrUnderConstraint(string expected) : base(expected) { } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The expected path - /// The actual path - /// True for success, false for failure - protected override bool IsMatch(string expectedPath, string actualPath) - { - string path1 = Canonicalize(expectedPath); - string path2 = Canonicalize(actualPath); - return StringUtil.StringsEqual(path1, path2, caseInsensitive) || IsSubPath(path1, path2, caseInsensitive); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("Path under or matching"); - writer.WriteExpectedValue(expectedPath); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/StartsWithConstraint.cs b/test/NUnitLite/src/framework/Constraints/StartsWithConstraint.cs deleted file mode 100644 index 51be3de24..000000000 --- a/test/NUnitLite/src/framework/Constraints/StartsWithConstraint.cs +++ /dev/null @@ -1,65 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// StartsWithConstraint can test whether a string starts - /// with an expected substring. - /// - public class StartsWithConstraint : StringConstraint - { - /// - /// Initializes a new instance of the class. - /// - /// The expected string - public StartsWithConstraint(string expected) : base(expected) { } - - /// - /// Test whether the constraint is matched by the actual value. - /// This is a template method, which calls the IsMatch method - /// of the derived class. - /// - /// - /// - protected override bool Matches(string actual) - { - if (this.caseInsensitive) - return actual.ToLower().StartsWith(expected.ToLower()); - else - return actual.StartsWith(expected); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("String starting with"); - writer.WriteExpectedValue(MsgUtils.ClipString(expected, writer.MaxLineLength - 40, 0)); - if (this.caseInsensitive) - writer.WriteModifier("ignoring case"); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/StringConstraint.cs b/test/NUnitLite/src/framework/Constraints/StringConstraint.cs deleted file mode 100644 index f9e7a0faf..000000000 --- a/test/NUnitLite/src/framework/Constraints/StringConstraint.cs +++ /dev/null @@ -1,81 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// StringConstraint is the abstract base for constraints - /// that operate on strings. It supports the IgnoreCase - /// modifier for string operations. - /// - public abstract class StringConstraint : Constraint - { - /// - /// The expected value - /// - protected readonly string expected; - - /// - /// Indicates whether tests should be case-insensitive - /// - protected bool caseInsensitive; - - /// - /// Constructs a StringConstraint given an expected value - /// - /// The expected value - protected StringConstraint(string expected) - : base(expected) - { - this.expected = expected; - } - - /// - /// Modify the constraint to ignore case in matching. - /// - public StringConstraint IgnoreCase - { - get { caseInsensitive = true; return this; } - } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - string actualAsString = actual as string; - return actualAsString != null && Matches(actualAsString); - } - - /// - /// Test whether the constraint is satisfied by a given string - /// - /// The string to be tested - /// True for success, false for failure - protected abstract bool Matches(string actual); - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/SubPathConstraint.cs b/test/NUnitLite/src/framework/Constraints/SubPathConstraint.cs deleted file mode 100644 index 4c3528bf4..000000000 --- a/test/NUnitLite/src/framework/Constraints/SubPathConstraint.cs +++ /dev/null @@ -1,60 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// SubPathConstraint tests that the actual path is under the expected path - /// - public class SubPathConstraint : PathConstraint - { - /// - /// Initializes a new instance of the class. - /// - /// The expected path - public SubPathConstraint(string expected) : base(expected) { } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The expected path - /// The actual path - /// True for success, false for failure - protected override bool IsMatch(string expectedPath, string actualPath) - { - return IsSubPath(Canonicalize(expectedPath), Canonicalize(actualPath), caseInsensitive); - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("Path under"); - writer.WriteExpectedValue(expectedPath); - } - } -} diff --git a/test/NUnitLite/src/framework/Constraints/SubstringConstraint.cs b/test/NUnitLite/src/framework/Constraints/SubstringConstraint.cs deleted file mode 100644 index 716abae38..000000000 --- a/test/NUnitLite/src/framework/Constraints/SubstringConstraint.cs +++ /dev/null @@ -1,63 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// SubstringConstraint can test whether a string contains - /// the expected substring. - /// - public class SubstringConstraint : StringConstraint - { - /// - /// Initializes a new instance of the class. - /// - /// The expected. - public SubstringConstraint(string expected) : base(expected) { } - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - protected override bool Matches(string actual) - { - if (this.caseInsensitive) - return actual.ToLower().IndexOf(expected.ToLower()) >= 0; - else - return actual.IndexOf(expected) >= 0; - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.WritePredicate("String containing"); - writer.WriteExpectedValue(expected); - if (this.caseInsensitive) - writer.WriteModifier("ignoring case"); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/ThrowsConstraint.cs b/test/NUnitLite/src/framework/Constraints/ThrowsConstraint.cs deleted file mode 100644 index 1ddb5cb01..000000000 --- a/test/NUnitLite/src/framework/Constraints/ThrowsConstraint.cs +++ /dev/null @@ -1,267 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints -{ - /// - /// ThrowsConstraint is used to test the exception thrown by - /// a delegate by applying a constraint to it. - /// - public class ThrowsConstraint : PrefixConstraint - { - private Exception caughtException; - - /// - /// Initializes a new instance of the class, - /// using a constraint to be applied to the exception. - /// - /// A constraint to apply to the caught exception. - public ThrowsConstraint(Constraint baseConstraint) - : base(baseConstraint) { } - - /// - /// Get the actual exception thrown - used by Assert.Throws. - /// - public Exception ActualException - { - get { return caughtException; } - } - - #region Constraint Overrides - - /// - /// Executes the code of the delegate and captures any exception. - /// If a non-null base constraint was provided, it applies that - /// constraint to the exception. - /// - /// A delegate representing the code to be tested - /// True if an exception is thrown and the constraint succeeds, otherwise false - public override bool Matches(object actual) - { - caughtException = ExceptionInterceptor.Intercept(actual); - - if (caughtException == null) - return false; - - return baseConstraint == null || baseConstraint.Matches(caughtException); - } - - /// - /// Converts an ActualValueDelegate to a TestDelegate - /// before calling the primary overload. - /// -#if CLR_2_0 || CLR_4_0 - public override bool Matches(ActualValueDelegate del) - { - return Matches(new GenericInvocationDescriptor(del)); - } -#else - public override bool Matches(ActualValueDelegate del) - { - return Matches(new ObjectInvocationDescriptor(del)); - } -#endif - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - if (baseConstraint == null) - writer.WritePredicate("an exception"); - else - baseConstraint.WriteDescriptionTo(writer); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - if (caughtException == null) - writer.Write("no exception thrown"); - else if (baseConstraint != null) - baseConstraint.WriteActualValueTo(writer); - else - writer.WriteActualValue(caughtException); - } - #endregion - - /// - /// Returns the string representation of this constraint - /// - protected override string GetStringRepresentation() - { - if (baseConstraint == null) - return ""; - - return base.GetStringRepresentation(); - } - } - - #region ExceptionInterceptor - - internal class ExceptionInterceptor - { - private ExceptionInterceptor() { } - - internal static Exception Intercept(object invocation) - { - IInvocationDescriptor invocationDescriptor = GetInvocationDescriptor(invocation); - -#if NET_4_5 - if (AsyncInvocationRegion.IsAsyncOperation(invocationDescriptor.Delegate)) - { - using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(invocationDescriptor.Delegate)) - { - object result = invocationDescriptor.Invoke(); - - try - { - region.WaitForPendingOperationsToComplete(result); - return null; - } - catch (Exception ex) - { - return ex; - } - } - } - else -#endif - { - try - { - invocationDescriptor.Invoke(); - return null; - } - catch (Exception ex) - { - return ex; - } - } - } - - private static IInvocationDescriptor GetInvocationDescriptor(object actual) - { - IInvocationDescriptor invocationDescriptor = actual as IInvocationDescriptor; - - if (invocationDescriptor == null) - { - TestDelegate testDelegate = actual as TestDelegate; - - if (testDelegate == null) - throw new ArgumentException( - String.Format("The actual value must be a TestDelegate or ActualValueDelegate but was {0}", actual.GetType().Name), - "actual"); - - invocationDescriptor = new VoidInvocationDescriptor(testDelegate); - } - - return invocationDescriptor; - } - } - - #endregion - - #region InvocationDescriptor - - internal class VoidInvocationDescriptor : IInvocationDescriptor - { - private readonly TestDelegate _del; - - public VoidInvocationDescriptor(TestDelegate del) - { - _del = del; - } - - public object Invoke() - { - _del(); - return null; - } - - public Delegate Delegate - { - get { return _del; } - } - } - -#if CLR_2_0 || CLR_4_0 - internal class GenericInvocationDescriptor : IInvocationDescriptor - { - private readonly ActualValueDelegate _del; - - public GenericInvocationDescriptor(ActualValueDelegate del) - { - _del = del; - } - - public object Invoke() - { - return _del(); - } - - public Delegate Delegate - { - get { return _del; } - } - } -#else - internal class ObjectInvocationDescriptor : IInvocationDescriptor - { - private readonly ActualValueDelegate _del; - - public ObjectInvocationDescriptor(ActualValueDelegate del) - { - _del = del; - } - - public object Invoke() - { - return _del(); - } - - public Delegate Delegate - { - get { return _del; } - } - } -#endif - - internal interface IInvocationDescriptor - { - object Invoke(); - Delegate Delegate { get; } - } - - #endregion -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/ThrowsNothingConstraint.cs b/test/NUnitLite/src/framework/Constraints/ThrowsNothingConstraint.cs deleted file mode 100644 index 2877fc6c1..000000000 --- a/test/NUnitLite/src/framework/Constraints/ThrowsNothingConstraint.cs +++ /dev/null @@ -1,81 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// ThrowsNothingConstraint tests that a delegate does not - /// throw an exception. - /// - public class ThrowsNothingConstraint : Constraint - { - private Exception caughtException; - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True if no exception is thrown, otherwise false - public override bool Matches(object actual) - { - caughtException = ExceptionInterceptor.Intercept(actual); - - return caughtException == null; - } - -#if CLR_2_0 || CLR_4_0 - public override bool Matches(ActualValueDelegate del) - { - return Matches(new GenericInvocationDescriptor(del)); - } -#else - public override bool Matches(ActualValueDelegate del) - { - return Matches(new ObjectInvocationDescriptor(del)); - } -#endif - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write(string.Format("No Exception to be thrown")); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. Overridden in ThrowsNothingConstraint to write - /// information about the exception that was actually caught. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - writer.WriteLine(" ({0})", caughtException.Message); - writer.Write(caughtException.StackTrace); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/TrueConstraint.cs b/test/NUnitLite/src/framework/Constraints/TrueConstraint.cs deleted file mode 100644 index 8ea492a00..000000000 --- a/test/NUnitLite/src/framework/Constraints/TrueConstraint.cs +++ /dev/null @@ -1,36 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints -{ - /// - /// TrueConstraint tests that the actual value is true - /// - public class TrueConstraint : BasicConstraint - { - /// - /// Initializes a new instance of the class. - /// - public TrueConstraint() : base(true, "True") { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/TypeConstraint.cs b/test/NUnitLite/src/framework/Constraints/TypeConstraint.cs deleted file mode 100644 index 245534866..000000000 --- a/test/NUnitLite/src/framework/Constraints/TypeConstraint.cs +++ /dev/null @@ -1,59 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - /// - /// TypeConstraint is the abstract base for constraints - /// that take a Type as their expected value. - /// - public abstract class TypeConstraint : Constraint - { - /// - /// The expected Type used by the constraint - /// - protected readonly Type expectedType; - - /// - /// Construct a TypeConstraint for a given Type - /// - /// - protected TypeConstraint(Type type) : base(type) - { - this.expectedType = type; - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. TypeConstraints override this method to write - /// the name of the type. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - writer.WriteActualValue(actual == null ? null : actual.GetType()); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Constraints/XmlSerializableConstraint.cs b/test/NUnitLite/src/framework/Constraints/XmlSerializableConstraint.cs deleted file mode 100644 index 9443d32c6..000000000 --- a/test/NUnitLite/src/framework/Constraints/XmlSerializableConstraint.cs +++ /dev/null @@ -1,105 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if !SILVERLIGHT -using System; -using System.IO; -using System.Xml.Serialization; - -namespace NUnit.Framework.Constraints -{ - /// - /// XmlSerializableConstraint tests whether - /// an object is serializable in XML format. - /// - public class XmlSerializableConstraint : Constraint - { - private XmlSerializer serializer; - - /// - /// Test whether the constraint is satisfied by a given value - /// - /// The value to be tested - /// True for success, false for failure - public override bool Matches(object actual) - { - this.actual = actual; - - if(actual == null) - throw new ArgumentException(); - - MemoryStream stream = new MemoryStream(); - - try - { - serializer = new XmlSerializer(actual.GetType()); - - serializer.Serialize(stream, actual); - - stream.Seek(0, SeekOrigin.Begin); - - object value = serializer.Deserialize(stream); - - return value != null; - } - catch (NotSupportedException) - { - return false; - } - catch (InvalidOperationException) - { - return false; - } - } - - /// - /// Write the constraint description to a MessageWriter - /// - /// The writer on which the description is displayed - public override void WriteDescriptionTo(MessageWriter writer) - { - writer.Write("xml serializable"); - } - - /// - /// Write the actual value for a failing constraint test to a - /// MessageWriter. The default implementation simply writes - /// the raw value of actual, leaving it to the writer to - /// perform any formatting. - /// - /// The writer on which the actual value is displayed - public override void WriteActualValueTo(MessageWriter writer) - { - writer.Write("<{0}>", actual.GetType().Name); - } - - /// - /// Returns the string representation of this constraint - /// - protected override string GetStringRepresentation() - { - return ""; - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Contains.cs b/test/NUnitLite/src/framework/Contains.cs deleted file mode 100644 index b81ef81cc..000000000 --- a/test/NUnitLite/src/framework/Contains.cs +++ /dev/null @@ -1,62 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework -{ - /// - /// Helper class with properties and methods that supply - /// a number of constraints used in Asserts. - /// - public class Contains - { - #region Item - - /// - /// Returns a new CollectionContainsConstraint checking for the - /// presence of a particular object in the collection. - /// - public static CollectionContainsConstraint Item(object expected) - { - return new CollectionContainsConstraint(expected); - } - - #endregion - - #region Substring - - /// - /// Returns a constraint that succeeds if the actual - /// value contains the substring supplied as an argument. - /// - public static SubstringConstraint Substring(string expected) - { - return new SubstringConstraint(expected);; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Env.cs b/test/NUnitLite/src/framework/Env.cs deleted file mode 100644 index 7f5b8387e..000000000 --- a/test/NUnitLite/src/framework/Env.cs +++ /dev/null @@ -1,56 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Text; - -namespace NUnit -{ - /// - /// Env is a static class that provides some of the features of - /// System.Environment that are not available under all runtimes - /// - public class Env - { - // Define NewLine to be used for this system - // NOTE: Since this is done at compile time for .NET CF, - // these binaries are not yet currently portable. - /// - /// The newline sequence in the current environmemt. - /// -#if PocketPC || WindowsCE || NETCF - public static readonly string NewLine = "\r\n"; -#else - public static readonly string NewLine = Environment.NewLine; -#endif - - /// - /// Path to the 'My Documents' folder - /// -#if SILVERLIGHT || PocketPC || WindowsCE || NETCF - public static string DocumentFolder = @"\My Documents"; -#else - public static string DocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal); -#endif - } -} diff --git a/test/NUnitLite/src/framework/Exceptions/AssertionException.cs b/test/NUnitLite/src/framework/Exceptions/AssertionException.cs deleted file mode 100644 index 424190d3e..000000000 --- a/test/NUnitLite/src/framework/Exceptions/AssertionException.cs +++ /dev/null @@ -1,56 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework -{ - using System; - - /// - /// Thrown when an assertion failed. - /// - [Serializable] - public class AssertionException : System.Exception - { - /// The error message that explains - /// the reason for the exception - public AssertionException (string message) : base(message) - {} - - /// The error message that explains - /// the reason for the exception - /// The exception that caused the - /// current exception - public AssertionException(string message, Exception inner) : - base(message, inner) - {} - -#if !NETCF && !SILVERLIGHT - /// - /// Serialization Constructor - /// - protected AssertionException(System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) : base(info,context) - {} -#endif - } -} diff --git a/test/NUnitLite/src/framework/Exceptions/IgnoreException.cs b/test/NUnitLite/src/framework/Exceptions/IgnoreException.cs deleted file mode 100644 index 442b75923..000000000 --- a/test/NUnitLite/src/framework/Exceptions/IgnoreException.cs +++ /dev/null @@ -1,55 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2004 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework -{ - using System; - - /// - /// Thrown when an assertion failed. - /// - [Serializable] - public class IgnoreException : System.Exception - { - /// - public IgnoreException (string message) : base(message) - {} - - /// The error message that explains - /// the reason for the exception - /// The exception that caused the - /// current exception - public IgnoreException(string message, Exception inner) : - base(message, inner) - {} - -#if !NETCF && !SILVERLIGHT - /// - /// Serialization Constructor - /// - protected IgnoreException(System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) : base(info,context) - {} -#endif - } -} diff --git a/test/NUnitLite/src/framework/Extensibility/ISuiteBuilder.cs b/test/NUnitLite/src/framework/Extensibility/ISuiteBuilder.cs deleted file mode 100644 index 485e5ce0d..000000000 --- a/test/NUnitLite/src/framework/Extensibility/ISuiteBuilder.cs +++ /dev/null @@ -1,55 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Extensibility -{ - /// - /// The ISuiteBuilder interface is exposed by a class that knows how to - /// build a suite from one or more Types. - /// - public interface ISuiteBuilder - { - /// - /// Examine the type and determine if it is suitable for - /// this builder to use in building a TestSuite. - /// - /// Note that returning false will cause the type to be ignored - /// in loading the tests. If it is desired to load the suite - /// but label it as non-runnable, ignored, etc., then this - /// method must return true. - /// - /// The type of the fixture to be used - /// True if the type can be used to build a TestSuite - bool CanBuildFrom( Type type ); - - /// - /// Build a TestSuite from type provided. - /// - /// The type of the fixture to be used - /// A TestSuite - Test BuildFrom( Type type ); - } -} diff --git a/test/NUnitLite/src/framework/Extensibility/ITestCaseBuilder.cs b/test/NUnitLite/src/framework/Extensibility/ITestCaseBuilder.cs deleted file mode 100644 index 7b5c9017e..000000000 --- a/test/NUnitLite/src/framework/Extensibility/ITestCaseBuilder.cs +++ /dev/null @@ -1,88 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Reflection; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Extensibility -{ - /// - /// The ITestCaseBuilder interface is exposed by a class that knows how to - /// build a test case from certain methods. - /// - public interface ITestCaseBuilder - { - /// - /// Examine the method and determine if it is suitable for - /// this builder to use in building a TestCase. - /// - /// Note that returning false will cause the method to be ignored - /// in loading the tests. If it is desired to load the method - /// but label it as non-runnable, ignored, etc., then this - /// method must return true. - /// - /// The test method to examine - /// True is the builder can use this method - bool CanBuildFrom(MethodInfo method); - - /// - /// Build a TestCase from the provided MethodInfo. - /// - /// The method to be used as a test case - /// A TestCase or null - Test BuildFrom(MethodInfo method); - } - - /// - /// ITestCaseBuilder2 extends ITestCaseBuilder with methods - /// that include the suite for which the test case is being - /// built. Test case builders not needing the suite can - /// continue to implement ITestCaseBuilder. - /// - public interface ITestCaseBuilder2 : ITestCaseBuilder - { - /// - /// Examine the method and determine if it is suitable for - /// this builder to use in building a TestCase to be - /// included in the suite being populated. - /// - /// Note that returning false will cause the method to be ignored - /// in loading the tests. If it is desired to load the method - /// but label it as non-runnable, ignored, etc., then this - /// method must return true. - /// - /// The test method to examine - /// The suite being populated - /// True is the builder can use this method - bool CanBuildFrom(MethodInfo method, Test suite); - - /// - /// Build a TestCase from the provided MethodInfo for - /// inclusion in the suite being constructed. - /// - /// The method to be used as a test case - /// The test suite being populated, or null - /// A TestCase or null - Test BuildFrom(MethodInfo method, Test suite); - } -} diff --git a/test/NUnitLite/src/framework/Extensibility/ITestCaseProvider.cs b/test/NUnitLite/src/framework/Extensibility/ITestCaseProvider.cs deleted file mode 100644 index 69e0ec4ab..000000000 --- a/test/NUnitLite/src/framework/Extensibility/ITestCaseProvider.cs +++ /dev/null @@ -1,55 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Reflection; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Extensibility -{ - /// - /// The ITestCaseProvider interface is used by extensions - /// that provide data for parameterized tests, along with - /// certain flags and other indicators used in the test. - /// - public interface ITestCaseProvider - { - /// - /// Determine whether any test cases are available for a parameterized method. - /// - /// A MethodInfo representing a parameterized test - /// True if any cases are available, otherwise false. - bool HasTestCasesFor(MethodInfo method); - - /// - /// Return an IEnumerable providing test cases for use in - /// running a paramterized test. - /// - /// - /// -#if CLR_2_0 || CLR_4_0 - System.Collections.Generic.IEnumerable GetTestCasesFor(MethodInfo method); -#else - System.Collections.IEnumerable GetTestCasesFor(MethodInfo method); -#endif - } -} diff --git a/test/NUnitLite/src/framework/Guard.cs b/test/NUnitLite/src/framework/Guard.cs deleted file mode 100644 index 25285838b..000000000 --- a/test/NUnitLite/src/framework/Guard.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; - -namespace NUnit.Framework -{ - /// - /// Class used to guard against unexpected argument values - /// by throwing an appropriate exception. - /// - public class Guard - { - /// - /// Throws an exception if an argument is null - /// - /// The value to be tested - /// The name of the argument - public static void ArgumentNotNull(object value, string name) - { - if (value == null) - throw new ArgumentNullException("Argument " + name + " must not be null", name); - } - - /// - /// Throws an exception if a string argument is null or empty - /// - /// The value to be tested - /// The name of the argument - public static void ArgumentNotNullOrEmpty(string value, string name) - { - ArgumentNotNull(value, name); - - if (value == string.Empty) - throw new ArgumentException("Argument " + name +" must not be the empty string", name); - } - } -} diff --git a/test/NUnitLite/src/framework/IExpectException.cs b/test/NUnitLite/src/framework/IExpectException.cs deleted file mode 100644 index adcdca719..000000000 --- a/test/NUnitLite/src/framework/IExpectException.cs +++ /dev/null @@ -1,42 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework -{ - /// - /// Interface implemented by a user fixture in order to - /// validate any expected exceptions. It is only called - /// for test methods marked with the ExpectedException - /// attribute. - /// - public interface IExpectException - { - /// - /// Method to handle an expected exception - /// - /// The exception to be handled - void HandleException(Exception ex); - } -} diff --git a/test/NUnitLite/src/framework/Internal/AssemblyHelper.cs b/test/NUnitLite/src/framework/Internal/AssemblyHelper.cs deleted file mode 100644 index 359fd412d..000000000 --- a/test/NUnitLite/src/framework/Internal/AssemblyHelper.cs +++ /dev/null @@ -1,135 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Internal -{ - /// - /// AssemblyHelper provides static methods for working - /// with assemblies. - /// - public class AssemblyHelper - { - #region GetAssemblyPath - -#if !NETCF - /// - /// Gets the path from which the assembly defining a type was loaded. - /// - /// The Type. - /// The path. - public static string GetAssemblyPath(Type type) - { - return GetAssemblyPath(type.Assembly); - } - - /// - /// Gets the path from which an assembly was loaded. - /// - /// The assembly. - /// The path. - public static string GetAssemblyPath(Assembly assembly) - { - string codeBase = assembly.CodeBase; - - if (IsFileUri(codeBase)) - return GetAssemblyPathFromCodeBase(codeBase); - - return assembly.Location; - } -#endif - - #endregion - - #region GetDirectoryName - -#if !NETCF - /// - /// Gets the path to the directory from which an assembly was loaded. - /// - /// The assembly. - /// The path. - public static string GetDirectoryName( Assembly assembly ) - { - return System.IO.Path.GetDirectoryName(GetAssemblyPath(assembly)); - } -#endif - - #endregion - - #region GetAssemblyName - - /// - /// Gets the AssemblyName of an assembly. - /// - /// The assembly - /// An AssemblyName - public static AssemblyName GetAssemblyName(Assembly assembly) - { -#if SILVERLIGHT - return new AssemblyName(assembly.FullName); -#else - return assembly.GetName(); -#endif - } - - #endregion - - #region Helper Methods - -#if !NETCF - private static bool IsFileUri(string uri) - { - return uri.ToLower().StartsWith(Uri.UriSchemeFile); - } - - // Public for testing purposes - public static string GetAssemblyPathFromCodeBase(string codeBase) - { - // Skip over the file:// part - int start = Uri.UriSchemeFile.Length + Uri.SchemeDelimiter.Length; - - bool isWindows = System.IO.Path.DirectorySeparatorChar == '\\'; - - if (codeBase[start] == '/') // third slash means a local path - { - // Handle Windows Drive specifications - if (isWindows && codeBase[start + 2] == ':') - ++start; - // else leave the last slash so path is absolute - } - else // It's either a Windows Drive spec or a share - { - if (!isWindows || codeBase[start + 1] != ':') - start -= 2; // Back up to include two slashes - } - - return codeBase.Substring(start); - } -#endif - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/AsyncInvocationRegion.cs b/test/NUnitLite/src/framework/Internal/AsyncInvocationRegion.cs deleted file mode 100644 index 345a80873..000000000 --- a/test/NUnitLite/src/framework/Internal/AsyncInvocationRegion.cs +++ /dev/null @@ -1,131 +0,0 @@ -#if NET_4_5 -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Threading; - -namespace NUnit.Framework.Internal -{ - internal abstract class AsyncInvocationRegion : IDisposable - { - private static readonly Type AsyncStateMachineAttribute = Type.GetType("System.Runtime.CompilerServices.AsyncStateMachineAttribute"); - private static readonly MethodInfo PreserveStackTraceMethod = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic); - private static readonly Action PreserveStackTrace; - - static AsyncInvocationRegion() - { - PreserveStackTrace = (Action)Delegate.CreateDelegate(typeof(Action), PreserveStackTraceMethod); - } - - private AsyncInvocationRegion() - { - } - - public static AsyncInvocationRegion Create(Delegate @delegate) - { - return Create(@delegate.Method); - } - - public static AsyncInvocationRegion Create(MethodInfo method) - { - if (!IsAsyncOperation(method)) - throw new InvalidOperationException(@"Either asynchronous support is not available or an attempt -at wrapping a non-async method invocation in an async region was done"); - - if (method.ReturnType == typeof(void)) - return new AsyncVoidInvocationRegion(); - - return new AsyncTaskInvocationRegion(); - } - - public static bool IsAsyncOperation(MethodInfo method) - { - return AsyncStateMachineAttribute != null && method.IsDefined(AsyncStateMachineAttribute, false); - } - - public static bool IsAsyncOperation(Delegate @delegate) - { - return IsAsyncOperation(@delegate.Method); - } - - /// - /// Waits for pending asynchronous operations to complete, if appropriate, - /// and returns a proper result of the invocation by unwrapping task results - /// - /// The raw result of the method invocation - /// The unwrapped result, if necessary - public abstract object WaitForPendingOperationsToComplete(object invocationResult); - - public virtual void Dispose() - { } - - private class AsyncVoidInvocationRegion : AsyncInvocationRegion - { - private readonly SynchronizationContext _previousContext; - private readonly AsyncSynchronizationContext _currentContext; - - public AsyncVoidInvocationRegion() - { - _previousContext = SynchronizationContext.Current; - _currentContext = new AsyncSynchronizationContext(); - SynchronizationContext.SetSynchronizationContext(_currentContext); - } - - public override void Dispose() - { - SynchronizationContext.SetSynchronizationContext(_previousContext); - } - - public override object WaitForPendingOperationsToComplete(object invocationResult) - { - try - { - _currentContext.WaitForPendingOperationsToComplete(); - return invocationResult; - } - catch (Exception e) - { - PreserveStackTrace(e); - throw; - } - } - } - - private class AsyncTaskInvocationRegion : AsyncInvocationRegion - { - private const string TaskWaitMethod = "Wait"; - private const string TaskResultProperty = "Result"; - private const string SystemAggregateException = "System.AggregateException"; - private const string InnerExceptionsProperty = "InnerExceptions"; - private const BindingFlags TaskResultPropertyBindingFlags = BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public; - - public override object WaitForPendingOperationsToComplete(object invocationResult) - { - try - { - invocationResult.GetType().GetMethod(TaskWaitMethod, new Type[0]).Invoke(invocationResult, null); - } - catch (TargetInvocationException e) - { - IList innerExceptions = GetAllExceptions(e.InnerException); - - PreserveStackTrace(innerExceptions[0]); - throw innerExceptions[0]; - } - - PropertyInfo taskResultProperty = invocationResult.GetType().GetProperty(TaskResultProperty, TaskResultPropertyBindingFlags); - - return taskResultProperty != null ? taskResultProperty.GetValue(invocationResult, null) : invocationResult; - } - - private static IList GetAllExceptions(Exception exception) - { - if (SystemAggregateException.Equals(exception.GetType().FullName)) - return (IList)exception.GetType().GetProperty(InnerExceptionsProperty).GetValue(exception, null); - - return new Exception[] { exception }; - } - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/AsyncSynchronizationContext.cs b/test/NUnitLite/src/framework/Internal/AsyncSynchronizationContext.cs deleted file mode 100644 index 6187a2c07..000000000 --- a/test/NUnitLite/src/framework/Internal/AsyncSynchronizationContext.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections; -using System.Threading; - -namespace NUnit.Framework.Internal -{ - internal class AsyncSynchronizationContext : SynchronizationContext - { - private int _operationCount; - private readonly AsyncOperationQueue _operations = new AsyncOperationQueue(); - - public override void Send(SendOrPostCallback d, object state) - { - throw new InvalidOperationException("Sending to this synchronization context is not supported"); - } - - public override void Post(SendOrPostCallback d, object state) - { - _operations.Enqueue(new AsyncOperation(d, state)); - } - - public override void OperationStarted() - { - Interlocked.Increment(ref _operationCount); - base.OperationStarted(); - } - - public override void OperationCompleted() - { - if (Interlocked.Decrement(ref _operationCount) == 0) - _operations.MarkAsComplete(); - - base.OperationCompleted(); - } - - public void WaitForPendingOperationsToComplete() - { - _operations.InvokeAll(); - } - - private class AsyncOperationQueue - { - private bool _run = true; - private readonly Queue _operations = Queue.Synchronized(new Queue()); - private readonly AutoResetEvent _operationsAvailable = new AutoResetEvent(false); - - public void Enqueue(AsyncOperation asyncOperation) - { - _operations.Enqueue(asyncOperation); - _operationsAvailable.Set(); - } - - public void MarkAsComplete() - { - _run = false; - _operationsAvailable.Set(); - } - - public void InvokeAll() - { - while (_run) - { - InvokePendingOperations(); - _operationsAvailable.WaitOne(); - } - - InvokePendingOperations(); - } - - private void InvokePendingOperations() - { - while (_operations.Count > 0) - { - AsyncOperation operation = (AsyncOperation)_operations.Dequeue(); - operation.Invoke(); - } - } - } - - private class AsyncOperation - { - private readonly SendOrPostCallback _action; - private readonly object _state; - - public AsyncOperation(SendOrPostCallback action, object state) - { - _action = action; - _state = state; - } - - public void Invoke() - { - _action(_state); - } - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/Builders/CombinatorialStrategy.cs b/test/NUnitLite/src/framework/Internal/Builders/CombinatorialStrategy.cs deleted file mode 100644 index 9f2bae179..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/CombinatorialStrategy.cs +++ /dev/null @@ -1,92 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// CombinatorialStrategy creates test cases by using all possible - /// combinations of the parameter data. - /// - public class CombinatorialStrategy : CombiningStrategy - { - /// - /// Initializes a new instance of the class. - /// - /// The sources. - public CombinatorialStrategy(IEnumerable[] sources) : base(sources) { } - - /// - /// Gets the test cases generated by the CombiningStrategy. - /// - /// The test cases. -#if CLR_2_0 || CLR_4_0 - public override IEnumerable GetTestCases() - { - List testCases = new List(); -#else - public override IEnumerable GetTestCases() - { - ArrayList testCases = new ArrayList(); -#endif - IEnumerator[] enumerators = new IEnumerator[Sources.Length]; - int index = -1; - - for (; ; ) - { - while (++index < Sources.Length) - { - enumerators[index] = Sources[index].GetEnumerator(); - if (!enumerators[index].MoveNext()) - return testCases; - } - - object[] testdata = new object[Sources.Length]; - - for (int i = 0; i < Sources.Length; i++) - testdata[i] = enumerators[i].Current; - - ParameterSet parms = new ParameterSet(); - parms.Arguments = testdata; - testCases.Add(parms); - - index = Sources.Length; - - while (--index >= 0 && !enumerators[index].MoveNext()) ; - - if (index < 0) break; - } - - return testCases; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/CombinatorialTestCaseProvider.cs b/test/NUnitLite/src/framework/Internal/Builders/CombinatorialTestCaseProvider.cs deleted file mode 100644 index 936692357..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/CombinatorialTestCaseProvider.cs +++ /dev/null @@ -1,108 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Collections; -using NUnit.Framework.Api; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// CombinatorialTestCaseProvider creates test cases from individual - /// parameter data values, combining them using the CombiningStrategy - /// indicated by an Attribute used on the test method. - /// - public class CombinatorialTestCaseProvider : ITestCaseProvider - { - #region Static Members - static IParameterDataProvider dataPointProvider = new ParameterDataProviders(); - - #endregion - - #region ITestCaseProvider Members - - /// - /// Determine whether any test cases are available for a parameterized method. - /// - /// A MethodInfo representing a parameterized test - /// - /// True if any cases are available, otherwise false. - /// - public bool HasTestCasesFor(System.Reflection.MethodInfo method) - { - if (method.GetParameters().Length == 0) - return false; - - foreach (ParameterInfo parameter in method.GetParameters()) - if (!dataPointProvider.HasDataFor(parameter)) - return false; - - return true; - } - - /// - /// Return an IEnumerable providing test cases for use in - /// running a paramterized test. - /// - /// - /// -#if CLR_2_0 || CLR_4_0 - public System.Collections.Generic.IEnumerable GetTestCasesFor(MethodInfo method) -#else - public IEnumerable GetTestCasesFor(MethodInfo method) -#endif - { - return GetStrategy(method).GetTestCases(); - } - #endregion - - #region GetStrategy - - /// - /// Gets the strategy to be used in building test cases for this test. - /// - /// The method for which test cases are being built. - /// - private CombiningStrategy GetStrategy(MethodInfo method) - { - ParameterInfo[] parameters = method.GetParameters(); - IEnumerable[] sources = new IEnumerable[parameters.Length]; - for (int i = 0; i < parameters.Length; i++) - sources[i] = dataPointProvider.GetDataFor(parameters[i]); - - if (method.IsDefined(typeof(NUnit.Framework.SequentialAttribute), false)) - return new SequentialStrategy(sources); - - if (method.IsDefined(typeof(NUnit.Framework.PairwiseAttribute), false) && - method.GetParameters().Length > 2) - return new PairwiseStrategy(sources); - - return new CombinatorialStrategy(sources); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/CombiningStrategy.cs b/test/NUnitLite/src/framework/Internal/Builders/CombiningStrategy.cs deleted file mode 100644 index 7dcdac058..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/CombiningStrategy.cs +++ /dev/null @@ -1,91 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using NUnit.Framework.Internal; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Builders -{ - /// - /// CombiningStrategy is the abstract base for classes that - /// know how to combine values provided for individual test - /// parameters to create a set of test cases. - /// - public abstract class CombiningStrategy - { - private IEnumerable[] sources; - private IEnumerator[] enumerators; - - /// - /// Initializes a new instance of the - /// class using a set of parameter sources. - /// - /// The sources. - public CombiningStrategy(IEnumerable[] sources) - { - this.sources = sources; - } - - /// - /// Gets the sources used by this strategy. - /// - /// The sources. - public IEnumerable[] Sources - { - get { return sources; } - } - - /// - /// Gets the enumerators for the sources. - /// - /// The enumerators. - public IEnumerator[] Enumerators - { - get - { - if (enumerators == null) - { - enumerators = new IEnumerator[Sources.Length]; - for (int i = 0; i < Sources.Length; i++) - enumerators[i] = Sources[i].GetEnumerator(); - } - - return enumerators; - } - } - - /// - /// Gets the test cases generated by the CombiningStrategy. - /// - /// The test cases. -#if CLR_2_0 || CLR_4_0 - public abstract System.Collections.Generic.IEnumerable GetTestCases(); -#else - public abstract System.Collections.IEnumerable GetTestCases(); -#endif - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/DataAttributeTestCaseProvider.cs b/test/NUnitLite/src/framework/Internal/Builders/DataAttributeTestCaseProvider.cs deleted file mode 100644 index 3632dd30a..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/DataAttributeTestCaseProvider.cs +++ /dev/null @@ -1,90 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// DataAttributeTestCaseProvider provides data for methods - /// annotated with any DataAttribute. For correct operation, - /// any new or custom Attributes must implement one of the - /// following interfaces: - /// ITestCaseData - /// ITestCaseSource - /// - public class DataAttributeTestCaseProvider : ITestCaseProvider - { - #region ITestCaseProvider Members - - /// - /// Determine whether any test cases are available for a parameterized method. - /// - /// A MethodInfo representing a parameterized test - /// True if any cases are available, otherwise false. - public bool HasTestCasesFor(MethodInfo method) - { - return method.IsDefined(typeof(DataAttribute), false); - } - - /// - /// Return an IEnumerable providing test cases for use in - /// running a parameterized test. - /// - /// - /// -#if CLR_2_0 || CLR_4_0 - public IEnumerable GetTestCasesFor(MethodInfo method) - { - List testCases = new List(); -#else - public IEnumerable GetTestCasesFor(MethodInfo method) - { - ArrayList testCases = new ArrayList(); -#endif - - foreach (DataAttribute attr in method.GetCustomAttributes(typeof(DataAttribute), false)) - { - ITestCaseSource source = attr as ITestCaseSource; - if (source != null) - { - // TODO: Create a class to handle exceptions for NUnitLite - foreach (ITestCaseData testCase in ((ITestCaseSource)attr).GetTestCasesFor(method)) - testCases.Add(testCase); - continue; - } - } - - return testCases; - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/DatapointProvider.cs b/test/NUnitLite/src/framework/Internal/Builders/DatapointProvider.cs deleted file mode 100644 index d4712917b..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/DatapointProvider.cs +++ /dev/null @@ -1,186 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Collections; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// Provides data from fields marked with the DatapointAttribute or the - /// DatapointsAttribute. - /// - public class DatapointProvider : IParameterDataProvider - { - #region IDataPointProvider Members - - /// - /// Determine whether any data is available for a parameter. - /// - /// A ParameterInfo representing one - /// argument to a parameterized test - /// - /// True if any data is available, otherwise false. - /// - public bool HasDataFor(System.Reflection.ParameterInfo parameter) - { - Type parameterType = parameter.ParameterType; - MemberInfo method = parameter.Member; - Type fixtureType = method.ReflectedType; - - if (!method.IsDefined(typeof(TheoryAttribute), true)) - return false; - - if (parameterType == typeof(bool) || parameterType.IsEnum) - return true; - - foreach (MemberInfo member in fixtureType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) - { - if (member.IsDefined(typeof(DatapointAttribute), true) && - GetTypeFromMemberInfo(member) == parameterType) - return true; - else if (member.IsDefined(typeof(DatapointSourceAttribute), true) && - GetElementTypeFromMemberInfo(member) == parameterType) - return true; - } - - return false; - } - - /// - /// Return an IEnumerable providing data for use with the - /// supplied parameter. - /// - /// A ParameterInfo representing one - /// argument to a parameterized test - /// - /// An IEnumerable providing the required data - /// - public System.Collections.IEnumerable GetDataFor(System.Reflection.ParameterInfo parameter) - { - ObjectList datapoints = new ObjectList(); - - Type parameterType = parameter.ParameterType; - Type fixtureType = parameter.Member.ReflectedType; - - foreach (MemberInfo member in fixtureType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) - { - if (member.IsDefined(typeof(DatapointAttribute), true)) - { - if (GetTypeFromMemberInfo(member) == parameterType && - member.MemberType == MemberTypes.Field) - { - FieldInfo field = member as FieldInfo; - if (field.IsStatic) - datapoints.Add(field.GetValue(null)); - else - datapoints.Add(field.GetValue(ProviderCache.GetInstanceOf(fixtureType))); - } - } - else if (member.IsDefined(typeof(DatapointSourceAttribute), true)) - { - if (GetElementTypeFromMemberInfo(member) == parameterType) - { - object instance; - - switch(member.MemberType) - { - case MemberTypes.Field: - FieldInfo field = member as FieldInfo; - instance = field.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); - foreach (object data in (IEnumerable)field.GetValue(instance)) - datapoints.Add(data); - break; - case MemberTypes.Property: - PropertyInfo property = member as PropertyInfo; - MethodInfo getMethod = property.GetGetMethod(true); - instance = getMethod.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); - foreach (object data in (IEnumerable)property.GetValue(instance,null)) - datapoints.Add(data); - break; - case MemberTypes.Method: - MethodInfo method = member as MethodInfo; - instance = method.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); - foreach (object data in (IEnumerable)method.Invoke(instance, new Type[0])) - datapoints.Add(data); - break; - } - } - } - } - - if (datapoints.Count == 0) - { - if (parameterType == typeof(bool)) - { - datapoints.Add(true); - datapoints.Add(false); - } - else if (parameterType.IsEnum) - { - datapoints.AddRange(TypeHelper.GetEnumValues(parameterType)); - } - } - - return datapoints; - } - - private Type GetTypeFromMemberInfo(MemberInfo member) - { - switch (member.MemberType) - { - case MemberTypes.Field: - return ((FieldInfo)member).FieldType; - case MemberTypes.Property: - return ((PropertyInfo)member).PropertyType; - case MemberTypes.Method: - return ((MethodInfo)member).ReturnType; - default: - return null; - } - } - - private Type GetElementTypeFromMemberInfo(MemberInfo member) - { - Type type = GetTypeFromMemberInfo(member); - - if (type == null) - return null; - - if (type.IsArray) - return type.GetElementType(); - -#if CLR_2_0 || CLR_4_0 - if (type.IsGenericType && type.Name == "IEnumerable`1") - return type.GetGenericArguments()[0]; -#endif - - return null; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/NUnitTestCaseBuilder.cs b/test/NUnitLite/src/framework/Internal/Builders/NUnitTestCaseBuilder.cs deleted file mode 100644 index b2be4174e..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/NUnitTestCaseBuilder.cs +++ /dev/null @@ -1,408 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008-2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal.Commands; - -#if NET_4_5 -using System.Threading.Tasks; -#endif - -namespace NUnit.Framework.Builders -{ - /// - /// Class to build ether a parameterized or a normal NUnitTestMethod. - /// There are four cases that the builder must deal with: - /// 1. The method needs no params and none are provided - /// 2. The method needs params and they are provided - /// 3. The method needs no params but they are provided in error - /// 4. The method needs params but they are not provided - /// This could have been done using two different builders, but it - /// turned out to be simpler to have just one. The BuildFrom method - /// takes a different branch depending on whether any parameters are - /// provided, but all four cases are dealt with in lower-level methods - /// - public class NUnitTestCaseBuilder : ITestCaseBuilder2 - { - private Randomizer randomizer; - - private ITestCaseProvider testCaseProvider = new TestCaseProviders(); - - /// - /// Default no argument constructor for NUnitTestCaseBuilder - /// - public NUnitTestCaseBuilder() - { - randomizer = Randomizer.CreateRandomizer(); - } - - #region ITestCaseBuilder Methods - /// - /// Determines if the method can be used to build an NUnit test - /// test method of some kind. The method must normally be marked - /// with an identifying attriute for this to be true. - /// - /// Note that this method does not check that the signature - /// of the method for validity. If we did that here, any - /// test methods with invalid signatures would be passed - /// over in silence in the test run. Since we want such - /// methods to be reported, the check for validity is made - /// in BuildFrom rather than here. - /// - /// A MethodInfo for the method being used as a test method - /// True if the builder can create a test case from this method - public bool CanBuildFrom(MethodInfo method) - { - return method.IsDefined(typeof(TestAttribute), false) - || method.IsDefined(typeof(ITestCaseSource), false) - || method.IsDefined(typeof(TheoryAttribute), false); - } - - /// - /// Build a Test from the provided MethodInfo. Depending on - /// whether the method takes arguments and on the availability - /// of test case data, this method may return a single test - /// or a group of tests contained in a ParameterizedMethodSuite. - /// - /// The MethodInfo for which a test is to be built - /// A Test representing one or more method invocations - public Test BuildFrom(MethodInfo method) - { - return BuildFrom(method, null); - } - - #endregion - - #region ITestCaseBuilder2 Members - - /// - /// Determines if the method can be used to build an NUnit test - /// test method of some kind. The method must normally be marked - /// with an identifying attriute for this to be true. - /// - /// Note that this method does not check that the signature - /// of the method for validity. If we did that here, any - /// test methods with invalid signatures would be passed - /// over in silence in the test run. Since we want such - /// methods to be reported, the check for validity is made - /// in BuildFrom rather than here. - /// - /// A MethodInfo for the method being used as a test method - /// The test suite being built, to which the new test would be added - /// True if the builder can create a test case from this method - public bool CanBuildFrom(MethodInfo method, Test parentSuite) - { - return CanBuildFrom(method); - } - - /// - /// Build a Test from the provided MethodInfo. Depending on - /// whether the method takes arguments and on the availability - /// of test case data, this method may return a single test - /// or a group of tests contained in a ParameterizedMethodSuite. - /// - /// The MethodInfo for which a test is to be built - /// The test fixture being populated, or null - /// A Test representing one or more method invocations - public Test BuildFrom(MethodInfo method, Test parentSuite) - { - return testCaseProvider.HasTestCasesFor(method) - ? BuildParameterizedMethodSuite(method, parentSuite) - : BuildSingleTestMethod(method, parentSuite, null); - } - - #endregion - - #region Implementation - - /// - /// Builds a ParameterizedMetodSuite containing individual - /// test cases for each set of parameters provided for - /// this method. - /// - /// The MethodInfo for which a test is to be built - /// The test suite for which the method is being built - /// A ParameterizedMethodSuite populated with test cases - public Test BuildParameterizedMethodSuite(MethodInfo method, Test parentSuite) - { - ParameterizedMethodSuite methodSuite = new ParameterizedMethodSuite(method); - methodSuite.ApplyAttributesToTest(method); - - foreach (ITestCaseData testcase in testCaseProvider.GetTestCasesFor(method)) - { - ParameterSet parms = testcase as ParameterSet; - if (parms == null) - parms = new ParameterSet(testcase); - - TestMethod test = BuildSingleTestMethod(method, parentSuite, parms); - - methodSuite.Add(test); - } - - return methodSuite; - } - - /// - /// Builds a single NUnitTestMethod, either as a child of the fixture - /// or as one of a set of test cases under a ParameterizedTestMethodSuite. - /// - /// The MethodInfo from which to construct the TestMethod - /// The suite or fixture to which the new test will be added - /// The ParameterSet to be used, or null - /// - private TestMethod BuildSingleTestMethod(MethodInfo method, Test parentSuite, ParameterSet parms) - { - TestMethod testMethod = new TestMethod(method, parentSuite); - - testMethod.Seed = randomizer.Next(); - - string prefix = method.ReflectedType.FullName; - - // Needed to give proper fullname to test in a parameterized fixture. - // Without this, the arguments to the fixture are not included. - if (parentSuite != null) - { - prefix = parentSuite.FullName; - //testMethod.FullName = prefix + "." + testMethod.Name; - } - - if (CheckTestMethodSignature(testMethod, parms)) - { - if (parms == null) - testMethod.ApplyAttributesToTest(method); - - foreach (ICommandDecorator decorator in method.GetCustomAttributes(typeof(ICommandDecorator), true)) - testMethod.CustomDecorators.Add(decorator); - - ExpectedExceptionAttribute[] attributes = - (ExpectedExceptionAttribute[])method.GetCustomAttributes(typeof(ExpectedExceptionAttribute), false); - - if (attributes.Length > 0) - { - ExpectedExceptionAttribute attr = attributes[0]; - string handlerName = attr.Handler; - if (handlerName != null && GetExceptionHandler(testMethod.FixtureType, handlerName) == null) - MarkAsNotRunnable( - testMethod, - string.Format("The specified exception handler {0} was not found", handlerName)); - - testMethod.CustomDecorators.Add(new ExpectedExceptionDecorator(attr.ExceptionData)); - } - } - - if (parms != null) - { - // NOTE: After the call to CheckTestMethodSignature, the Method - // property of testMethod may no longer be the same as the - // original MethodInfo, so we reassign it here. - method = testMethod.Method; - - if (parms.TestName != null) - { - testMethod.Name = parms.TestName; - testMethod.FullName = prefix + "." + parms.TestName; - } - else if (parms.OriginalArguments != null) - { - string name = MethodHelper.GetDisplayName(method, parms.OriginalArguments); - testMethod.Name = name; - testMethod.FullName = prefix + "." + name; - } - - parms.ApplyToTest(testMethod); - } - - return testMethod; - } - - #endregion - - #region Helper Methods - - /// - /// Helper method that checks the signature of a TestMethod and - /// any supplied parameters to determine if the test is valid. - /// - /// Currently, NUnitTestMethods are required to be public, - /// non-abstract methods, either static or instance, - /// returning void. They may take arguments but the values must - /// be provided or the TestMethod is not considered runnable. - /// - /// Methods not meeting these criteria will be marked as - /// non-runnable and the method will return false in that case. - /// - /// The TestMethod to be checked. If it - /// is found to be non-runnable, it will be modified. - /// Parameters to be used for this test, or null - /// True if the method signature is valid, false if not - private static bool CheckTestMethodSignature(TestMethod testMethod, ParameterSet parms) - { - if (testMethod.Method.IsAbstract) - { - return MarkAsNotRunnable(testMethod, "Method is abstract"); - } - - if (!testMethod.Method.IsPublic) - { - return MarkAsNotRunnable(testMethod, "Method is not public"); - } - -#if NETCF - // TODO: Get this to work - if (testMethod.Method.IsGenericMethodDefinition) - { - return MarkAsNotRunnable(testMethod, "Generic test methods are not yet supported under .NET CF"); - } -#endif - - ParameterInfo[] parameters = testMethod.Method.GetParameters(); - int argsNeeded = parameters.Length; - - object[] arglist = null; - int argsProvided = 0; - - if (parms != null) - { - testMethod.parms = parms; - testMethod.RunState = parms.RunState; - - arglist = parms.Arguments; - - if (arglist != null) - argsProvided = arglist.Length; - - if (testMethod.RunState != RunState.Runnable) - return false; - } - - Type returnType = testMethod.Method.ReturnType; - if (returnType.Equals(typeof(void))) - { - if (parms != null && parms.HasExpectedResult) - return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); - } - else - { -#if NET_4_5 - if (MethodHelper.IsAsyncMethod(testMethod.Method)) - { - bool returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>); - if (returnsGenericTask && (parms == null|| !parms.HasExpectedResult && !parms.ExceptionExpected)) - return MarkAsNotRunnable(testMethod, "Async test method must have Task or void return type when no result is expected"); - else if (!returnsGenericTask && parms != null && parms.HasExpectedResult) - return MarkAsNotRunnable(testMethod, "Async test method must have Task return type when a result is expected"); - } - else -#endif - if (parms == null || !parms.HasExpectedResult && !parms.ExceptionExpected) - return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected"); - } - - if (argsProvided > 0 && argsNeeded == 0) - { - return MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any"); - } - - if (argsProvided == 0 && argsNeeded > 0) - { - return MarkAsNotRunnable(testMethod, "No arguments were provided"); - } - - if (argsProvided != argsNeeded) - { - return MarkAsNotRunnable(testMethod, "Wrong number of arguments provided"); - } - -#if CLR_2_0 || CLR_4_0 -#if !NETCF - if (testMethod.Method.IsGenericMethodDefinition) - { - Type[] typeArguments = GetTypeArgumentsForMethod(testMethod.Method, arglist); - foreach (object o in typeArguments) - if (o == null) - { - return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method"); - } - - testMethod.method = testMethod.Method.MakeGenericMethod(typeArguments); - parameters = testMethod.Method.GetParameters(); - } -#endif -#endif - - if (arglist != null && parameters != null) - TypeHelper.ConvertArgumentList(arglist, parameters); - - return true; - } - -#if CLR_2_0 || CLR_4_0 -#if !NETCF - private static Type[] GetTypeArgumentsForMethod(MethodInfo method, object[] arglist) - { - Type[] typeParameters = method.GetGenericArguments(); - Type[] typeArguments = new Type[typeParameters.Length]; - ParameterInfo[] parameters = method.GetParameters(); - - for (int typeIndex = 0; typeIndex < typeArguments.Length; typeIndex++) - { - Type typeParameter = typeParameters[typeIndex]; - - for (int argIndex = 0; argIndex < parameters.Length; argIndex++) - { - if (parameters[argIndex].ParameterType.Equals(typeParameter)) - typeArguments[typeIndex] = TypeHelper.BestCommonType( - typeArguments[typeIndex], - arglist[argIndex].GetType()); - } - } - - return typeArguments; - } -#endif -#endif - - private static MethodInfo GetExceptionHandler(Type fixtureType, string name) - { - return fixtureType.GetMethod( - name, - BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - null, - new Type[] { typeof(System.Exception) }, - null); - } - - private static bool MarkAsNotRunnable(TestMethod testMethod, string reason) - { - testMethod.RunState = RunState.NotRunnable; - testMethod.Properties.Set(PropertyNames.SkipReason, reason); - return false; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/NUnitTestFixtureBuilder.cs b/test/NUnitLite/src/framework/Internal/Builders/NUnitTestFixtureBuilder.cs deleted file mode 100644 index b890a4d62..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/NUnitTestFixtureBuilder.cs +++ /dev/null @@ -1,349 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Text; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.Framework.Extensibility; - -namespace NUnit.Framework.Builders -{ - /// - /// Built-in SuiteBuilder for NUnit TestFixture - /// - public class NUnitTestFixtureBuilder : ISuiteBuilder - { - #region Static Fields - - static readonly string NO_TYPE_ARGS_MSG = - "Fixture type contains generic parameters. You must either provide " + - "Type arguments or specify constructor arguments that allow NUnit " + - "to deduce the Type arguments."; - - #endregion - - #region Instance Fields - /// - /// The NUnitTestFixture being constructed; - /// - private TestFixture fixture; - - private Extensibility.ITestCaseBuilder2 testBuilder; - - #endregion - - #region Constructor - - public NUnitTestFixtureBuilder() - { - testBuilder = new NUnitTestCaseBuilder(); - } - - #endregion - - #region ISuiteBuilder Methods - /// - /// Checks to see if the fixture type has the TestFixtureAttribute - /// - /// The fixture type to check - /// True if the fixture can be built, false if not - public bool CanBuildFrom(Type type) - { - if ( type.IsAbstract && !type.IsSealed ) - return false; - - if (type.IsDefined(typeof(TestFixtureAttribute), true)) - return true; - -#if CLR_2_0 || CLR_4_0 - // Generics must have a TestFixtureAttribute - if (type.IsGenericTypeDefinition) - return false; -#endif - - return Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestAttribute)) || - Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestCaseAttribute)) || - Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestCaseSourceAttribute)) || - Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TheoryAttribute)); - } - - /// - /// Build a TestSuite from type provided. - /// - /// - /// - public Test BuildFrom(Type type) - { - TestFixtureAttribute[] attrs = GetTestFixtureAttributes(type); - -#if CLR_2_0 || CLR_4_0 - if (type.IsGenericType) - return BuildMultipleFixtures(type, attrs); -#endif - - switch (attrs.Length) - { - case 0: - return BuildSingleFixture(type, null); - case 1: - object[] args = (object[])attrs[0].Arguments; - return args == null || args.Length == 0 - ? BuildSingleFixture(type, attrs[0]) - : BuildMultipleFixtures(type, attrs); - default: - return BuildMultipleFixtures(type, attrs); - } - } - #endregion - - #region Helper Methods - - private Test BuildMultipleFixtures(Type type, TestFixtureAttribute[] attrs) - { - TestSuite suite = new ParameterizedFixtureSuite(type); - - if (attrs.Length > 0) - { - foreach (TestFixtureAttribute attr in attrs) - suite.Add(BuildSingleFixture(type, attr)); - } - else - { - suite.RunState = RunState.NotRunnable; - suite.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG); - } - - return suite; - } - - private Test BuildSingleFixture(Type type, TestFixtureAttribute attr) - { - object[] arguments = null; - - if (attr != null) - { - arguments = (object[])attr.Arguments; - -#if CLR_2_0 || CLR_4_0 - if (type.ContainsGenericParameters) - { - Type[] typeArgs = (Type[])attr.TypeArgs; - if( typeArgs.Length > 0 || - TypeHelper.CanDeduceTypeArgsFromArgs(type, arguments, ref typeArgs)) - { - type = TypeHelper.MakeGenericType(type, typeArgs); - } - } -#endif - } - - this.fixture = new TestFixture(type, arguments); - CheckTestFixtureIsValid(fixture); - - fixture.ApplyAttributesToTest(type); - - if (fixture.RunState == RunState.Runnable && attr != null) - { - if (attr.Ignore) - { - fixture.RunState = RunState.Ignored; - fixture.Properties.Set(PropertyNames.SkipReason, attr.IgnoreReason); - } - } - - AddTestCases(type); - - return this.fixture; - } - - /// - /// Method to add test cases to the newly constructed fixture. - /// - /// - private void AddTestCases( Type fixtureType ) - { - IList methods = fixtureType.GetMethods( - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static ); - - foreach(MethodInfo method in methods) - { - Test test = BuildTestCase(method, this.fixture); - - if(test != null) - { - this.fixture.Add( test ); - } - } - } - - /// - /// Method to create a test case from a MethodInfo and add - /// it to the fixture being built. It first checks to see if - /// any global TestCaseBuilder addin wants to build the - /// test case. If not, it uses the internal builder - /// collection maintained by this fixture builder. After - /// building the test case, it applies any decorators - /// that have been installed. - /// - /// The default implementation has no test case builders. - /// Derived classes should add builders to the collection - /// in their constructor. - /// - /// The MethodInfo for which a test is to be created - /// The test suite being built. - /// A newly constructed Test - private Test BuildTestCase( MethodInfo method, TestSuite suite ) - { - return testBuilder.CanBuildFrom(method, suite) - ? testBuilder.BuildFrom(method, suite) - : null; - } - - private void CheckTestFixtureIsValid(TestFixture fixture) - { - Type fixtureType = fixture.FixtureType; - -#if CLR_2_0 || CLR_4_0 - if (fixtureType.ContainsGenericParameters) - { - SetNotRunnable(fixture, NO_TYPE_ARGS_MSG); - return; - } -#endif - if( !IsStaticClass(fixtureType) && !HasValidConstructor(fixtureType, fixture.arguments) ) - { - SetNotRunnable(fixture, "No suitable constructor was found"); - return; - } - - if (!CheckSetUpTearDownMethods(fixture, fixture.SetUpMethods)) - return; - if (!CheckSetUpTearDownMethods(fixture, fixture.TearDownMethods)) - return; - if (!CheckSetUpTearDownMethods(fixture, Reflect.GetMethodsWithAttribute(fixture.FixtureType, typeof(TestFixtureSetUpAttribute), true))) - return; - CheckSetUpTearDownMethods(fixture, Reflect.GetMethodsWithAttribute(fixture.FixtureType, typeof(TestFixtureTearDownAttribute), true)); - } - - private static bool HasValidConstructor(Type fixtureType, object[] args) - { - Type[] argTypes; - - // Note: This could be done more simply using - // Type.EmptyTypes and Type.GetTypeArray() but - // they don't exist in all runtimes we support. - if (args == null) - argTypes = new Type[0]; - else - { - argTypes = new Type[args.Length]; - - int index = 0; - foreach (object arg in args) - argTypes[index++] = arg.GetType(); - } - - return fixtureType.GetConstructor(argTypes) != null; - } - - private void SetNotRunnable(TestFixture fixture, string reason) - { - fixture.RunState = RunState.NotRunnable; - fixture.Properties.Set(PropertyNames.SkipReason, reason); - } - - private static bool IsStaticClass(Type type) - { - return type.IsAbstract && type.IsSealed; - } - - private bool CheckSetUpTearDownMethods(TestFixture fixture, MethodInfo[] methods) - { - foreach (MethodInfo method in methods) - if (method.IsAbstract || - !method.IsPublic && !method.IsFamily || - method.GetParameters().Length > 0 || - !method.ReturnType.Equals(typeof(void))) - { - SetNotRunnable(fixture, string.Format("Invalid signature for Setup or TearDown method: {0}", method.Name)); - return false; - } - - return true; - } - - /// - /// Get TestFixtureAttributes following a somewhat obscure - /// set of rules to eliminate spurious duplication of fixtures. - /// 1. If there are any attributes with args, they are the only - /// ones returned and those without args are ignored. - /// 2. No more than one attribute without args is ever returned. - /// - private TestFixtureAttribute[] GetTestFixtureAttributes(Type type) - { - TestFixtureAttribute[] attrs = - (TestFixtureAttribute[])type.GetCustomAttributes(typeof(TestFixtureAttribute), true); - - // Just return - no possibility of duplication - if (attrs.Length <= 1) - return attrs; - - int withArgs = 0; - bool[] hasArgs = new bool[attrs.Length]; - - // Count and record those attrs with arguments - for (int i = 0; i < attrs.Length; i++) - { - TestFixtureAttribute attr = attrs[i]; - - if (attr.Arguments.Length > 0 || attr.TypeArgs.Length > 0) - { - withArgs++; - hasArgs[i] = true; - } - } - - // If all attributes have args, just return them - if (withArgs == attrs.Length) - return attrs; - - // If all attributes are without args, just return the first found - if (withArgs == 0) - return new TestFixtureAttribute[] { attrs[0] }; - - // Some of each type, so extract those with args - int count = 0; - TestFixtureAttribute[] result = new TestFixtureAttribute[withArgs]; - for (int i = 0; i < attrs.Length; i++) - if (hasArgs[i]) - result[count++] = attrs[i]; - - return result; - } - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/Builders/PairwiseStrategy.cs b/test/NUnitLite/src/framework/Internal/Builders/PairwiseStrategy.cs deleted file mode 100644 index 19f79a708..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/PairwiseStrategy.cs +++ /dev/null @@ -1,754 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using System.Text; -using NUnit.Framework.Api; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// PairwiseStrategy creates test cases by combining the parameter - /// data so that all possible pairs of data items are used. - /// - public class PairwiseStrategy : CombiningStrategy - { - internal class FleaRand - { - private const int FleaRandSize = 256; - - private uint b; - private uint c; - private uint d; - private uint z; - - private uint[] m = new uint[FleaRandSize]; - private uint[] r = new uint[FleaRandSize]; - - private uint q; - - /// - /// Initializes a new instance of the class. - /// - /// The seed. - public FleaRand(uint seed) - { - this.b = seed; - this.c = seed; - this.d = seed; - this.z = seed; - - for (int i = 0; i < this.m.Length; i++) - { - this.m[i] = seed; - } - - for (int i = 0; i < 10; i++) - { - this.Batch(); - } - - this.q = 0; - } - - public uint Next() - { - if (this.q == 0) - { - this.Batch(); - this.q = (uint)this.r.Length - 1; - } - else - { - this.q--; - } - - return this.r[this.q]; - } - - private void Batch() - { - uint a; - uint b = this.b; - uint c = this.c + (++this.z); - uint d = this.d; - - for (int i = 0; i < this.r.Length; i++) - { - a = this.m[b % this.m.Length]; - this.m[b % this.m.Length] = d; - d = (c << 19) + (c >> 13) + b; - c = b ^ this.m[i]; - b = a + d; - this.r[i] = c; - } - - this.b = b; - this.c = c; - this.d = d; - } - } - - internal class FeatureInfo - { - public const string Names = "abcdefghijklmnopqrstuvwxyz"; - - public readonly int Dimension; - public readonly int Feature; - - public FeatureInfo(int dimension, int feature) - { - this.Dimension = dimension; - this.Feature = feature; - } - -#if DEBUG - public override string ToString() - { - return (this.Dimension + 1).ToString() + FeatureInfo.Names[this.Feature]; - } -#endif - } - - internal class Tuple - { -#if CLR_2_0 || CLR_4_0 - private readonly List features = new List(); -#else - private readonly ArrayList features = new ArrayList(); -#endif - - public int Count - { - get - { - return this.features.Count; - } - } - - public FeatureInfo this[int index] - { - get - { - return (FeatureInfo)this.features[index]; - } - } - - public void Add(FeatureInfo feature) - { - this.features.Add(feature); - } - -#if DEBUG - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.Append('('); - - for (int i = 0; i < this.features.Count; i++) - { - if (i > 0) - { - sb.Append(' '); - } - - sb.Append(this.features[i].ToString()); - } - - sb.Append(')'); - - return sb.ToString(); - } -#endif - } - - internal class TupleCollection - { -#if CLR_2_0 || CLR_4_0 - private readonly List tuples = new List(); -#else - private readonly ArrayList tuples = new ArrayList(); -#endif - - public int Count - { - get - { - return this.tuples.Count; - } - } - - public Tuple this[int index] - { - get - { - return (Tuple)this.tuples[index]; - } - } - - public void Add(Tuple tuple) - { - this.tuples.Add(tuple); - } - - public void RemoveAt(int index) - { - this.tuples.RemoveAt(index); - } - } - - internal class TestCase - { - public readonly int[] Features; - - public TestCase(int numberOfDimensions) - { - this.Features = new int[numberOfDimensions]; - } - - public bool IsTupleCovered(Tuple tuple) - { - for (int i = 0; i < tuple.Count; i++) - { - if (this.Features[tuple[i].Dimension] != tuple[i].Feature) - { - return false; - } - } - - return true; - } - -#if DEBUG - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < this.Features.Length; i++) - { - if (i > 0) - { - sb.Append(' '); - } - - sb.Append(i + 1); - sb.Append(FeatureInfo.Names[this.Features[i]]); - } - - return sb.ToString(); - } -#endif - } - - internal class TestCaseCollection : IEnumerable - { -#if CLR_2_0 || CLR_4_0 - private readonly List testCases = new List(); -#else - private readonly ArrayList testCases = new ArrayList(); -#endif - - public void Add(TestCase testCase) - { - this.testCases.Add(testCase); - } - - public IEnumerator GetEnumerator() - { - return this.testCases.GetEnumerator(); - } - - public bool IsTupleCovered(Tuple tuple) - { - foreach (TestCase testCase in this.testCases) - { - if (testCase.IsTupleCovered(tuple)) - { - return true; - } - } - - return false; - } - } - - internal class PairwiseTestCaseGenerator - { - private const int MaxTupleLength = 2; - - private readonly FleaRand random = new FleaRand(0); - - private readonly int[] dimensions; - - private readonly TupleCollection[][] uncoveredTuples; - - private readonly int[][] currentTupleLength; - - private readonly TestCaseCollection testCases = new TestCaseCollection(); - - public PairwiseTestCaseGenerator(int[] dimensions) - { - this.dimensions = dimensions; - - this.uncoveredTuples = new TupleCollection[this.dimensions.Length][]; - - for (int d = 0; d < this.uncoveredTuples.Length; d++) - { - this.uncoveredTuples[d] = new TupleCollection[this.dimensions[d]]; - - for (int f = 0; f < this.dimensions[d]; f++) - { - this.uncoveredTuples[d][f] = new TupleCollection(); - } - } - - this.currentTupleLength = new int[this.dimensions.Length][]; - - for (int d = 0; d < this.dimensions.Length; d++) - { - this.currentTupleLength[d] = new int[this.dimensions[d]]; - } - } - - public IEnumerable GetTestCases() - { - this.CreateTestCases(); - - this.SelfTest(); - - return this.testCases; - } - - private void CreateTestCases() - { - while (true) - { - this.ExtendTupleSet(); - - Tuple tuple = this.FindTupleToCover(); - - if (tuple == null) - { - return; - } - - TestCase testCase = this.FindGoodTestCase(tuple); - - this.RemoveTuplesCoveredBy(testCase); - - this.testCases.Add(testCase); - } - } - - private void ExtendTupleSet() - { - for (int d = 0; d < this.dimensions.Length; d++) - { - for (int f = 0; f < this.dimensions[d]; f++) - { - this.ExtendTupleSet(d, f); - } - } - } - - private void ExtendTupleSet(int dimension, int feature) - { - // If tuples for [dimension][feature] already exists, it's no needs to add more tuples. - if (this.uncoveredTuples[dimension][feature].Count > 0) - { - return; - } - - // If maximum tuple length for [dimension][feature] is reached, it's no needs to add more tuples. - if (this.currentTupleLength[dimension][feature] == MaxTupleLength) - { - return; - } - - this.currentTupleLength[dimension][feature]++; - - int tupleLength = this.currentTupleLength[dimension][feature]; - - if (tupleLength == 1) - { - Tuple tuple = new Tuple(); - - tuple.Add(new FeatureInfo(dimension, feature)); - - if (this.testCases.IsTupleCovered(tuple)) - { - return; - } - - this.uncoveredTuples[dimension][feature].Add(tuple); - } - else - { - for (int d = 0; d < this.dimensions.Length; d++) - { - for (int f = 0; f < this.dimensions[d]; f++) - { - Tuple tuple = new Tuple(); - tuple.Add(new FeatureInfo(d, f)); - - if (tuple[0].Dimension == dimension) - { - continue; - } - - tuple.Add(new FeatureInfo(dimension, feature)); - - if (this.testCases.IsTupleCovered(tuple)) - { - continue; - } - - this.uncoveredTuples[dimension][feature].Add(tuple); - } - } - } - } - - private Tuple FindTupleToCover() - { - int tupleLength = MaxTupleLength; - int tupleCount = 0; - Tuple tuple = null; - - for (int d = 0; d < this.dimensions.Length; d++) - { - for (int f = 0; f < this.dimensions[d]; f++) - { - if (this.currentTupleLength[d][f] < tupleLength) - { - tupleLength = this.currentTupleLength[d][f]; - tupleCount = this.uncoveredTuples[d][f].Count; - tuple = this.uncoveredTuples[d][f][0]; - } - else - { - if (this.currentTupleLength[d][f] == tupleLength && this.uncoveredTuples[d][f].Count > tupleCount) - { - tupleCount = this.uncoveredTuples[d][f].Count; - tuple = this.uncoveredTuples[d][f][0]; - } - } - } - } - - return tuple; - } - - private TestCase FindGoodTestCase(Tuple tuple) - { - TestCase bestTest = null; - int bestCoverage = -1; - - for (int i = 0; i < 5; i++) - { - TestCase test = new TestCase(this.dimensions.Length); - - int coverage = this.CreateTestCase(tuple, test); - - if (coverage > bestCoverage) - { - bestTest = test; - bestCoverage = coverage; - } - } - - return bestTest; - } - - private int CreateTestCase(Tuple tuple, TestCase test) - { - // Create a random test case... - for (int i = 0; i < test.Features.Length; i++) - { - test.Features[i] = (int)(this.random.Next() % this.dimensions[i]); - } - - // ...and inject the tuple into it! - for (int i = 0; i < tuple.Count; i++) - { - test.Features[tuple[i].Dimension] = tuple[i].Feature; - } - - return this.MaximizeCoverage(test, tuple); - } - - private int MaximizeCoverage(TestCase test, Tuple tuple) - { - int[] dimensionOrder = this.GetMutableDimensions(tuple); - - while (true) - { - bool progress = false; - int totalCoverage = 1; - - // Scramble dimensions. - for (int i = dimensionOrder.Length; i > 1; i--) - { - int j = (int)(this.random.Next() % i); - int t = dimensionOrder[i - 1]; - dimensionOrder[i - 1] = dimensionOrder[j]; - dimensionOrder[j] = t; - } - - // For each dimension that can be modified... - for (int i = 0; i < dimensionOrder.Length; i++) - { - int d = dimensionOrder[i]; - -#if CLR_2_0 || CLR_4_0 - List bestFeatures = new List(); -#else - ArrayList bestFeatures = new ArrayList(); -#endif - - int bestCoverage = this.CountTuplesCovered(test, d, test.Features[d]); - - int bestTupleLength = this.currentTupleLength[d][test.Features[d]]; - - // For each feature that can be modified, check if it can extend coverage. - for (int f = 0; f < this.dimensions[d]; f++) - { - test.Features[d] = f; - - int coverage = this.CountTuplesCovered(test, d, f); - - if (this.currentTupleLength[d][f] < bestTupleLength) - { - progress = true; - bestTupleLength = this.currentTupleLength[d][f]; - bestCoverage = coverage; - bestFeatures.Clear(); - bestFeatures.Add(f); - } - else - { - if (this.currentTupleLength[d][f] == bestTupleLength && coverage >= bestCoverage) - { - if (coverage > bestCoverage) - { - progress = true; - bestCoverage = coverage; - bestFeatures.Clear(); - } - - bestFeatures.Add(f); - } - } - } - - if (bestFeatures.Count == 1) - { - test.Features[d] = (int)bestFeatures[0]; - } - else - { - test.Features[d] = (int)bestFeatures[(int)(this.random.Next() % bestFeatures.Count)]; - } - - totalCoverage += bestCoverage; - } - - if (!progress) - { - return totalCoverage; - } - } - } - - private int[] GetMutableDimensions(Tuple tuple) - { - bool[] immutableDimensions = new bool[this.dimensions.Length]; - - for (int i = 0; i < tuple.Count; i++) - { - immutableDimensions[tuple[i].Dimension] = true; - } - -#if CLR_2_0 || CLR_4_0 - List mutableDimensions = new List(); -#else - ArrayList mutableDimensions = new ArrayList(); -#endif - - for (int i = 0; i < this.dimensions.Length; i++) - { - if (!immutableDimensions[i]) - { - mutableDimensions.Add(i); - } - } - -#if CLR_2_0 || CLR_4_0 - return mutableDimensions.ToArray(); -#else - return (int[])mutableDimensions.ToArray(typeof(int)); -#endif - } - - private int CountTuplesCovered(TestCase test, int dimension, int feature) - { - int tuplesCovered = 0; - - TupleCollection tuples = this.uncoveredTuples[dimension][feature]; - - for (int i = 0; i < tuples.Count; i++) - { - if (test.IsTupleCovered(tuples[i])) - { - tuplesCovered++; - } - } - - return tuplesCovered; - } - - private void RemoveTuplesCoveredBy(TestCase testCase) - { - for (int d = 0; d < this.uncoveredTuples.Length; d++) - { - for (int f = 0; f < this.uncoveredTuples[d].Length; f++) - { - TupleCollection tuples = this.uncoveredTuples[d][f]; - - for (int i = tuples.Count - 1; i >= 0; i--) - { - if (testCase.IsTupleCovered(tuples[i])) - { - tuples.RemoveAt(i); - } - } - } - } - } - - private void SelfTest() - { - for (int d1 = 0; d1 < this.dimensions.Length - 1; d1++) - { - for (int d2 = d1 + 1; d2 < this.dimensions.Length; d2++) - { - for (int f1 = 0; f1 < this.dimensions[d1]; f1++) - { - for (int f2 = 0; f2 < this.dimensions[d2]; f2++) - { - Tuple tuple = new Tuple(); - tuple.Add(new FeatureInfo(d1, f1)); - tuple.Add(new FeatureInfo(d2, f2)); - - if (!this.testCases.IsTupleCovered(tuple)) - { - throw new Exception("PairwiseStrategy self-test failed : Not all pairs are covered!"); - } - } - } - } - } - } - } - - /// - /// Initializes a new instance of the class. - /// - /// The sources. - public PairwiseStrategy(IEnumerable[] sources) : base(sources) { } - - /// - /// Gets the test cases generated by this strategy instance. - /// - /// The test cases. -#if CLR_2_0 || CLR_4_0 - public override IEnumerable GetTestCases() - { - List testCases = new List(); -#else - public override IEnumerable GetTestCases() - { - ArrayList testCases = new ArrayList(); -#endif - ObjectList[] valueSet = CreateValueSet(); - int[] dimensions = CreateDimensions(valueSet); - - IEnumerable pairwiseTestCases = new PairwiseTestCaseGenerator(dimensions).GetTestCases(); - - foreach (TestCase pairwiseTestCase in pairwiseTestCases) - { - object[] testData = new object[pairwiseTestCase.Features.Length]; - - for (int i = 0; i < pairwiseTestCase.Features.Length; i++) - { - testData[i] = valueSet[i][pairwiseTestCase.Features[i]]; - } - - ParameterSet parms = new ParameterSet(); - parms.Arguments = testData; - testCases.Add(parms); - } - - return testCases; - } - - private ObjectList[] CreateValueSet() - { - ObjectList[] valueSet = new ObjectList[Sources.Length]; - - for (int i = 0; i < valueSet.Length; i++) - { - ObjectList values = new ObjectList(); - - foreach (object value in Sources[i]) - { - values.Add(value); - } - - valueSet[i] = values; - } - - return valueSet; - } - - private int[] CreateDimensions(ObjectList[] valueSet) - { - int[] dimensions = new int[valueSet.Length]; - - for (int i = 0; i < valueSet.Length; i++) - { - dimensions[i] = valueSet[i].Count; - } - - return dimensions; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/ParameterDataProvider.cs b/test/NUnitLite/src/framework/Internal/Builders/ParameterDataProvider.cs deleted file mode 100644 index 54d02f4a5..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/ParameterDataProvider.cs +++ /dev/null @@ -1,79 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Collections; -using NUnit.Framework.Api; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// ParameterDataProvider supplies individual argument values for - /// single parameters using attributes derived from DataAttribute. - /// - public class ParameterDataProvider : IParameterDataProvider - { - #region IDataPointProvider Members - - /// - /// Determine whether any data is available for a parameter. - /// - /// A ParameterInfo representing one - /// argument to a parameterized test - /// - /// True if any data is available, otherwise false. - /// - public bool HasDataFor(ParameterInfo parameter) - { - return parameter.IsDefined(typeof(DataAttribute), false); - } - - /// - /// Return an IEnumerable providing data for use with the - /// supplied parameter. - /// - /// A ParameterInfo representing one - /// argument to a parameterized test - /// - /// An IEnumerable providing the required data - /// - public IEnumerable GetDataFor(ParameterInfo parameter) - { - ObjectList data = new ObjectList(); - - foreach (Attribute attr in parameter.GetCustomAttributes(typeof(DataAttribute), false)) - { - IParameterDataSource source = attr as IParameterDataSource; - if (source != null) - foreach (object item in source.GetData(parameter)) - data.Add(item); - } - - return data; - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Builders/SequentialStrategy.cs b/test/NUnitLite/src/framework/Internal/Builders/SequentialStrategy.cs deleted file mode 100644 index 10db34ba6..000000000 --- a/test/NUnitLite/src/framework/Internal/Builders/SequentialStrategy.cs +++ /dev/null @@ -1,88 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Builders -{ - /// - /// SequentialStrategy creates test cases by using all of the - /// parameter data sources in parallel, substituting null - /// when any of them run out of data. - /// - public class SequentialStrategy : CombiningStrategy - { - /// - /// Initializes a new instance of the class. - /// - /// The sources. - public SequentialStrategy(IEnumerable[] sources) : base(sources) { } - - /// - /// Gets the test cases generated by the CombiningStrategy. - /// - /// The test cases. -#if CLR_2_0 || CLR_4_0 - public override IEnumerable GetTestCases() - { - List testCases = new List(); -#else - public override IEnumerable GetTestCases() - { - ArrayList testCases = new ArrayList(); -#endif - - for (; ; ) - { - bool gotData = false; - object[] testdata = new object[Sources.Length]; - - for (int i = 0; i < Sources.Length; i++) - if (Enumerators[i].MoveNext()) - { - testdata[i] = Enumerators[i].Current; - gotData = true; - } - else - testdata[i] = null; - - if (!gotData) - break; - - ParameterSet parms = new ParameterSet(); - parms.Arguments = testdata; - testCases.Add(parms); - } - - return testCases; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Commands/CommandDecoratorList.cs b/test/NUnitLite/src/framework/Internal/Commands/CommandDecoratorList.cs deleted file mode 100644 index 5b77b850e..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/CommandDecoratorList.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// CommandDecoratorList maintains a list of ICommandDecorators - /// and is able to sort them by level so that they are applied - /// in the proper order. - /// -#if CLR_2_0 || CLR_4_0 - public class CommandDecoratorList : System.Collections.Generic.List -#else - public class CommandDecoratorList : System.Collections.ArrayList -#endif - { - /// - /// Order command decorators by the stage at which they apply. - /// - public void OrderByStage() - { - Sort(CommandDecoratorComparison); - } - -#if CLR_2_0 || CLR_4_0 - private int CommandDecoratorComparison(ICommandDecorator x, ICommandDecorator y) - { - return x.Stage.CompareTo(y.Stage); - } -#else - private CommandDecoratorComparer CommandDecoratorComparison = new CommandDecoratorComparer(); - - private class CommandDecoratorComparer : System.Collections.IComparer - { - public int Compare(object x, object y) - { - ICommandDecorator xDecorator = x as ICommandDecorator; - ICommandDecorator yDecorator = y as ICommandDecorator; - - if (xDecorator == null || yDecorator == null) - return 0; - - return xDecorator.Stage.CompareTo(yDecorator.Stage); - } - } -#endif - } -} diff --git a/test/NUnitLite/src/framework/Internal/Commands/ExpectedExceptionCommand.cs b/test/NUnitLite/src/framework/Internal/Commands/ExpectedExceptionCommand.cs deleted file mode 100644 index e2d06fae6..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/ExpectedExceptionCommand.cs +++ /dev/null @@ -1,220 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// TODO: Documentation needed for class - /// - public class ExpectedExceptionCommand : DelegatingTestCommand - { - private ExpectedExceptionData exceptionData; - - /// - /// Initializes a new instance of the class. - /// - /// The inner command. - /// The exception data. - public ExpectedExceptionCommand(TestCommand innerCommand, ExpectedExceptionData exceptionData) - : base(innerCommand) - { - this.exceptionData = exceptionData; - } - - - /// - /// Runs the test, saving a TestResult in the supplied TestExecutionContext - /// - /// The context in which the test is to be run. - /// A TestResult - public override TestResult Execute(TestExecutionContext context) - { - try - { - context.CurrentResult = innerCommand.Execute(context); - - if (context.CurrentResult.ResultState == ResultState.Success) - ProcessNoException(context); - } - catch (Exception ex) - { -#if !NETCF && !SILVERLIGHT - if (ex is ThreadAbortException) - Thread.ResetAbort(); -#endif - ProcessException(ex, context); - } - - return context.CurrentResult; - } - - /// - /// Handles processing when no exception was thrown. - /// - /// The execution context. - public void ProcessNoException(TestExecutionContext context) - { - context.CurrentResult.SetResult(ResultState.Failure, NoExceptionMessage()); - } - - /// - /// Handles processing when an exception was thrown. - /// - /// The exception. - /// The execution context. - public void ProcessException(Exception exception, TestExecutionContext context) - { - if (exception is NUnitException) - exception = exception.InnerException; - - if (IsExpectedExceptionType(exception)) - { - if (IsExpectedMessageMatch(exception)) - { - if (context.TestObject != null) - { - MethodInfo exceptionMethod = exceptionData.GetExceptionHandler(context.TestObject.GetType()); - if (exceptionMethod != null) - { - Reflect.InvokeMethod(exceptionMethod, context.TestObject, exception); - } - else - { - IExpectException handler = context.TestObject as IExpectException; - if (handler != null) - handler.HandleException(exception); - } - } - - context.CurrentResult.SetResult(ResultState.Success); - } - else - { - context.CurrentResult.SetResult(ResultState.Failure, WrongTextMessage(exception), GetStackTrace(exception)); - } - } - else - { - context.CurrentResult.RecordException(exception); - - // If it shows as an error, change it to a failure due to the wrong type - if (context.CurrentResult.ResultState == ResultState.Error) - context.CurrentResult.SetResult(ResultState.Failure, WrongTypeMessage(exception), GetStackTrace(exception)); - } - } - - #region Helper Methods - - private bool IsExpectedExceptionType(Exception exception) - { - return exceptionData.ExpectedExceptionName == null || - exceptionData.ExpectedExceptionName.Equals(exception.GetType().FullName); - } - - private bool IsExpectedMessageMatch(Exception exception) - { - if (exceptionData.ExpectedMessage == null) - return true; - - switch (exceptionData.MatchType) - { - case MessageMatch.Exact: - default: - return exceptionData.ExpectedMessage.Equals(exception.Message); - case MessageMatch.Contains: - return exception.Message.IndexOf(exceptionData.ExpectedMessage) >= 0; - case MessageMatch.Regex: - return Regex.IsMatch(exception.Message, exceptionData.ExpectedMessage); - case MessageMatch.StartsWith: - return exception.Message.StartsWith(exceptionData.ExpectedMessage); - } - } - - private string NoExceptionMessage() - { - string expectedType = exceptionData.ExpectedExceptionName == null ? "An Exception" : exceptionData.ExpectedExceptionName; - return CombineWithUserMessage(expectedType + " was expected"); - } - - private string WrongTypeMessage(Exception exception) - { - return CombineWithUserMessage( - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: " + exceptionData.ExpectedExceptionName + Env.NewLine + - " but was: " + exception.GetType().FullName + " : " + exception.Message); - } - - private string WrongTextMessage(Exception exception) - { - string expectedText; - switch (exceptionData.MatchType) - { - default: - case MessageMatch.Exact: - expectedText = "Expected: "; - break; - case MessageMatch.Contains: - expectedText = "Expected message containing: "; - break; - case MessageMatch.Regex: - expectedText = "Expected message matching: "; - break; - case MessageMatch.StartsWith: - expectedText = "Expected message starting: "; - break; - } - - return CombineWithUserMessage( - "The exception message text was incorrect" + Env.NewLine + - expectedText + exceptionData.ExpectedMessage + Env.NewLine + - " but was: " + exception.Message); - } - - private string CombineWithUserMessage(string message) - { - if (exceptionData.UserMessage == null) - return message; - return exceptionData.UserMessage + Env.NewLine + message; - } - - private string GetStackTrace(Exception exception) - { - try - { - return exception.StackTrace; - } - catch (Exception) - { - return "No stack trace available"; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/Commands/ICommandDecorator.cs b/test/NUnitLite/src/framework/Internal/Commands/ICommandDecorator.cs deleted file mode 100644 index 68f769049..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/ICommandDecorator.cs +++ /dev/null @@ -1,54 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// ICommandDecorator is implemented by attributes and other - /// objects able to decorate a TestCommand, usually by wrapping - /// it with an outer command. - /// - public interface ICommandDecorator - { - /// - /// The stage of command execution to which this decorator applies. - /// - CommandStage Stage { get; } - - /// - /// The priority of this decorator as compared to other decorators - /// in the same Stage. Lower values are applied first. - /// - int Priority { get; } - - /// - /// Decorate a command, usually by wrapping it with another - /// command, and return the decorated command. - /// - /// The command to be decorated - /// The decorated command - TestCommand Decorate(TestCommand command); - } -} diff --git a/test/NUnitLite/src/framework/Internal/Commands/OneTimeSetUpCommand.cs b/test/NUnitLite/src/framework/Internal/Commands/OneTimeSetUpCommand.cs deleted file mode 100644 index 5f0112b22..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/OneTimeSetUpCommand.cs +++ /dev/null @@ -1,74 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// OneTimeSetUpCommand runs any one-time setup methods for a suite, - /// constructing the user test object if necessary. - /// - public class OneTimeSetUpCommand : TestCommand - { - private readonly TestSuite suite; - private readonly Type fixtureType; - private readonly object[] arguments; - - /// - /// Constructs a OneTimeSetUpComand for a suite - /// - /// The suite to which the command applies - public OneTimeSetUpCommand(TestSuite suite) : base(suite) - { - this.suite = suite; - this.fixtureType = suite.FixtureType; - this.arguments = suite.arguments; - } - - /// - /// Overridden to run the one-time setup for a suite. - /// - /// The TestExecutionContext to be used. - /// A TestResult - public override TestResult Execute(TestExecutionContext context) - { - if (fixtureType != null) - { - if (context.TestObject == null && !IsStaticClass(fixtureType)) - context.TestObject = Reflect.Construct(fixtureType, arguments); - - foreach (MethodInfo method in Reflect.GetMethodsWithAttribute(fixtureType, typeof(TestFixtureSetUpAttribute), true)) - Reflect.InvokeMethod(method, method.IsStatic ? null : context.TestObject); - } - - return context.CurrentResult; - } - - private static bool IsStaticClass(Type type) - { - return type.IsAbstract && type.IsSealed; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Commands/OneTimeTearDownCommand.cs b/test/NUnitLite/src/framework/Internal/Commands/OneTimeTearDownCommand.cs deleted file mode 100644 index 8ba497f1d..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/OneTimeTearDownCommand.cs +++ /dev/null @@ -1,106 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// OneTimeTearDownCommand performs any teardown actions - /// specified for a suite and calls Dispose on the user - /// test object, if any. - /// - public class OneTimeTearDownCommand : TestCommand - { - private readonly TestSuite suite; - private readonly Type fixtureType; - - /// - /// Construct a OneTimeTearDownCommand - /// - /// The test suite to which the command applies - public OneTimeTearDownCommand(TestSuite suite) - : base(suite) - { - this.suite = suite; - this.fixtureType = suite.FixtureType; - } - - /// - /// Overridden to run the teardown methods specified on the test. - /// - /// The TestExecutionContext to be used. - /// A TestResult - public override TestResult Execute(TestExecutionContext context) - { - TestResult suiteResult = context.CurrentResult; - - if (fixtureType != null) - { - MethodInfo[] teardownMethods = - Reflect.GetMethodsWithAttribute(fixtureType, typeof(TestFixtureTearDownAttribute), true); - - try - { - int index = teardownMethods.Length; - while (--index >= 0) - { - MethodInfo fixtureTearDown = teardownMethods[index]; - if (!fixtureTearDown.IsStatic && context.TestObject == null) - Console.WriteLine("TestObject should not be null!!!"); - Reflect.InvokeMethod(fixtureTearDown, fixtureTearDown.IsStatic ? null : context.TestObject); - } - - IDisposable disposable = context.TestObject as IDisposable; - if (disposable != null) - disposable.Dispose(); - } - catch (Exception ex) - { - // Error in TestFixtureTearDown or Dispose causes the - // suite to be marked as a error, even if - // all the contained tests passed. - NUnitException nex = ex as NUnitException; - if (nex != null) - ex = nex.InnerException; - - // TODO: Can we move this logic into TestResult itself? - string message = "TearDown : " + ExceptionHelper.BuildMessage(ex); - if (suiteResult.Message != null) - message = suiteResult.Message + NUnit.Env.NewLine + message; - - string stackTrace = "--TearDown" + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex); - if (suiteResult.StackTrace != null) - stackTrace = suiteResult.StackTrace + NUnit.Env.NewLine + stackTrace; - - // TODO: What about ignore exceptions in teardown? - suiteResult.SetResult(ResultState.Error, message, stackTrace); - } - } - - return suiteResult; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Commands/RepeatedTestCommand.cs b/test/NUnitLite/src/framework/Internal/Commands/RepeatedTestCommand.cs deleted file mode 100644 index 48b74675d..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/RepeatedTestCommand.cs +++ /dev/null @@ -1,72 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -#if false -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// TODO: Documentation needed for class - /// - public class RepeatedTestCommand : DelegatingTestCommand - { - private int repeatCount; - - /// - /// Initializes a new instance of the class. - /// TODO: Add a comment about where the repeat count is retrieved. - /// - /// The inner command. - public RepeatedTestCommand(TestCommand innerCommand) - : base(innerCommand) - { - this.repeatCount = Test.Properties.GetSetting(PropertyNames.RepeatCount, 1); - } - - /// - /// Runs the test, saving a TestResult in the supplied TestExecutionContext. - /// - /// The context in which the test should run. - /// A TestResult - public override TestResult Execute(TestExecutionContext context) - { - int count = repeatCount; - - while (count-- > 0) - { - context.CurrentResult = innerCommand.Execute(context); - - // TODO: We may want to change this so that all iterations are run - if (context.CurrentResult.ResultState == ResultState.Failure || - context.CurrentResult.ResultState == ResultState.Error || - context.CurrentResult.ResultState == ResultState.Cancelled) - { - break; - } - } - - return context.CurrentResult; - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/Commands/SetUpTearDownCommand.cs b/test/NUnitLite/src/framework/Internal/Commands/SetUpTearDownCommand.cs deleted file mode 100644 index 4cae06607..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/SetUpTearDownCommand.cs +++ /dev/null @@ -1,143 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Threading; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// SetUpTearDownDecorator decorates a test command by running - /// a setup method before the original command and a teardown - /// method after it has executed. - /// - public class SetUpTearDownDecorator : ICommandDecorator - { - CommandStage ICommandDecorator.Stage - { - get { return CommandStage.SetUpTearDown; } - } - - int ICommandDecorator.Priority - { - get { return 0; } - } - - TestCommand ICommandDecorator.Decorate(TestCommand command) - { - return new SetUpTearDownCommand(command); - } - } - - /// - /// TODO: Documentation needed for class - /// - public class SetUpTearDownCommand : DelegatingTestCommand - { - private readonly MethodInfo[] setUpMethods; - private readonly MethodInfo[] tearDownMethods; - - /// - /// Initializes a new instance of the class. - /// - /// The inner command. - public SetUpTearDownCommand(TestCommand innerCommand) - : base(innerCommand) - { - this.setUpMethods = Test.SetUpMethods; - this.tearDownMethods = Test.TearDownMethods; - } - - /// - /// Runs the test, saving a TestResult in the supplied TestExecutionContext. - /// - /// The context in which the test should run. - /// A TestResult - public override TestResult Execute(TestExecutionContext context) - { - try - { - RunSetUpMethods(context); - - context.CurrentResult = innerCommand.Execute(context); - } - catch (Exception ex) - { -#if !NETCF && !SILVERLIGHT - if (ex is ThreadAbortException) - Thread.ResetAbort(); -#endif - context.CurrentResult.RecordException(ex); - } - finally - { - RunTearDownMethods(context); - } - - return context.CurrentResult; - } - - private void RunSetUpMethods(TestExecutionContext context) - { - if (setUpMethods != null) - foreach (MethodInfo setUpMethod in setUpMethods) - Reflect.InvokeMethod(setUpMethod, setUpMethod.IsStatic ? null : context.TestObject); - } - - private void RunTearDownMethods(TestExecutionContext context) - { - try - { - if (tearDownMethods != null) - { - int index = tearDownMethods.Length; - while (--index >= 0) - Reflect.InvokeMethod(tearDownMethods[index], tearDownMethods[index].IsStatic ? null : context.TestObject); - } - } - catch (Exception ex) - { - if (ex is NUnitException) - ex = ex.InnerException; - - // TODO: What about ignore exceptions in teardown? - ResultState resultState = context.CurrentResult.ResultState == ResultState.Cancelled - ? ResultState.Cancelled - : ResultState.Error; - - // TODO: Can we move this logic into TestResult itself? - string message = "TearDown : " + ExceptionHelper.BuildMessage(ex); - if (context.CurrentResult.Message != null) - message = context.CurrentResult.Message + NUnit.Env.NewLine + message; - - string stackTrace = "--TearDown" + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex); - if (context.CurrentResult.StackTrace != null) - stackTrace = context.CurrentResult.StackTrace + NUnit.Env.NewLine + stackTrace; - - context.CurrentResult.SetResult(resultState, message, stackTrace); - } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Commands/TestMethodCommand.cs b/test/NUnitLite/src/framework/Internal/Commands/TestMethodCommand.cs deleted file mode 100644 index 743e188e9..000000000 --- a/test/NUnitLite/src/framework/Internal/Commands/TestMethodCommand.cs +++ /dev/null @@ -1,168 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// TestMethodCommand is the lowest level concrete command - /// used to run actual test cases. - /// - public class TestMethodCommand : TestCommand - { - private const string TaskWaitMethod = "Wait"; - private const string TaskResultProperty = "Result"; - private const string SystemAggregateException = "System.AggregateException"; - private const string InnerExceptionsProperty = "InnerExceptions"; - private const BindingFlags TaskResultPropertyBindingFlags = BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public; - private readonly TestMethod testMethod; - private readonly object[] arguments; - - /// - /// Initializes a new instance of the class. - /// - /// The test. - public TestMethodCommand(TestMethod testMethod) : base(testMethod) - { - this.testMethod = testMethod; - this.arguments = testMethod.Arguments; - } - - /// - /// Runs the test, saving a TestResult in the execution context, as - /// well as returning it. If the test has an expected result, it - /// is asserts on that value. Since failed tests and errors throw - /// an exception, this command must be wrapped in an outer command, - /// will handle that exception and records the failure. This role - /// is usually played by the SetUpTearDown command. - /// - /// The execution context - public override TestResult Execute(TestExecutionContext context) - { - // TODO: Decide if we should handle exceptions here - object result = RunTestMethod(context); - - if (testMethod.HasExpectedResult) - NUnit.Framework.Assert.AreEqual(testMethod.ExpectedResult, result); - - context.CurrentResult.SetResult(ResultState.Success); - // TODO: Set assert count here? - //context.CurrentResult.AssertCount = context.AssertCount; - return context.CurrentResult; - } - - private object RunTestMethod(TestExecutionContext context) - { -#if NET_4_5 - if (MethodHelper.IsAsyncMethod(testMethod.Method)) - return RunAsyncTestMethod(context); - //{ - // if (testMethod.Method.ReturnType == typeof(void)) - // return RunAsyncVoidTestMethod(context); - // else - // return RunAsyncTaskTestMethod(context); - //} - else -#endif - return RunNonAsyncTestMethod(context); - } - -#if NET_4_5 - private object RunAsyncTestMethod(TestExecutionContext context) - { - using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(testMethod.Method)) - { - object result = Reflect.InvokeMethod(testMethod.Method, context.TestObject, arguments); - - try - { - return region.WaitForPendingOperationsToComplete(result); - } - catch (Exception e) - { - throw new NUnitException("Rethrown", e); - } - } - } -#endif - - private object RunNonAsyncTestMethod(TestExecutionContext context) - { - return Reflect.InvokeMethod(testMethod.Method, context.TestObject, arguments); - } - -#if NET_4_5x - private object RunAsyncVoidTestMethod(TestExecutionContext context) - { - var previousContext = SynchronizationContext.Current; - var currentContext = new AsyncSynchronizationContext(); - SynchronizationContext.SetSynchronizationContext(currentContext); - - try - { - object result = Reflect.InvokeMethod(testMethod.Method, context.TestObject, arguments); - - currentContext.WaitForOperationCompleted(); - - if (currentContext.Exceptions.Count > 0) - throw new NUnitException("Rethrown", currentContext.Exceptions[0]); - - return result; - } - finally - { - SynchronizationContext.SetSynchronizationContext(previousContext); - } - } - - private object RunAsyncTaskTestMethod(TestExecutionContext context) - { - try - { - object task = Reflect.InvokeMethod(testMethod.Method, context.TestObject, arguments); - - Reflect.InvokeMethod(testMethod.Method.ReturnType.GetMethod(TaskWaitMethod, new Type[0]), task); - PropertyInfo resultProperty = testMethod.Method.ReturnType.GetProperty(TaskResultProperty, TaskResultPropertyBindingFlags); - - return resultProperty != null ? resultProperty.GetValue(task, null) : null; - } - catch (NUnitException e) - { - if (e.InnerException != null && - e.InnerException.GetType().FullName.Equals(SystemAggregateException)) - { - IList inner = (IList)e.InnerException.GetType() - .GetProperty(InnerExceptionsProperty).GetValue(e.InnerException, null); - - throw new NUnitException("Rethrown", inner[0]); - } - - throw; - } - } -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/CultureDetector.cs b/test/NUnitLite/src/framework/Internal/CultureDetector.cs deleted file mode 100644 index cda504c03..000000000 --- a/test/NUnitLite/src/framework/Internal/CultureDetector.cs +++ /dev/null @@ -1,142 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Globalization; - -namespace NUnit.Framework.Internal -{ - /// - /// CultureDetector is a helper class used by NUnit to determine - /// whether a test should be run based on the current culture. - /// - public class CultureDetector - { - private CultureInfo currentCulture; - - // Set whenever we fail to support a list of platforms - private string reason = string.Empty; - - /// - /// Default constructor uses the current culutre. - /// - public CultureDetector() - { - this.currentCulture = CultureInfo.CurrentCulture; - } - - /// - /// Contruct a CultureDetector for a particular culture for testing. - /// - /// The culture to be used - public CultureDetector( string culture ) - { - this.currentCulture = new CultureInfo( culture ); - } - - /// - /// Test to determine if one of a collection of culturess - /// is being used currently. - /// - /// - /// - public bool IsCultureSupported( string[] cultures ) - { - foreach( string culture in cultures ) - if ( IsCultureSupported( culture ) ) - return true; - - return false; - } - - /// - /// Tests to determine if the current culture is supported - /// based on a culture attribute. - /// - /// The attribute to examine - /// - public bool IsCultureSupported( CultureAttribute cultureAttribute ) - { - string include = cultureAttribute.Include; - string exclude = cultureAttribute.Exclude; - - //try - //{ - if (include != null && !IsCultureSupported(include)) - { - reason = string.Format("Only supported under culture {0}", include); - return false; - } - - if (exclude != null && IsCultureSupported(exclude)) - { - reason = string.Format("Not supported under culture {0}", exclude); - return false; - } - //} - //catch( ArgumentException ex ) - //{ - // reason = string.Format( "Invalid culture: {0}", ex.ParamName ); - // return false; - //} - - return true; - } - - /// - /// Test to determine if the a particular culture or comma- - /// delimited set of cultures is in use. - /// - /// Name of the culture or comma-separated list of culture names - /// True if the culture is in use on the system - public bool IsCultureSupported( string culture ) - { - culture = culture.Trim(); - - if ( culture.IndexOf( ',' ) >= 0 ) - { - if ( IsCultureSupported( culture.Split( new char[] { ',' } ) ) ) - return true; - } - else - { - if( this.currentCulture.Name == culture || this.currentCulture.TwoLetterISOLanguageName == culture) - return true; - } - - this.reason = "Only supported under culture " + culture; - return false; - } - - /// - /// Return the last failure reason. Results are not - /// defined if called before IsSupported( Attribute ) - /// is called. - /// - public string Reason - { - get { return reason; } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/ExceptionHelper.cs b/test/NUnitLite/src/framework/Internal/ExceptionHelper.cs deleted file mode 100644 index 09058aba5..000000000 --- a/test/NUnitLite/src/framework/Internal/ExceptionHelper.cs +++ /dev/null @@ -1,95 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Globalization; -using System.Text; - -namespace NUnit.Framework.Internal -{ - /// - /// ExceptionHelper provides static methods for working with exceptions - /// - public class ExceptionHelper - { - // TODO: Move to a utility class - /// - /// Builds up a message, using the Message field of the specified exception - /// as well as any InnerExceptions. - /// - /// The exception. - /// A combined message string. - public static string BuildMessage(Exception exception) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat(CultureInfo.CurrentCulture, "{0} : {1}", exception.GetType().ToString(), exception.Message); - - Exception inner = exception.InnerException; - while (inner != null) - { - sb.Append(NUnit.Env.NewLine); - sb.AppendFormat(CultureInfo.CurrentCulture, " ----> {0} : {1}", inner.GetType().ToString(), inner.Message); - inner = inner.InnerException; - } - - return sb.ToString(); - } - - /// - /// Builds up a message, using the Message field of the specified exception - /// as well as any InnerExceptions. - /// - /// The exception. - /// A combined stack trace. - public static string BuildStackTrace(Exception exception) - { - StringBuilder sb = new StringBuilder(GetStackTrace(exception)); - - Exception inner = exception.InnerException; - while (inner != null) - { - sb.Append(NUnit.Env.NewLine); - sb.Append("--"); - sb.Append(inner.GetType().Name); - sb.Append(NUnit.Env.NewLine); - sb.Append(GetStackTrace(inner)); - - inner = inner.InnerException; - } - - return sb.ToString(); - } - - private static string GetStackTrace(Exception exception) - { - try - { - return exception.StackTrace; - } - catch (Exception) - { - return "No stack trace available"; - } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Extensibility/ParameterDataProviders.cs b/test/NUnitLite/src/framework/Internal/Extensibility/ParameterDataProviders.cs deleted file mode 100644 index df085d73d..000000000 --- a/test/NUnitLite/src/framework/Internal/Extensibility/ParameterDataProviders.cs +++ /dev/null @@ -1,85 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Builders; - -namespace NUnit.Framework.Extensibility -{ - class ParameterDataProviders : IParameterDataProvider - { -#if CLR_2_0 || CLR_4_0 - private List Extensions = new List(); -#else - private ArrayList Extensions = new ArrayList(); -#endif - - public ParameterDataProviders() - { - Extensions.Add(new ParameterDataProvider()); - Extensions.Add(new DatapointProvider()); - } - - #region IDataPointProvider Members - - /// - /// Determine whether any data is available for a parameter. - /// - /// A ParameterInfo representing one - /// argument to a parameterized test - /// True if any data is available, otherwise false. - public bool HasDataFor(ParameterInfo parameter) - { - foreach (IParameterDataProvider provider in Extensions) - if (provider.HasDataFor(parameter)) - return true; - - return false; - } - - /// - /// Return an IEnumerable providing data for use with the - /// supplied parameter. - /// - /// A ParameterInfo representing one - /// argument to a parameterized test - /// An IEnumerable providing the required data - public IEnumerable GetDataFor(ParameterInfo parameter) - { - ObjectList list = new ObjectList(); - - foreach (IParameterDataProvider provider in Extensions) - if (provider.HasDataFor(parameter)) - foreach (object o in provider.GetDataFor(parameter)) - list.Add(o); - - return list; - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Extensibility/TestCaseProviders.cs b/test/NUnitLite/src/framework/Internal/Extensibility/TestCaseProviders.cs deleted file mode 100644 index d1f5c4626..000000000 --- a/test/NUnitLite/src/framework/Internal/Extensibility/TestCaseProviders.cs +++ /dev/null @@ -1,101 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.Framework.Builders; - -namespace NUnit.Framework.Extensibility -{ - class TestCaseProviders : ITestCaseProvider - { -#if CLR_2_0 || CLR_4_0 - private List Extensions = new List(); -#else - private System.Collections.ArrayList Extensions = new System.Collections.ArrayList(); -#endif - - public TestCaseProviders() - { - this.Extensions.Add(new DataAttributeTestCaseProvider()); - this.Extensions.Add(new CombinatorialTestCaseProvider()); - } - - #region ITestCaseProvider Members - - /// - /// Determine whether any test cases are available for a parameterized method. - /// - /// A MethodInfo representing a parameterized test - /// True if any cases are available, otherwise false. - public bool HasTestCasesFor(MethodInfo method) - { - foreach (ITestCaseProvider provider in Extensions) - if (provider.HasTestCasesFor(method)) - return true; - - return false; - } - - /// - /// Return an enumeration providing test cases for use in - /// running a parameterized test. - /// - /// - /// -#if CLR_2_0 || CLR_4_0 - public System.Collections.Generic.IEnumerable GetTestCasesFor(MethodInfo method) - { - List testcases = new List(); -#else - public System.Collections.IEnumerable GetTestCasesFor(MethodInfo method) - { - System.Collections.ArrayList testcases = new System.Collections.ArrayList(); -#endif - - foreach (ITestCaseProvider provider in Extensions) - try - { - if (provider.HasTestCasesFor(method)) - foreach (ITestCaseData testcase in provider.GetTestCasesFor(method)) - testcases.Add(testcase); - } - catch (System.Reflection.TargetInvocationException ex) - { - testcases.Add(new ParameterSet(ex.InnerException)); - } - catch (System.Exception ex) - { - testcases.Add(new ParameterSet(ex)); - } - - return testcases; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/AndFilter.cs b/test/NUnitLite/src/framework/Internal/Filters/AndFilter.cs deleted file mode 100644 index fa1611010..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/AndFilter.cs +++ /dev/null @@ -1,96 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Filters -{ - /// - /// Combines multiple filters so that a test must pass all - /// of them in order to pass this filter. - /// - [Serializable] - public class AndFilter : TestFilter - { -#if CLR_2_0 || CLR_4_0 - private List filters = new List(); -#else - private System.Collections.ArrayList filters = new System.Collections.ArrayList(); -#endif - - /// - /// Constructs an empty AndFilter - /// - public AndFilter() { } - - /// - /// Constructs an AndFilter from an array of filters - /// - /// - public AndFilter( params ITestFilter[] filters ) - { - this.filters.AddRange( filters ); - } - - /// - /// Adds a filter to the list of filters - /// - /// The filter to be added - public void Add( ITestFilter filter ) - { - this.filters.Add( filter ); - } - - /// - /// Checks whether the AndFilter is matched by a test - /// - /// The test to be matched - /// True if all the component filters pass, otherwise false - public override bool Pass( ITest test ) - { - foreach( ITestFilter filter in filters ) - if ( !filter.Pass( test ) ) - return false; - - return true; - } - - /// - /// Checks whether the AndFilter is matched by a test - /// - /// The test to be matched - /// True if all the component filters match, otherwise false - public override bool Match( ITest test ) - { - foreach( TestFilter filter in filters ) - if ( !filter.Match( test ) ) - return false; - - return true; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/CategoryExpression.cs b/test/NUnitLite/src/framework/Internal/Filters/CategoryExpression.cs deleted file mode 100644 index 5b6eb8f27..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/CategoryExpression.cs +++ /dev/null @@ -1,180 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Internal.Filters -{ - /// - /// CategoryExpression parses strings representing boolean - /// combinations of categories according to the following - /// grammar: - /// CategoryName ::= string not containing any of ',', '&', '+', '-' - /// CategoryFilter ::= CategoryName | CategoryFilter ',' CategoryName - /// CategoryPrimitive ::= CategoryFilter | '-' CategoryPrimitive - /// CategoryTerm ::= CategoryPrimitive | CategoryTerm '&' CategoryPrimitive - /// - public class CategoryExpression - { - static readonly char[] ops = new char[] { ',', ';', '-', '|', '+', '(', ')' }; - - private string text; - private int next; - private string token; - - private TestFilter filter; - - /// - /// Construct expression from a text string - /// - /// The text of the expression - public CategoryExpression(string text) - { - this.text = text; - this.next = 0; - } - - /// - /// Gets the TestFilter represented by the expression - /// - public TestFilter Filter - { - get - { - if( filter == null ) - { - filter = GetToken() == null - ? TestFilter.Empty - : GetExpression(); - } - - return filter; - } - } - - private TestFilter GetExpression() - { - TestFilter term = GetTerm(); - if ( token != "|" ) - return term; - - OrFilter filter = new OrFilter( term ); - - while ( token == "|" ) - { - GetToken(); - filter.Add( GetTerm() ); - } - - return filter; - } - - private TestFilter GetTerm() - { - TestFilter prim = GetPrimitive(); - if ( token != "+" && token != "-" ) - return prim; - - AndFilter filter = new AndFilter( prim ); - - while ( token == "+"|| token == "-" ) - { - string tok = token; - GetToken(); - prim = GetPrimitive(); - filter.Add( tok == "-" ? new NotFilter( prim ) : prim ); - } - - return filter; - } - - private TestFilter GetPrimitive() - { - if( token == "-" ) - { - GetToken(); - return new NotFilter( GetPrimitive() ); - } - else if( token == "(" ) - { - GetToken(); - TestFilter expr = GetExpression(); - GetToken(); // Skip ')' - return expr; - } - - return GetCategoryFilter(); - } - - private CategoryFilter GetCategoryFilter() - { - CategoryFilter filter = new CategoryFilter( token ); - - while( GetToken() == "," || token == ";" ) - filter.AddCategory( GetToken() ); - - return filter; - } - - private string GetToken() - { - SkipWhiteSpace(); - - if ( EndOfText() ) - token = null; - else if ( NextIsOperator() ) - token = text.Substring(next++, 1); - else - { - int index2 = text.IndexOfAny( ops, next ); - if ( index2 < 0 ) index2 = text.Length; - - token = text.Substring( next, index2 - next ).TrimEnd(); - next = index2; - } - - return token; - } - - private void SkipWhiteSpace() - { - while( next < text.Length && Char.IsWhiteSpace( text[next] ) ) - ++next; - } - - private bool EndOfText() - { - return next >= text.Length; - } - - private bool NextIsOperator() - { - foreach( char op in ops ) - if( op == text[next] ) - return true; - - return false; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/CategoryFilter.cs b/test/NUnitLite/src/framework/Internal/Filters/CategoryFilter.cs deleted file mode 100644 index 1eac74a29..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/CategoryFilter.cs +++ /dev/null @@ -1,118 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Text; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Filters -{ - /// - /// CategoryFilter is able to select or exclude tests - /// based on their categories. - /// - /// - [Serializable] - public class CategoryFilter : TestFilter - { -#if CLR_2_0 || CLR_4_0 - List categories = new List(); -#else - ArrayList categories = new ArrayList(); -#endif - - /// - /// Construct an empty CategoryFilter - /// - public CategoryFilter() - { - } - - /// - /// Construct a CategoryFilter using a single category name - /// - /// A category name - public CategoryFilter( string name ) - { - if ( name != null && name != string.Empty ) - categories.Add( name ); - } - - /// - /// Construct a CategoryFilter using an array of category names - /// - /// An array of category names - public CategoryFilter( string[] names ) - { - if ( names != null ) - categories.AddRange( names ); - } - - /// - /// Add a category name to the filter - /// - /// A category name - public void AddCategory(string name) - { - categories.Add( name ); - } - - /// - /// Check whether the filter matches a test - /// - /// The test to be matched - /// - public override bool Match(ITest test) - { - IList testCategories = test.Properties[PropertyNames.Category] as IList; - - if ( testCategories == null || testCategories.Count == 0) - return false; - - foreach( string cat in this.categories ) - if ( testCategories.Contains( cat ) ) - return true; - - return false; - } - - /// - /// Return the string representation of a category filter - /// - /// - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - for( int i = 0; i < categories.Count; i++ ) - { - if ( i > 0 ) sb.Append( ',' ); - sb.Append( categories[i] ); - } - return sb.ToString(); - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/NotFilter.cs b/test/NUnitLite/src/framework/Internal/Filters/NotFilter.cs deleted file mode 100644 index 7a16fe639..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/NotFilter.cs +++ /dev/null @@ -1,97 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Filters -{ - /// - /// NotFilter negates the operation of another filter - /// - [Serializable] - public class NotFilter : TestFilter - { - ITestFilter baseFilter; - bool topLevel = false; - - /// - /// Construct a not filter on another filter - /// - /// The filter to be negated - public NotFilter( ITestFilter baseFilter) - { - this.baseFilter = baseFilter; - } - - /// - /// Indicates whether this is a top-level NotFilter, - /// requiring special handling of Explicit - /// - public bool TopLevel - { - get { return topLevel; } - set { topLevel = value; } - } - - /// - /// Gets the base filter - /// - public ITestFilter BaseFilter - { - get { return baseFilter; } - } - - /// - /// Check whether the filter matches a test - /// - /// The test to be matched - /// True if it matches, otherwise false - public override bool Match( ITest test ) - { - if (topLevel && test.RunState == RunState.Explicit) - return false; - - return !baseFilter.Pass( test ); - } - - /// - /// Determine whether any descendant of the test matches the filter criteria. - /// - /// The test to be matched - /// True if at least one descendant matches the filter criteria - protected override bool MatchDescendant(ITest test) - { - if (!test.HasChildren || test.Tests == null || topLevel && test.RunState == RunState.Explicit) - return false; - - foreach (ITest child in test.Tests) - { - if (Match(child) || MatchDescendant(child)) - return true; - } - - return false; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/OrFilter.cs b/test/NUnitLite/src/framework/Internal/Filters/OrFilter.cs deleted file mode 100644 index 74171cbda..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/OrFilter.cs +++ /dev/null @@ -1,111 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Filters -{ - /// - /// Combines multiple filters so that a test must pass one - /// of them in order to pass this filter. - /// - [Serializable] - public class OrFilter : TestFilter - { -#if CLR_2_0 || CLR_4_0 - private List filters = new List(); -#else - private System.Collections.ArrayList filters = new System.Collections.ArrayList(); -#endif - - /// - /// Constructs an empty OrFilter - /// - public OrFilter() { } - - /// - /// Constructs an AndFilter from an array of filters - /// - /// - public OrFilter( params ITestFilter[] filters ) - { - this.filters.AddRange( filters ); - } - - /// - /// Adds a filter to the list of filters - /// - /// The filter to be added - public void Add( ITestFilter filter ) - { - this.filters.Add( filter ); - } - - /// - /// Return an array of the composing filters - /// - public ITestFilter[] Filters - { - get - { -#if CLR_2_0 || CLR_4_0 - return filters.ToArray(); -#else - return (ITestFilter[])filters.ToArray(typeof(ITestFilter)); -#endif - } - } - - /// - /// Checks whether the OrFilter is matched by a test - /// - /// The test to be matched - /// True if any of the component filters pass, otherwise false - public override bool Pass( ITest test ) - { - foreach( ITestFilter filter in filters ) - if ( filter.Pass( test ) ) - return true; - - return false; - } - - /// - /// Checks whether the OrFilter is matched by a test - /// - /// The test to be matched - /// True if any of the component filters match, otherwise false - public override bool Match( ITest test ) - { - foreach( TestFilter filter in filters ) - if ( filter.Match( test ) ) - return true; - - return false; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/SimpleCategoryExpression.cs b/test/NUnitLite/src/framework/Internal/Filters/SimpleCategoryExpression.cs deleted file mode 100644 index 87ef5ab87..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/SimpleCategoryExpression.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace NUnit.Framework.Internal.Filters -{ - /// - /// SimpleCategoryFilter parses a basic string representing a - /// single category or a list of categories separated by commas - /// - public class SimpleCategoryExpression - { - private string text; - - private TestFilter filter; - - /// - /// Construct category filter from a text string - /// - /// A list of categories to parse - public SimpleCategoryExpression(string text) - { - this.text = text; - } - - /// - /// Gets the TestFilter represented by the expression - /// - public TestFilter Filter - { - get - { - if (filter == null) - { - filter = GetCategories(); - } - return filter; - } - } - - private TestFilter GetCategories() - { - string[] categories = text.Split(','); - return new CategoryFilter(categories); - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Filters/SimpleNameFilter.cs b/test/NUnitLite/src/framework/Internal/Filters/SimpleNameFilter.cs deleted file mode 100644 index bec326a46..000000000 --- a/test/NUnitLite/src/framework/Internal/Filters/SimpleNameFilter.cs +++ /dev/null @@ -1,93 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.Filters -{ - /// - /// SimpleName filter selects tests based on their name - /// - [Serializable] - public class SimpleNameFilter : TestFilter - { -#if CLR_2_0 || CLR_4_0 - private List names = new List(); -#else - private System.Collections.ArrayList names = new System.Collections.ArrayList(); -#endif - - /// - /// Construct an empty SimpleNameFilter - /// - public SimpleNameFilter() { } - - /// - /// Construct a SimpleNameFilter for a single name - /// - /// The name the filter will recognize. - public SimpleNameFilter(string nameToAdd) - { - Add(nameToAdd); - } - - /// - /// Construct a SimpleNameFilter for an array of names - /// - /// The names the filter will recognize. - public SimpleNameFilter(string[] namesToAdd) - { - foreach (string name in namesToAdd) - Add(name); - } - - /// - /// Add a name to a SimpleNameFilter - /// - /// The name to be added. - public void Add(string name) - { - Guard.ArgumentNotNullOrEmpty(name, "name"); - - names.Add(name); - } - - /// - /// Check whether the filter matches a test - /// - /// The test to be matched - /// True if it matches, otherwise false - public override bool Match( ITest test ) - { - foreach( string name in names ) - if ( test.FullName == name ) - return true; - - return false; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/InvalidTestFixtureException.cs b/test/NUnitLite/src/framework/Internal/InvalidTestFixtureException.cs deleted file mode 100644 index c17e92b41..000000000 --- a/test/NUnitLite/src/framework/Internal/InvalidTestFixtureException.cs +++ /dev/null @@ -1,66 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2006 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Internal -{ - using System; -#if !NETCF - using System.Runtime.Serialization; -#endif - - /// - /// InvalidTestFixtureException is thrown when an appropriate test - /// fixture constructor using the provided arguments cannot be found. - /// - [Serializable] - public class InvalidTestFixtureException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public InvalidTestFixtureException() : base() {} - - /// - /// Initializes a new instance of the class. - /// - /// The message. - public InvalidTestFixtureException(string message) : base(message) - {} - - /// - /// Initializes a new instance of the class. - /// - /// The message. - /// The inner. - public InvalidTestFixtureException(string message, Exception inner) : base(message, inner) - {} - -#if !NETCF && !SILVERLIGHT - /// - /// Serialization Constructor - /// - protected InvalidTestFixtureException(SerializationInfo info, - StreamingContext context) : base(info,context){} -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/framework/Internal/MethodHelper.cs b/test/NUnitLite/src/framework/Internal/MethodHelper.cs deleted file mode 100644 index 780eaf8cb..000000000 --- a/test/NUnitLite/src/framework/Internal/MethodHelper.cs +++ /dev/null @@ -1,226 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Text; - -namespace NUnit.Framework.Internal -{ - /// - /// MethodHelper provides static methods for working with methods. - /// - public class MethodHelper - { - /// - /// Gets the display name for a method as used by NUnit. - /// - /// The method for which a display name is needed. - /// The arguments provided. - /// The display name for the method - public static string GetDisplayName(MethodInfo method, object[] arglist) - { - StringBuilder sb = new StringBuilder(method.Name); - -#if CLR_2_0 || CLR_4_0 - if (method.IsGenericMethod) - { - sb.Append("<"); - int cnt = 0; - foreach (Type t in method.GetGenericArguments()) - { - if (cnt++ > 0) sb.Append(","); - sb.Append(t.Name); - } - sb.Append(">"); - } -#endif - - if (arglist != null) - { - sb.Append("("); - - for (int i = 0; i < arglist.Length; i++) - { - if (i > 0) sb.Append(","); - sb.Append(GetDisplayString(arglist[i])); - } - - sb.Append(")"); - } - - return sb.ToString(); - } - - private static string GetDisplayString(object arg) - { - string display = arg == null - ? "null" - : Convert.ToString(arg, System.Globalization.CultureInfo.InvariantCulture); - - if (arg is double) - { - double d = (double)arg; - - if (double.IsNaN(d)) - display = "double.NaN"; - else if (double.IsPositiveInfinity(d)) - display = "double.PositiveInfinity"; - else if (double.IsNegativeInfinity(d)) - display = "double.NegativeInfinity"; - else if (d == double.MaxValue) - display = "double.MaxValue"; - else if (d == double.MinValue) - display = "double.MinValue"; - else - { - if (display.IndexOf('.') == -1) - display += ".0"; - display += "d"; - } - } - else if (arg is float) - { - float f = (float)arg; - - if (float.IsNaN(f)) - display = "float.NaN"; - else if (float.IsPositiveInfinity(f)) - display = "float.PositiveInfinity"; - else if (float.IsNegativeInfinity(f)) - display = "float.NegativeInfinity"; - else if (f == float.MaxValue) - display = "float.MaxValue"; - else if (f == float.MinValue) - display = "float.MinValue"; - else - { - if (display.IndexOf('.') == -1) - display += ".0"; - display += "f"; - } - } - else if (arg is decimal) - { - decimal d = (decimal)arg; - if (d == decimal.MinValue) - display = "decimal.MinValue"; - else if (d == decimal.MaxValue) - display = "decimal.MaxValue"; - else - display += "m"; - } - else if (arg is long) - { - long l = (long)arg; - if (l == long.MinValue) - display = "long.MinValue"; - else if (l == long.MinValue) - display = "long.MaxValue"; - else - display += "L"; - } - else if (arg is ulong) - { - ulong ul = (ulong)arg; - if (ul == ulong.MinValue) - display = "ulong.MinValue"; - else if (ul == ulong.MinValue) - display = "ulong.MaxValue"; - else - display += "UL"; - } - else if (arg is string) - { - StringBuilder sb = new StringBuilder(); - sb.Append("\""); - foreach (char c in (string)arg) - sb.Append(EscapeControlChar(c)); - sb.Append("\""); - display = sb.ToString(); - } - else if (arg is char) - { - display = "\'" + EscapeControlChar((char)arg) + "\'"; - } - else if (arg is int) - { - int ival = (int)arg; - if (ival == int.MaxValue) - display = "int.MaxValue"; - else if (ival == int.MinValue) - display = "int.MinValue"; - } - - return display; - } - - private static string EscapeControlChar(char c) - { - switch (c) - { - case '\'': - return "\\\'"; - case '\"': - return "\\\""; - case '\\': - return "\\\\"; - case '\0': - return "\\0"; - case '\a': - return "\\a"; - case '\b': - return "\\b"; - case '\f': - return "\\f"; - case '\n': - return "\\n"; - case '\r': - return "\\r"; - case '\t': - return "\\t"; - case '\v': - return "\\v"; - - case '\x0085': - case '\x2028': - case '\x2029': - return string.Format("\\x{0:X4}", (int)c); - - default: - return c.ToString(); - } - } - -#if NET_4_5 - /// - /// Returns true if the method specified by the argument - /// is an async method. - /// - public static bool IsAsyncMethod(MethodInfo method) - { - return method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute)); - } -#endif - } -} diff --git a/test/NUnitLite/src/framework/Internal/NUnitException.cs b/test/NUnitLite/src/framework/Internal/NUnitException.cs deleted file mode 100644 index 2665b54d4..000000000 --- a/test/NUnitLite/src/framework/Internal/NUnitException.cs +++ /dev/null @@ -1,71 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Internal -{ - using System; -#if !NETCF - using System.Runtime.Serialization; -#endif - - /// - /// Thrown when an assertion failed. Here to preserve the inner - /// exception and hence its stack trace. - /// - [Serializable] - public class NUnitException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public NUnitException () : base() - {} - - /// - /// Initializes a new instance of the class. - /// - /// The error message that explains - /// the reason for the exception - public NUnitException(string message) : base (message) - {} - - /// - /// Initializes a new instance of the class. - /// - /// The error message that explains - /// the reason for the exception - /// The exception that caused the - /// current exception - public NUnitException(string message, Exception inner) : - base(message, inner) - {} - -#if !NETCF && !SILVERLIGHT - /// - /// Serialization Constructor - /// - protected NUnitException(SerializationInfo info, - StreamingContext context) : base(info,context){} -#endif - } -} diff --git a/test/NUnitLite/src/framework/Internal/NUnitLiteTestAssemblyBuilder.cs b/test/NUnitLite/src/framework/Internal/NUnitLiteTestAssemblyBuilder.cs deleted file mode 100644 index 26ea0acf0..000000000 --- a/test/NUnitLite/src/framework/Internal/NUnitLiteTestAssemblyBuilder.cs +++ /dev/null @@ -1,196 +0,0 @@ -using System; -using System.Collections; -using System.IO; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Builders; -using NUnit.Framework.Extensibility; - -namespace NUnit.Framework.Internal -{ - /// - /// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite - /// containing test fixtures present in the assembly. - /// - public class NUnitLiteTestAssemblyBuilder : ITestAssemblyBuilder - { - #region Instance Fields - - /// - /// The loaded assembly - /// - Assembly assembly; - - #endregion - - #region Constructor - - /// - /// Initializes a new instance of the class. - /// - public NUnitLiteTestAssemblyBuilder() - { - } - - #endregion - - #region Build Methods - /// - /// Build a suite of tests from a provided assembly - /// - /// The assembly from which tests are to be built - /// A dictionary of options to use in building the suite - /// - /// A TestSuite containing the tests found in the assembly - /// - public TestSuite Build(Assembly assembly, IDictionary options) - { - this.assembly = assembly; - - IList fixtureNames = options["LOAD"] as IList; - - IList fixtures = GetFixtures(assembly, fixtureNames); - - if (fixtures.Count > 0) - { -#if NETCF || SILVERLIGHT - AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(assembly); - return BuildTestAssembly(assemblyName.Name, fixtures); -#else - string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly); - return BuildTestAssembly(assemblyPath, fixtures); -#endif - } - - return null; - } - - /// - /// Build a suite of tests given the filename of an assembly - /// - /// The filename of the assembly from which tests are to be built - /// A dictionary of options to use in building the suite - /// - /// A TestSuite containing the tests found in the assembly - /// - public TestSuite Build(string assemblyName, IDictionary options) - { - this.assembly = Load(assemblyName); - if (assembly == null) return null; - - IList fixtureNames = options["LOAD"] as IList; - - IList fixtures = GetFixtures(assembly, fixtureNames); - if (fixtures.Count > 0) - return BuildTestAssembly(assemblyName, fixtures); - - return null; - } - #endregion - - #region Helper Methods - - private Assembly Load(string path) - { -#if NETCF || SILVERLIGHT - return Assembly.Load(path); -#else - // Throws if this isn't a managed assembly or if it was built - // with a later version of the same assembly. - AssemblyName assemblyName = AssemblyName.GetAssemblyName(Path.GetFileName(path)); - - return Assembly.Load(assemblyName); -#endif - } - - private IList GetFixtures(Assembly assembly, IList names) - { - ObjectList fixtures = new ObjectList(); - - IList testTypes = GetCandidateFixtureTypes(assembly, names); - - foreach (Type testType in testTypes) - { - if (TestFixtureBuilder.CanBuildFrom(testType)) - fixtures.Add(TestFixtureBuilder.BuildFrom(testType)); - } - - return fixtures; - } - - private IList GetCandidateFixtureTypes(Assembly assembly, IList names) - { - IList types = assembly.GetTypes(); - - if (names == null || names.Count == 0) - return types; - - ObjectList result = new ObjectList(); - - foreach (string name in names) - { - Type fixtureType = assembly.GetType(name); - if (fixtureType != null) - result.Add(fixtureType); - else - { - string prefix = name + "."; - - foreach (Type type in types) - if (type.FullName.StartsWith(prefix)) - result.Add(type); - } - } - - return result; - } - - private TestSuite BuildFromFixtureType(string assemblyName, Type testType) - { - // TODO: This is the only situation in which we currently - // recognize and load legacy suites. We need to determine - // whether to allow them in more places. - //if (legacySuiteBuilder.CanBuildFrom(testType)) - // return (TestSuite)legacySuiteBuilder.BuildFrom(testType); - //else - if (TestFixtureBuilder.CanBuildFrom(testType)) - return BuildTestAssembly(assemblyName, - new Test[] { TestFixtureBuilder.BuildFrom(testType) }); - return null; - } - - private TestSuite BuildTestAssembly(string assemblyName, IList fixtures) - { - TestSuite testAssembly = new TestAssembly(this.assembly, assemblyName); - testAssembly.Seed = Randomizer.InitialSeed; - - //NamespaceTreeBuilder treeBuilder = - // new NamespaceTreeBuilder(testAssembly); - //treeBuilder.Add(fixtures); - //testAssembly = treeBuilder.RootSuite; - - foreach (Test fixture in fixtures) - testAssembly.Add(fixture); - - if (fixtures.Count == 0) - { - testAssembly.RunState = RunState.NotRunnable; - testAssembly.Properties.Set(PropertyNames.SkipReason, "Has no TestFixtures"); - } - - testAssembly.ApplyAttributesToTest(assembly); - -#if !SILVERLIGHT - testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id); -#endif - testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName); - - - // TODO: Make this an option? Add Option to sort assemblies as well? - testAssembly.Sort(); - - return testAssembly; - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/NUnitLiteTestAssemblyRunner.cs b/test/NUnitLite/src/framework/Internal/NUnitLiteTestAssemblyRunner.cs deleted file mode 100644 index 0a2ad3e25..000000000 --- a/test/NUnitLite/src/framework/Internal/NUnitLiteTestAssemblyRunner.cs +++ /dev/null @@ -1,143 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal.WorkItems; - -namespace NUnit.Framework.Internal -{ - /// - /// Default implementation of ITestAssemblyRunner - /// - public class NUnitLiteTestAssemblyRunner : ITestAssemblyRunner - { - private IDictionary settings; - private ITestAssemblyBuilder builder; - private TestSuite loadedTest; - //private Thread runThread; - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The builder. - public NUnitLiteTestAssemblyRunner(ITestAssemblyBuilder builder) - { - this.builder = builder; - } - - #endregion - - #region Properties - - /// - /// TODO: Documentation needed for property - /// - public ITest LoadedTest - { - get - { - return this.loadedTest; - } - } - - #endregion - - #region Methods - - /// - /// Loads the tests found in an Assembly - /// - /// File name of the assembly to load - /// Dictionary of option settings for loading the assembly - /// True if the load was successful - public bool Load(string assemblyName, IDictionary settings) - { - this.settings = settings; - this.loadedTest = this.builder.Build(assemblyName, settings); - if (loadedTest == null) return false; - - return true; - } - - /// - /// Loads the tests found in an Assembly - /// - /// The assembly to load - /// Dictionary of option settings for loading the assembly - /// True if the load was successful - public bool Load(Assembly assembly, IDictionary settings) - { - this.settings = settings; - this.loadedTest = this.builder.Build(assembly, settings); - if (loadedTest == null) return false; - - return true; - } - - ///// - ///// Count Test Cases using a filter - ///// - ///// The filter to apply - ///// The number of test cases found - //public int CountTestCases(TestFilter filter) - //{ - // return this.suite.CountTestCases(filter); - //} - - /// - /// Run selected tests and return a test result. The test is run synchronously, - /// and the listener interface is notified as it progresses. - /// - /// Interface to receive EventListener notifications. - /// A test filter used to select tests to be run - /// - public ITestResult Run(ITestListener listener, ITestFilter filter) - { - TestExecutionContext context = new TestExecutionContext(); - - if (this.settings.Contains("WorkDirectory")) - context.WorkDirectory = (string)this.settings["WorkDirectory"]; - else -#if NETCF || SILVERLIGHT - context.WorkDirectory = Env.DocumentFolder; -#else - context.WorkDirectory = Environment.CurrentDirectory; -#endif - context.Listener = listener; - - WorkItem workItem = loadedTest.CreateWorkItem(filter); - workItem.Execute(context); - - while (workItem.State != WorkItemState.Complete) - System.Threading.Thread.Sleep(5); - return workItem.Result; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/OSPlatform.cs b/test/NUnitLite/src/framework/Internal/OSPlatform.cs deleted file mode 100644 index 0ced8cdb4..000000000 --- a/test/NUnitLite/src/framework/Internal/OSPlatform.cs +++ /dev/null @@ -1,386 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Runtime.InteropServices; - -namespace NUnit.Framework.Internal -{ - /// - /// OSPlatform represents a particular operating system platform - /// - public class OSPlatform - { - PlatformID platform; - Version version; - ProductType product; - - #region Static Members - private static OSPlatform currentPlatform; - - - /// - /// Platform ID for Unix as defined by Microsoft .NET 2.0 and greater - /// - public static readonly PlatformID UnixPlatformID_Microsoft = (PlatformID)4; - - /// - /// Platform ID for Unix as defined by Mono - /// - public static readonly PlatformID UnixPlatformID_Mono = (PlatformID)128; - - /// - /// Get the OSPlatform under which we are currently running - /// - public static OSPlatform CurrentPlatform - { - get - { - if (currentPlatform == null) - { - OperatingSystem os = Environment.OSVersion; - -#if SILVERLIGHT - // TODO: Runtime silverlight detection? - currentPlatform = new OSPlatform(os.Platform, os.Version); -#else - if (os.Platform == PlatformID.Win32NT && os.Version.Major >= 5) - { - OSVERSIONINFOEX osvi = new OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); - GetVersionEx(ref osvi); - currentPlatform = new OSPlatform(os.Platform, os.Version, (ProductType)osvi.ProductType); - } - else - currentPlatform = new OSPlatform(os.Platform, os.Version); -#endif - } - - return currentPlatform; - } - } - #endregion - - #region Members used for Win32NT platform only - /// - /// Product Type Enumeration used for Windows - /// - public enum ProductType - { - /// - /// Product type is unknown or unspecified - /// - Unknown, - - /// - /// Product type is Workstation - /// - WorkStation, - - /// - /// Product type is Domain Controller - /// - DomainController, - - /// - /// Product type is Server - /// - Server, - } - - [StructLayout(LayoutKind.Sequential)] - struct OSVERSIONINFOEX - { - public uint dwOSVersionInfoSize; - public uint dwMajorVersion; - public uint dwMinorVersion; - public uint dwBuildNumber; - public uint dwPlatformId; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string szCSDVersion; - public Int16 wServicePackMajor; - public Int16 wServicePackMinor; - public Int16 wSuiteMask; - public Byte ProductType; - public Byte Reserved; - } - - [DllImport("Kernel32.dll")] - private static extern bool GetVersionEx(ref OSVERSIONINFOEX osvi); - #endregion - - /// - /// Construct from a platform ID and version - /// - public OSPlatform(PlatformID platform, Version version) - { - this.platform = platform; - this.version = version; - } - - /// - /// Construct from a platform ID, version and product type - /// - public OSPlatform(PlatformID platform, Version version, ProductType product) - : this( platform, version ) - { - this.product = product; - } - - /// - /// Get the platform ID of this instance - /// - public PlatformID Platform - { - get { return platform; } - } - - /// - /// Get the Version of this instance - /// - public Version Version - { - get { return version; } - } - - /// - /// Get the Product Type of this instance - /// - public ProductType Product - { - get { return product; } - } - - /// - /// Return true if this is a windows platform - /// - public bool IsWindows - { - get - { - return platform == PlatformID.Win32NT - || platform == PlatformID.Win32Windows - || platform == PlatformID.Win32S - || platform == PlatformID.WinCE; - } - } - - /// - /// Return true if this is a Unix or Linux platform - /// - public bool IsUnix - { - get - { - return platform == UnixPlatformID_Microsoft - || platform == UnixPlatformID_Mono; - } - } - - /// - /// Return true if the platform is Win32S - /// - public bool IsWin32S - { - get { return platform == PlatformID.Win32S; } - } - - /// - /// Return true if the platform is Win32Windows - /// - public bool IsWin32Windows - { - get { return platform == PlatformID.Win32Windows; } - } - - /// - /// Return true if the platform is Win32NT - /// - public bool IsWin32NT - { - get { return platform == PlatformID.Win32NT; } - } - - /// - /// Return true if the platform is Windows CE - /// - public bool IsWinCE - { - get { return (int)platform == 3; } // PlatformID.WinCE not defined in .NET 1.0 - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF - /// - /// Return true if the platform is Xbox - /// - public bool IsXbox - { - get { return platform == PlatformID.Xbox; } - } - - /// - /// Return true if the platform is MacOSX - /// - public bool IsMacOSX - { - get { return platform == PlatformID.MacOSX; } - } -#endif - - /// - /// Return true if the platform is Windows 95 - /// - public bool IsWin95 - { - get { return platform == PlatformID.Win32Windows && version.Major == 4 && version.Minor == 0; } - } - - /// - /// Return true if the platform is Windows 98 - /// - public bool IsWin98 - { - get { return platform == PlatformID.Win32Windows && version.Major == 4 && version.Minor == 10; } - } - - /// - /// Return true if the platform is Windows ME - /// - public bool IsWinME - { - get { return platform == PlatformID.Win32Windows && version.Major == 4 && version.Minor == 90; } - } - - /// - /// Return true if the platform is NT 3 - /// - public bool IsNT3 - { - get { return platform == PlatformID.Win32NT && version.Major == 3; } - } - - /// - /// Return true if the platform is NT 4 - /// - public bool IsNT4 - { - get { return platform == PlatformID.Win32NT && version.Major == 4; } - } - - /// - /// Return true if the platform is NT 5 - /// - public bool IsNT5 - { - get { return platform == PlatformID.Win32NT && version.Major == 5; } - } - - /// - /// Return true if the platform is Windows 2000 - /// - public bool IsWin2K - { - get { return IsNT5 && version.Minor == 0; } - } - - /// - /// Return true if the platform is Windows XP - /// - public bool IsWinXP - { - get { return IsNT5 && (version.Minor == 1 || version.Minor == 2 && Product == ProductType.WorkStation); } - } - - /// - /// Return true if the platform is Windows 2003 Server - /// - public bool IsWin2003Server - { - get { return IsNT5 && version.Minor == 2 && Product == ProductType.Server; } - } - - /// - /// Return true if the platform is NT 6 - /// - public bool IsNT6 - { - get { return platform == PlatformID.Win32NT && version.Major == 6; } - } - - /// - /// Return true if the platform is Vista - /// - public bool IsVista - { - get { return IsNT6 && version.Minor == 0 && Product == ProductType.WorkStation; } - } - - /// - /// Return true if the platform is Windows 2008 Server (original or R2) - /// - public bool IsWin2008Server - { - get { return IsNT6 && Product == ProductType.Server; } - } - - /// - /// Return true if the platform is Windows 2008 Server (original) - /// - public bool IsWin2008ServerR1 - { - get { return IsNT6 && version.Minor == 0 && Product == ProductType.Server; } - } - - /// - /// Return true if the platform is Windows 2008 Server R2 - /// - public bool IsWin2008ServerR2 - { - get { return IsNT6 && version.Minor == 1 && Product == ProductType.Server; } - } - - /// - /// Return true if the platform is Windows 2012 Server - /// - public bool IsWin2012Server - { - get { return IsNT6 && version.Minor == 2 && Product == ProductType.Server; } - } - - /// - /// Return true if the platform is Windows 7 - /// - public bool IsWindows7 - { - get { return IsNT6 && version.Minor == 1 && Product == ProductType.WorkStation; } - } - - /// - /// Return true if the platform is Windows 8 - /// - public bool IsWindows8 - { - get { return IsNT6 && version.Minor == 8 && Product == ProductType.WorkStation; } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/ParameterSet.cs b/test/NUnitLite/src/framework/Internal/ParameterSet.cs deleted file mode 100644 index 68277ebeb..000000000 --- a/test/NUnitLite/src/framework/Internal/ParameterSet.cs +++ /dev/null @@ -1,219 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// ParameterSet encapsulates method arguments and - /// other selected parameters needed for constructing - /// a parameterized test case. - /// - public class ParameterSet : ITestCaseData, IApplyToTest - { - #region Instance Fields - - private object[] arguments; - private object[] originalArguments; - private object result; - private bool hasExpectedResult; - private ExpectedExceptionData exceptionData; - - /// - /// A dictionary of properties, used to add information - /// to tests without requiring the class to change. - /// - private IPropertyBag properties; - - #endregion - - #region Properties - - private RunState runState; - /// - /// The RunState for this set of parameters. - /// - public RunState RunState - { - get { return runState; } - set { runState = value; } - } - - /// - /// The arguments to be used in running the test, - /// which must match the method signature. - /// - public object[] Arguments - { - get { return arguments; } - set - { - arguments = value; - - if (originalArguments == null) - originalArguments = value; - } - } - - /// - /// The original arguments provided by the user, - /// used for display purposes. - /// - public object[] OriginalArguments - { - get { return originalArguments; } - } - - /// - /// Gets a flag indicating whether an exception is expected. - /// - public bool ExceptionExpected - { - get { return exceptionData.ExpectedExceptionName != null; } - } - - /// - /// Data about any expected exception - /// - public ExpectedExceptionData ExceptionData - { - get { return exceptionData; } - } - - /// - /// The expected result of the test, which - /// must match the method return type. - /// - public object ExpectedResult - { - get { return result; } - set - { - result = value; - hasExpectedResult = true; - } - } - - /// - /// Gets a value indicating whether an expected result was specified. - /// - public bool HasExpectedResult - { - get { return hasExpectedResult; } - } - - private string testName; - /// - /// A name to be used for this test case in lieu - /// of the standard generated name containing - /// the argument list. - /// - public string TestName - { - get { return testName; } - set { testName = value; } - } - - /// - /// Gets the property dictionary for this test - /// - public IPropertyBag Properties - { - get - { - if (properties == null) - properties = new PropertyBag(); - - return properties; - } - } - - #endregion - - #region Constructors - - /// - /// Construct a non-runnable ParameterSet, specifying - /// the provider exception that made it invalid. - /// - public ParameterSet(Exception exception) - { - this.RunState = RunState.NotRunnable; - this.Properties.Set(PropertyNames.SkipReason, ExceptionHelper.BuildMessage(exception)); - this.Properties.Set(PropertyNames.ProviderStackTrace, ExceptionHelper.BuildStackTrace(exception)); - } - - /// - /// Construct an empty parameter set, which - /// defaults to being Runnable. - /// - public ParameterSet() - { - this.RunState = RunState.Runnable; - } - - /// - /// Construct a ParameterSet from an object implementing ITestCaseData - /// - /// - public ParameterSet(ITestCaseData data) - { - this.TestName = data.TestName; - this.RunState = data.RunState; - this.Arguments = data.Arguments; - this.exceptionData = data.ExceptionData; - - if (data.HasExpectedResult) - this.ExpectedResult = data.ExpectedResult; - - foreach (string key in data.Properties.Keys) - this.Properties[key] = data.Properties[key]; - } - - #endregion - - #region IApplyToTest Members - - /// - /// Applies ParameterSet values to the test itself. - /// - /// A test. - public void ApplyToTest(Test test) - { - if (this.RunState != RunState.Runnable) - test.RunState = this.RunState; - - foreach (string key in Properties.Keys) - foreach (object value in Properties[key]) - test.Properties.Add(key, value); - - TestMethod testMethod = test as TestMethod; - if (testMethod != null && exceptionData.ExpectedExceptionName != null) - testMethod.CustomDecorators.Add(new ExpectedExceptionDecorator(this.ExceptionData)); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/PlatformHelper.cs b/test/NUnitLite/src/framework/Internal/PlatformHelper.cs deleted file mode 100644 index 9ff4fa7a1..000000000 --- a/test/NUnitLite/src/framework/Internal/PlatformHelper.cs +++ /dev/null @@ -1,298 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Internal -{ - /// - /// PlatformHelper class is used by the PlatformAttribute class to - /// determine whether a platform is supported. - /// - public class PlatformHelper - { - private OSPlatform os; - private RuntimeFramework rt; - - // Set whenever we fail to support a list of platforms - private string reason = string.Empty; - - /// - /// Comma-delimited list of all supported OS platform constants - /// - public static readonly string OSPlatforms = -#if (CLR_2_0 || CLR_4_0) && !NETCF - "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6,Win2K,WinXP,Win2003Server,Vista,Win2008Server,Win2008ServerR2,Win2012Server,Windows7,Windows8,Unix,Linux,Xbox,MacOSX"; -#else - "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6,Win2K,WinXP,Win2003Server,Vista,Win2008Server,Win2008ServerR2,Win2012Server,Windows7,Windows8,Unix,Linux"; -#endif - - /// - /// Comma-delimited list of all supported Runtime platform constants - /// - public static readonly string RuntimePlatforms = - "Net,NetCF,SSCLI,Rotor,Mono,MonoTouch"; - - /// - /// Default constructor uses the operating system and - /// common language runtime of the system. - /// - public PlatformHelper() - { - this.os = OSPlatform.CurrentPlatform; - this.rt = RuntimeFramework.CurrentFramework; - } - - /// - /// Contruct a PlatformHelper for a particular operating - /// system and common language runtime. Used in testing. - /// - /// OperatingSystem to be used - /// RuntimeFramework to be used - public PlatformHelper( OSPlatform os, RuntimeFramework rt ) - { - this.os = os; - this.rt = rt; - } - - /// - /// Test to determine if one of a collection of platforms - /// is being used currently. - /// - /// - /// - public bool IsPlatformSupported( string[] platforms ) - { - foreach( string platform in platforms ) - if ( IsPlatformSupported( platform ) ) - return true; - - return false; - } - - /// - /// Tests to determine if the current platform is supported - /// based on a platform attribute. - /// - /// The attribute to examine - /// - public bool IsPlatformSupported( PlatformAttribute platformAttribute ) - { - string include = platformAttribute.Include; - string exclude = platformAttribute.Exclude; - - try - { - if (include != null && !IsPlatformSupported(include)) - { - reason = string.Format("Only supported on {0}", include); - return false; - } - - if (exclude != null && IsPlatformSupported(exclude)) - { - reason = string.Format("Not supported on {0}", exclude); - return false; - } - } - catch (Exception ex) - { - reason = ex.Message; - return false; - } - - return true; - } - - /// - /// Test to determine if the a particular platform or comma- - /// delimited set of platforms is in use. - /// - /// Name of the platform or comma-separated list of platform names - /// True if the platform is in use on the system - public bool IsPlatformSupported( string platform ) - { - if ( platform.IndexOf( ',' ) >= 0 ) - return IsPlatformSupported( platform.Split( new char[] { ',' } ) ); - - string platformName = platform.Trim(); - bool isSupported = false; - -// string versionSpecification = null; -// -// string[] parts = platformName.Split( new char[] { '-' } ); -// if ( parts.Length == 2 ) -// { -// platformName = parts[0]; -// versionSpecification = parts[1]; -// } - - switch( platformName.ToUpper() ) - { - case "WIN": - case "WIN32": - isSupported = os.IsWindows; - break; - case "WIN32S": - isSupported = os.IsWin32S; - break; - case "WIN32WINDOWS": - isSupported = os.IsWin32Windows; - break; - case "WIN32NT": - isSupported = os.IsWin32NT; - break; - case "WINCE": - isSupported = os.IsWinCE; - break; - case "WIN95": - isSupported = os.IsWin95; - break; - case "WIN98": - isSupported = os.IsWin98; - break; - case "WINME": - isSupported = os.IsWinME; - break; - case "NT3": - isSupported = os.IsNT3; - break; - case "NT4": - isSupported = os.IsNT4; - break; - case "NT5": - isSupported = os.IsNT5; - break; - case "WIN2K": - isSupported = os.IsWin2K; - break; - case "WINXP": - isSupported = os.IsWinXP; - break; - case "WIN2003SERVER": - isSupported = os.IsWin2003Server; - break; - case "NT6": - isSupported = os.IsNT6; - break; - case "VISTA": - isSupported = os.IsVista; - break; - case "WIN2008SERVER": - isSupported = os.IsWin2008Server; - break; - case "WIN2008SERVERR2": - isSupported = os.IsWin2008ServerR2; - break; - case "WIN2012SERVER": - isSupported = os.IsWin2012Server; - break; - case "WINDOWS7": - isSupported = os.IsWindows7; - break; - case "WINDOWS8": - isSupported = os.IsWindows8; - break; - case "UNIX": - case "LINUX": - isSupported = os.IsUnix; - break; -#if (CLR_2_0 || CLR_4_0) && !NETCF - case "XBOX": - isSupported = os.IsXbox; - break; - case "MACOSX": - isSupported = os.IsMacOSX; - break; -#endif - - default: - isSupported = IsRuntimeSupported(platformName); - break; - } - - if (!isSupported) - this.reason = "Only supported on " + platform; - - return isSupported; - } - - /// - /// Return the last failure reason. Results are not - /// defined if called before IsSupported( Attribute ) - /// is called. - /// - public string Reason - { - get { return reason; } - } - - private bool IsRuntimeSupported(string platformName) - { - string versionSpecification = null; - string[] parts = platformName.Split(new char[] { '-' }); - if (parts.Length == 2) - { - platformName = parts[0]; - versionSpecification = parts[1]; - } - - switch (platformName.ToUpper()) - { - case "NET": - return IsRuntimeSupported(RuntimeType.Net, versionSpecification); - - case "NETCF": - return IsRuntimeSupported(RuntimeType.NetCF, versionSpecification); - - case "SSCLI": - case "ROTOR": - return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification); - - case "MONO": - return IsRuntimeSupported(RuntimeType.Mono, versionSpecification); - - case "SL": - case "SILVERLIGHT": - return IsRuntimeSupported(RuntimeType.Silverlight, versionSpecification); - - case "MONOTOUCH": - return IsRuntimeSupported(RuntimeType.MonoTouch, versionSpecification); - - default: - throw new ArgumentException("Invalid platform name", platformName); - } - } - - private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification) - { - Version version = versionSpecification == null - ? RuntimeFramework.DefaultVersion - : new Version(versionSpecification); - - RuntimeFramework target = new RuntimeFramework(runtime, version); - - return rt.Supports(target); - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/PropertyBag.cs b/test/NUnitLite/src/framework/Internal/PropertyBag.cs deleted file mode 100644 index 75579577d..000000000 --- a/test/NUnitLite/src/framework/Internal/PropertyBag.cs +++ /dev/null @@ -1,462 +0,0 @@ -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// A PropertyBag represents a collection of name value pairs - /// that allows duplicate entries with the same key. Methods - /// are provided for adding a new pair as well as for setting - /// a key to a single value. All keys are strings but values - /// may be of any type. Null values are not permitted, since - /// a null entry represents the absence of the key. - /// - public class PropertyBag : IPropertyBag - { -#if CLR_2_0 || CLR_4_0 - private Dictionary inner = new Dictionary(); - - private bool TryGetValue(string key, out IList list) - { - return inner.TryGetValue(key, out list); - } -#else - private Hashtable inner = new Hashtable(); - - private bool TryGetValue(string key, out IList list) - { - list = inner.ContainsKey(key) - ? (IList)inner[key] - : null; - - return list != null; - } -#endif - - /// - /// Adds a key/value pair to the property set - /// - /// The key - /// The value - public void Add(string key, object value) - { - IList list; - if (!TryGetValue(key, out list)) - { - list = new ObjectList(); - inner.Add(key, list); - } - list.Add(value); - } - - /// - /// Sets the value for a key, removing any other - /// values that are already in the property set. - /// - /// - /// - public void Set(string key, object value) - { - IList list = new ObjectList(); - list.Add(value); - inner[key] = list; - } - - /// - /// Gets a single value for a key, using the first - /// one if multiple values are present and returning - /// null if the value is not found. - /// - /// - /// - public object Get(string key) - { - IList list; - return TryGetValue(key, out list) && list.Count > 0 - ? list[0] - : null; - } - - /// - /// Gets a single boolean value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - /// - /// - /// - public bool GetSetting(string key, bool defaultValue) - { - object value = Get(key); - return value == null - ? defaultValue - : (bool)value; - } - - /// - /// Gets a single string value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - /// - /// - /// - public string GetSetting(string key, string defaultValue) - { - object value = Get(key); - return value == null - ? defaultValue - : (string)value; - } - - /// - /// Gets a single int value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - /// - /// - /// - public int GetSetting(string key, int defaultValue) - { - object value = Get(key); - return value == null - ? defaultValue - : (int)value; - } - - /// - /// Gets a single Enum value for a key, using the first - /// one if multiple values are present and returning the - /// default value if no entry is found. - /// - /// - /// - /// - public Enum GetSetting(string key, Enum defaultValue) - { - object value = Get(key); - return value == null - ? defaultValue - : (Enum)value; - } - - /// - /// Clears this instance. - /// - public void Clear() - { - inner.Clear(); - } - - /// - /// Removes all entries for a key from the property set - /// - /// The key for which the entries are to be removed - public void Remove(string key) - { - inner.Remove(key); - } - - /// - /// Removes a single entry if present. If not found, - /// no error occurs. - /// - /// - /// - public void Remove(string key, object value) - { - IList list; - if (TryGetValue(key, out list)) - list.Remove(value); - } - - /// - /// Removes a specific PropertyEntry. If the entry is not - /// found, no errr occurs. - /// - /// The property entry to remove - public void Remove(PropertyEntry entry) - { - Remove(entry.Name, entry.Value); - } - - /// - /// Get the number of key/value pairs in the property set - /// - /// - public int Count - { - get - { - int count = 0; - - foreach (string key in inner.Keys) - count += ((IList)inner[key]).Count; - - return count; - } - } - - /// - /// Gets a flag indicating whether the specified key has - /// any entries in the property set. - /// - /// The key to be checked - /// - /// True if their are values present, otherwise false - /// - public bool ContainsKey(string key) - { - return inner.ContainsKey(key); - } - - /// - /// Gets a flag indicating whether the specified key and - /// value are present in the property set. - /// - /// The key to be checked - /// The value to be checked - /// - /// True if the key and value are present, otherwise false - /// - public bool Contains(string key, object value) - { - IList list; - return TryGetValue(key, out list) && list.Contains(value); - } - - /// - /// Gets a flag indicating whether the specified key and - /// value are present in the property set. - /// - /// The property entry to be checked - /// - /// True if the entry is present, otherwise false - /// - public bool Contains(PropertyEntry entry) - { - return Contains(entry.Name, entry.Value); - } - - /// - /// Gets a collection containing all the keys in the property set - /// - /// -#if CLR_2_0 || CLR_4_0 - public ICollection Keys -#else - public ICollection Keys -#endif - { - get { return inner.Keys; } - } - - /// - /// Gets an enumerator for all properties in the property bag - /// - /// - public IEnumerator GetEnumerator() - { - return new PropertyBagEnumerator(this); - } - - /// - /// Gets or sets the list of values for a particular key - /// - public IList this[string key] - { - get - { - IList list; - if (!TryGetValue(key, out list)) - { - list = new ObjectList(); - inner.Add(key, list); - } - return list; - } - set - { - inner[key] = value; - } - } - - #region IXmlNodeBuilder Members - - /// - /// Returns an XmlNode representating the current PropertyBag. - /// - /// Not used - /// An XmlNode representing the PropertyBag - public XmlNode ToXml(bool recursive) - { - //XmlResult topNode = XmlResult.CreateTopLevelElement("dummy"); - - XmlNode thisNode = AddToXml(new XmlNode("dummy"), recursive); - - return thisNode; - } - - /// - /// Returns an XmlNode representing the PropertyBag after - /// adding it as a child of the supplied parent node. - /// - /// The parent node. - /// Not used - /// - public XmlNode AddToXml(XmlNode parentNode, bool recursive) - { - XmlNode properties = parentNode.AddElement("properties"); - - foreach (string key in Keys) - { - foreach (object value in this[key]) - { - XmlNode prop = properties.AddElement("property"); - - // TODO: Format as string - prop.AddAttribute("name", key.ToString()); - prop.AddAttribute("value", value.ToString()); - } - } - - return properties; - } - - #endregion - - #region Nested PropertyBagEnumerator Class - - /// - /// TODO: Documentation needed for class - /// -#if CLR_2_0 || CLR_4_0 - public class PropertyBagEnumerator : IEnumerator - { - private IEnumerator> innerEnum; -#else - public class PropertyBagEnumerator : IEnumerator - { - private IEnumerator innerEnum; -#endif - private PropertyBag bag; - private IEnumerator valueEnum; - - /// - /// - /// - /// - public PropertyBagEnumerator(PropertyBag bag) - { - this.bag = bag; - - Initialize(); - } - - private void Initialize() - { - innerEnum = bag.inner.GetEnumerator(); - valueEnum = null; - - if (innerEnum.MoveNext()) - { -#if CLR_2_0 || CLR_4_0 - valueEnum = innerEnum.Current.Value.GetEnumerator(); -#else - DictionaryEntry entry = (DictionaryEntry)innerEnum.Current; - valueEnum = ((IList)entry.Value).GetEnumerator(); -#endif - } - } - - private PropertyEntry GetCurrentEntry() - { - if (valueEnum == null) - throw new InvalidOperationException(); - -#if CLR_2_0 || CLR_4_0 - string key = innerEnum.Current.Key; -#else - DictionaryEntry entry = (DictionaryEntry)innerEnum.Current; - string key = (string)entry.Key; -#endif - - object value = valueEnum.Current; - - return new PropertyEntry(key, value); - } - - #region IEnumerator Members - -#if CLR_2_0 || CLR_4_0 - PropertyEntry IEnumerator.Current - { - get - { - return GetCurrentEntry(); - } - } -#endif - - #endregion - - #region IDisposable Members - -#if CLR_2_0 || CLR_4_0 - void IDisposable.Dispose() - { - } -#endif - - #endregion - - #region IEnumerator Members - - object IEnumerator.Current - { - get - { - return GetCurrentEntry(); - } - } - - bool IEnumerator.MoveNext() - { - if (valueEnum == null) - return false; - - while (!valueEnum.MoveNext()) - { - if (!innerEnum.MoveNext()) - { - valueEnum = null; - return false; - } - -#if CLR_2_0 || CLR_4_0 - valueEnum = innerEnum.Current.Value.GetEnumerator(); -#else - DictionaryEntry entry = (DictionaryEntry)innerEnum.Current; - valueEnum = ((IList)entry.Value).GetEnumerator(); -#endif - } - - return true; - } - - void IEnumerator.Reset() - { - Initialize(); - } - - #endregion - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/PropertyNames.cs b/test/NUnitLite/src/framework/Internal/PropertyNames.cs deleted file mode 100644 index 13cc572b2..000000000 --- a/test/NUnitLite/src/framework/Internal/PropertyNames.cs +++ /dev/null @@ -1,102 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Internal -{ - /// - /// The PropertyNames class provides static constants for the - /// standard property names that NUnit uses on tests. - /// - public class PropertyNames - { - /// - /// The Description of a test - /// - public static readonly string Description = "Description"; - - /// - /// The reason a test was not run - /// - public static readonly string SkipReason = "_SKIPREASON"; - - /// - /// The stack trace from any data provider that threw - /// an exception. - /// - public static readonly string ProviderStackTrace = "_PROVIDERSTACKTRACE"; - - /// - /// The culture to be set for a test - /// - public static readonly string SetCulture = "SetCulture"; - - /// - /// The UI culture to be set for a test - /// - public static readonly string SetUICulture = "SetUICulture"; - - /// - /// The categories applying to a test - /// - public static readonly string Category = "Category"; - -#if !NUNITLITE - /// - /// The ApartmentState required for running the test - /// - public static readonly string ApartmentState = "ApartmentState"; -#endif - - /// - /// The timeout value for the test - /// - public static readonly string Timeout = "Timeout"; - - /// - /// The number of times the test should be repeated - /// - public static readonly string RepeatCount = "Repeat"; - - /// - /// The maximum time in ms, above which the test is considered to have failed - /// - public static readonly string MaxTime = "MaxTime"; - - /// - /// The selected strategy for joining parameter data into test cases - /// - public static readonly string JoinType = "_JOINTYPE"; - - /// - /// The process ID of the executing assembly - /// - public static readonly string ProcessID = "_PID"; - - /// - /// The FriendlyName of the AppDomain in which the assembly is running - /// - public static readonly string AppDomain = "_APPDOMAIN"; - } -} diff --git a/test/NUnitLite/src/framework/Internal/RandomGenerator.cs b/test/NUnitLite/src/framework/Internal/RandomGenerator.cs deleted file mode 100644 index 87c440012..000000000 --- a/test/NUnitLite/src/framework/Internal/RandomGenerator.cs +++ /dev/null @@ -1,196 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -using System; - -namespace NUnit.Framework.Internal -{ - /// - /// RandomGenerator returns a set of random values in a repeatable - /// way, to allow re-running of tests if necessary. - /// - /// This class is internal to the framework but exposed externally to through the TestContext - /// the class is used to allow for obtaining repeatable random values during a tests execution. - /// this class should not be used inside the framework only with a TestMethod. - /// - public class RandomGenerator - { - #region Members & Constructor - /// - /// Seed for the wrapped Random - /// - public readonly int seed; - - private Random random; - - /// - /// Lazy-loaded Random built on the readonly Seed - /// - private Random Rand - { - get - { - random = random == null ? new Random(seed) : random; - return random; - } - } - - /// - /// Constructor requires Seed value in order to store it for use in Random creation - /// - /// - public RandomGenerator(int seed) - { - this.seed = seed; - } - #endregion - - #region Ints - /// - /// Get Next Integer from Random - /// - /// int - public int GetInt() - { - return Rand.Next(); - } - /// - /// Get Next Integer within the specified min & max from Random - /// - /// - /// - /// int - public int GetInt(int min, int max) - { - return Rand.Next(min, max); - } - #endregion - - #region Shorts - /// - /// Get Next Short from Random - /// - /// short - public short GetShort() - { - return (short)Rand.Next(short.MinValue, short.MaxValue); - } - /// - /// Get Next Short within the specified min & max from Random - /// - /// - /// - /// short - public short GetShort(short min, short max) - { - return (short)Rand.Next(min, max); - } - #endregion - - #region Bytes - /// - /// Get Next Byte from Random - /// - /// byte - public byte GetByte() - { - return (byte)Rand.Next(Byte.MinValue, Byte.MaxValue); - } - /// - /// Get Next Byte within the specified min & max from Random - /// - /// - /// - /// byte - public byte GetByte(byte min, byte max) - { - return (byte)Rand.Next(min, max); - } - #endregion - - #region Bools - /// - /// Get Random Boolean value - /// - /// bool - public bool GetBool() - { - return Rand.Next(0, 2) == 0; - } - /// - /// Get Random Boolean value based on the probability of that value being true - /// - /// - /// bool - public bool GetBool(double probability) - { - return Rand.NextDouble() < Math.Abs(probability % 1.0); - } - #endregion - - #region Double & Float - /// - /// Get Next Double from Random - /// - /// - public double GetDouble() - { - return Rand.NextDouble(); - } - /// - /// Get Next Float from Random - /// - /// - public float GetFloat() - { - return (float)Rand.NextDouble(); - } - #endregion - - #region Enums -#if CLR_2_0 || CLR_4_0 - /// - /// Return a random enum value representation of the specified Type - /// - /// - /// T - public T GetEnum() - { - Array enums = TypeHelper.GetEnumValues(typeof(T)); - return (T)enums.GetValue(Rand.Next(0, enums.Length)); - } -#else - /// - /// Return a random enum value from the specified type - /// - /// - /// object - public object GetEnum(Type enumType) - { - Array enums = TypeHelper.GetEnumValues(enumType); - return enums.GetValue(Rand.Next(0, enums.Length)); - } -#endif - #endregion - - } -} diff --git a/test/NUnitLite/src/framework/Internal/Randomizer.cs b/test/NUnitLite/src/framework/Internal/Randomizer.cs deleted file mode 100644 index f0d824591..000000000 --- a/test/NUnitLite/src/framework/Internal/Randomizer.cs +++ /dev/null @@ -1,187 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; - -namespace NUnit.Framework.Internal -{ - /// - /// Randomizer returns a set of random values in a repeatable - /// way, to allow re-running of tests if necessary. - /// - /// This class is an internal framework class used for setting up tests. - /// It is used to generate random test parameters, at the time of loading - /// the tests. It also generates seeds for use at execution time, when - /// creating a RandomGenerator for use by the test. - /// - public class Randomizer : Random - { - #region Static Members - - private static int initialSeed = new Random().Next(); - - private static Random seedGenerator; - -#if CLR_2_0 || CLR_4_0 - private static Dictionary randomizers = new Dictionary(); -#else - private static System.Collections.Hashtable randomizers = new System.Collections.Hashtable(); -#endif - - /// - /// Initial seed used to create randomizers for this run - /// - public static int InitialSeed - { - get { return initialSeed; } - set { initialSeed = value; } - } - - /// - /// Get a randomizer for a particular member, returning - /// one that has already been created if it exists. - /// This ensures that the same values are generated - /// each time the tests are reloaded. - /// - public static Randomizer GetRandomizer(MemberInfo member) - { - if (randomizers.ContainsKey(member)) - return (Randomizer)randomizers[member]; - else - { - Randomizer r = CreateRandomizer(); - randomizers[member] = r; - return (Randomizer)r; - } - } - - /// - /// Get a randomizer for a particular parameter, returning - /// one that has already been created if it exists. - /// This ensures that the same values are generated - /// each time the tests are reloaded. - /// - public static Randomizer GetRandomizer(ParameterInfo parameter) - { - return GetRandomizer(parameter.Member); - } - - /// - /// Create a new Randomizer using the next seed - /// available to ensure that each randomizer gives - /// a unique sequence of values. - /// - /// - public static Randomizer CreateRandomizer() - { - if (seedGenerator == null) - seedGenerator = new Random(initialSeed); - - return new Randomizer(seedGenerator.Next()); - } - - #endregion - - #region Constructor - - /// - /// Construct a randomizer using a specified seed - /// - public Randomizer(int seed) : base(seed) { } - - #endregion - - #region Public Methods - /// - /// Return an array of random doubles between 0.0 and 1.0. - /// - /// - /// - public double[] GetDoubles(int count) - { - double[] rvals = new double[count]; - - for (int index = 0; index < count; index++) - rvals[index] = NextDouble(); - - return rvals; - } - - /// - /// Return an array of random Enums - /// - /// - /// - /// - public object[] GetEnums(int count, Type enumType) - { - if (!enumType.IsEnum) - throw new ArgumentException(string.Format("The specified type: {0} was not an enum", enumType)); - -#if !NETCF && !SILVERLIGHT - Array values = Enum.GetValues(enumType); -#else - Array values = TypeHelper.GetEnumValues(enumType); -#endif - object[] rvals = new Enum[count]; - - for (int index = 0; index < count; index++) - rvals[index] = values.GetValue(Next(values.Length)); - - return rvals; - } - - /// - /// Return an array of random doubles with values in a specified range. - /// - public double[] GetDoubles(double min, double max, int count) - { - double range = max - min; - double[] rvals = new double[count]; - - for (int index = 0; index < count; index++) - rvals[index] = NextDouble() * range + min; - - return rvals; - } - - /// - /// Return an array of random ints with values in a specified range. - /// - public int[] GetInts(int min, int max, int count) - { - int[] ivals = new int[count]; - - for (int index = 0; index < count; index++) - ivals[index] = Next(min, max); - - return ivals; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Reflect.cs b/test/NUnitLite/src/framework/Internal/Reflect.cs deleted file mode 100644 index 20f0d9b34..000000000 --- a/test/NUnitLite/src/framework/Internal/Reflect.cs +++ /dev/null @@ -1,249 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007-2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; - -namespace NUnit.Framework.Internal -{ - /// - /// Helper methods for inspecting a type by reflection. - /// - /// Many of these methods take ICustomAttributeProvider as an - /// argument to avoid duplication, even though certain attributes can - /// only appear on specific types of members, like MethodInfo or Type. - /// - /// In the case where a type is being examined for the presence of - /// an attribute, interface or named member, the Reflect methods - /// operate with the full name of the member being sought. This - /// removes the necessity of the caller having a reference to the - /// assembly that defines the item being sought and allows the - /// NUnit core to inspect assemblies that reference an older - /// version of the NUnit framework. - /// - public class Reflect - { - private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; - - // A zero-length Type array - not provided by System.Type for all CLR versions we support. - private static readonly Type[] EmptyTypes = new Type[0]; - - #region Get Methods of a type - - /// - /// Examine a fixture type and return an array of methods having a - /// particular attribute. The array is order with base methods first. - /// - /// The type to examine - /// The attribute Type to look for - /// Specifies whether to search the fixture type inheritance chain - /// The array of methods found - public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit) - { - MethodInfoList list = new MethodInfoList(); - - foreach (MethodInfo method in fixtureType.GetMethods(AllMembers)) - { - if (method.IsDefined(attributeType, inherit)) - list.Add(method); - } - - list.Sort(new BaseTypesFirstComparer()); - - return list.ToArray(); - } - -#if CLR_2_0 || CLR_4_0 - private class BaseTypesFirstComparer : IComparer - { - public int Compare(MethodInfo m1, MethodInfo m2) - { - if (m1 == null || m2 == null) return 0; - - Type m1Type = m1.DeclaringType; - Type m2Type = m2.DeclaringType; - - if ( m1Type == m2Type ) return 0; - if ( m1Type.IsAssignableFrom(m2Type) ) return -1; - - return 1; - } - } -#else - private class BaseTypesFirstComparer : IComparer - { - public int Compare(object x, object y) - { - MethodInfo m1 = x as MethodInfo; - MethodInfo m2 = y as MethodInfo; - - if (m1 == null || m2 == null) return 0; - - Type m1Type = m1.DeclaringType; - Type m2Type = m2.DeclaringType; - - if (m1Type == m2Type) return 0; - if (m1Type.IsAssignableFrom(m2Type)) return -1; - - return 1; - } - } -#endif - - /// - /// Examine a fixture type and return true if it has a method with - /// a particular attribute. - /// - /// The type to examine - /// The attribute Type to look for - /// Specifies whether to search the fixture type inheritance chain - /// True if found, otherwise false - public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType) - { - foreach (MethodInfo method in fixtureType.GetMethods(AllMembers)) - { - if (method.IsDefined(attributeType, false)) - return true; - } - - return false; - } - - #endregion - - #region Invoke Constructors - - /// - /// Invoke the default constructor on a Type - /// - /// The Type to be constructed - /// An instance of the Type - public static object Construct(Type type) - { - ConstructorInfo ctor = type.GetConstructor(EmptyTypes); - if (ctor == null) - throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor"); - - return ctor.Invoke(null); - } - - /// - /// Invoke a constructor on a Type with arguments - /// - /// The Type to be constructed - /// Arguments to the constructor - /// An instance of the Type - public static object Construct(Type type, object[] arguments) - { - if (arguments == null) return Construct(type); - - Type[] argTypes = GetTypeArray(arguments); - ConstructorInfo ctor = type.GetConstructor(argTypes); - if (ctor == null) - throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor"); - - return ctor.Invoke(arguments); - } - - /// - /// Returns an array of types from an array of objects. - /// Used because the compact framework doesn't support - /// Type.GetTypeArray() - /// - /// An array of objects - /// An array of Types - private static Type[] GetTypeArray(object[] objects) - { - Type[] types = new Type[objects.Length]; - int index = 0; - foreach (object o in objects) - types[index++] = o.GetType(); - return types; - } - - #endregion - - #region Invoke Methods - - /// - /// Invoke a parameterless method returning void on an object. - /// - /// A MethodInfo for the method to be invoked - /// The object on which to invoke the method - public static object InvokeMethod( MethodInfo method, object fixture ) - { - return InvokeMethod( method, fixture, null ); - } - - /// - /// Invoke a method, converting any TargetInvocationException to an NUnitException. - /// - /// A MethodInfo for the method to be invoked - /// The object on which to invoke the method - /// The argument list for the method - /// The return value from the invoked method - public static object InvokeMethod( MethodInfo method, object fixture, params object[] args ) - { - if(method != null) - { - try - { - return method.Invoke( fixture, args ); - } - catch(Exception e) - { - if (e is TargetInvocationException) - throw new NUnitException("Rethrown", e.InnerException); - else - throw new NUnitException("Rethrown", e); - } - } - - return null; - } - - #endregion - - #region Private Constructor for static-only class - - private Reflect() { } - - #endregion - -#if CLR_2_0 || CLR_4_0 - class MethodInfoList : List { } -#else - class MethodInfoList : ArrayList - { - public new MethodInfo[] ToArray() - { - return (MethodInfo[])base.ToArray(typeof(MethodInfo)); - } - } -#endif - } -} diff --git a/test/NUnitLite/src/framework/Internal/Results/TestCaseResult.cs b/test/NUnitLite/src/framework/Internal/Results/TestCaseResult.cs deleted file mode 100644 index 481180277..000000000 --- a/test/NUnitLite/src/framework/Internal/Results/TestCaseResult.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// Represents the result of running a single test case. - /// - public class TestCaseResult : TestResult - { - /// - /// Construct a TestCaseResult based on a TestMethod - /// - /// A TestMethod to which the result applies. - public TestCaseResult(TestMethod test) : base(test) { } - - /// - /// Gets the number of test cases that failed - /// when running the test and all its children. - /// - public override int FailCount - { - get { return ResultState.Status == TestStatus.Failed ? 1 : 0; } - } - - /// - /// Gets the number of test cases that passed - /// when running the test and all its children. - /// - public override int PassCount - { - get { return ResultState.Status == TestStatus.Passed ? 1 : 0; } - } - - /// - /// Gets the number of test cases that were skipped - /// when running the test and all its children. - /// - public override int SkipCount - { - get { return ResultState.Status == TestStatus.Skipped ? 1 : 0; } - } - - /// - /// Gets the number of test cases that were inconclusive - /// when running the test and all its children. - /// - public override int InconclusiveCount - { - get { return ResultState.Status == TestStatus.Inconclusive ? 1 : 0; } - } - - //public override XmlNode AddToXml(XmlNode parentNode, bool recursive) - //{ - // XmlNode thisNode = this.test.AddToXml(parentNode, recursive); - // //thisNode.AddAttribute("seed", this.test.Seed.ToString()); - // return thisNode; - //} - } -} diff --git a/test/NUnitLite/src/framework/Internal/Results/TestResult.cs b/test/NUnitLite/src/framework/Internal/Results/TestResult.cs deleted file mode 100644 index ae293ddcf..000000000 --- a/test/NUnitLite/src/framework/Internal/Results/TestResult.cs +++ /dev/null @@ -1,467 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// The TestResult class represents the result of a test. - /// - public abstract class TestResult : ITestResult - { - #region Fields - - /// - /// Indicates the result of the test - /// - [CLSCompliant(false)] - protected ResultState resultState; - - /// - /// The elapsed time for executing this test - /// - private TimeSpan time = TimeSpan.Zero; - - /// - /// The test that this result pertains to - /// - [CLSCompliant(false)] - protected readonly ITest test; - - /// - /// The stacktrace at the point of failure - /// - private string stackTrace; - - /// - /// Message giving the reason for failure, error or skipping the test - /// - [CLSCompliant(false)] - protected string message; - - /// - /// Number of asserts executed by this test - /// - [CLSCompliant(false)] - protected int assertCount = 0; - - /// - /// List of child results - /// -#if CLR_2_0 || CLR_4_0 - private System.Collections.Generic.List children; -#else - private System.Collections.ArrayList children; -#endif - - #endregion - - #region Constructor - - /// - /// Construct a test result given a Test - /// - /// The test to be used - public TestResult(ITest test) - { - this.test = test; - this.resultState = ResultState.Inconclusive; - } - - #endregion - - #region ITestResult Members - - /// - /// Gets the test with which this result is associated. - /// - public ITest Test - { - get { return test; } - } - - /// - /// Gets the ResultState of the test result, which - /// indicates the success or failure of the test. - /// - public ResultState ResultState - { - get { return resultState; } - } - - /// - /// Gets the name of the test result - /// - public virtual string Name - { - get { return test.Name; } - } - - /// - /// Gets the full name of the test result - /// - public virtual string FullName - { - get { return test.FullName; } - } - - /// - /// Gets or sets the elapsed time for running the test - /// - public TimeSpan Duration - { - get { return time; } - set { time = value; } - } - - /// - /// Gets the message associated with a test - /// failure or with not running the test - /// - public string Message - { - get { return message; } - } - - /// - /// Gets any stacktrace associated with an - /// error or failure. Not available in - /// the Compact Framework 1.0. - /// - public virtual string StackTrace - { - get { return stackTrace; } - } - - /// - /// Gets or sets the count of asserts executed - /// when running the test. - /// - public int AssertCount - { - get { return assertCount; } - set { assertCount = value; } - } - - /// - /// Gets the number of test cases that failed - /// when running the test and all its children. - /// - public abstract int FailCount { get; } - - /// - /// Gets the number of test cases that passed - /// when running the test and all its children. - /// - public abstract int PassCount { get; } - - /// - /// Gets the number of test cases that were skipped - /// when running the test and all its children. - /// - public abstract int SkipCount { get; } - - /// - /// Gets the number of test cases that were inconclusive - /// when running the test and all its children. - /// - public abstract int InconclusiveCount { get; } - - /// - /// Indicates whether this result has any child results. - /// Test HasChildren before accessing Children to avoid - /// the creation of an empty collection. - /// - public bool HasChildren - { - get { return children != null && children.Count > 0; } - } - - /// - /// Gets the collection of child results. - /// -#if CLR_2_0 || CLR_4_0 - public System.Collections.Generic.IList Children - { - get - { - if (children == null) - children = new System.Collections.Generic.List(); - - return children; - } - } -#else - public System.Collections.IList Children - { - get - { - if (children == null) - children = new System.Collections.ArrayList(); - - return children; - } - } -#endif - - #endregion - - #region IXmlNodeBuilder Members - - /// - /// Returns the Xml representation of the result. - /// - /// If true, descendant results are included - /// An XmlNode representing the result - public XmlNode ToXml(bool recursive) - { - XmlNode topNode = XmlNode.CreateTopLevelElement("dummy"); - - AddToXml(topNode, recursive); - - return topNode.FirstChild; - } - - /// - /// Adds the XML representation of the result as a child of the - /// supplied parent node.. - /// - /// The parent node. - /// If true, descendant results are included - /// - public virtual XmlNode AddToXml(XmlNode parentNode, bool recursive) - { - // A result node looks like a test node with extra info added - XmlNode thisNode = this.test.AddToXml(parentNode, false); - - thisNode.AddAttribute("result", ResultState.Status.ToString()); - if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString()) - thisNode.AddAttribute("label", ResultState.Label); - - thisNode.AddAttribute("time", this.Duration.ToString()); - - if (this.test is TestSuite) - { - thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString()); - thisNode.AddAttribute("passed", PassCount.ToString()); - thisNode.AddAttribute("failed", FailCount.ToString()); - thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString()); - thisNode.AddAttribute("skipped", SkipCount.ToString()); - } - - thisNode.AddAttribute("asserts", this.AssertCount.ToString()); - - switch (ResultState.Status) - { - case TestStatus.Failed: - AddFailureElement(thisNode); - break; - case TestStatus.Skipped: - AddReasonElement(thisNode); - break; - case TestStatus.Passed: - case TestStatus.Inconclusive: - if (this.Message != null) - AddReasonElement(thisNode); - break; - } - - if (recursive && HasChildren) - foreach (TestResult child in Children) - child.AddToXml(thisNode, recursive); - - return thisNode; - } - - #endregion - - #region Other Public Methods - - /// - /// Add a child result - /// - /// The child result to be added - public virtual void AddResult(TestResult result) - { - this.Children.Add(result); - - this.assertCount += result.AssertCount; - - switch (result.ResultState.Status) - { - case TestStatus.Passed: - - if (this.resultState.Status == TestStatus.Inconclusive) - SetResult(ResultState.Success); - - break; - - case TestStatus.Failed: - - if (this.resultState.Status != TestStatus.Failed) - SetResult(ResultState.Failure, "One or more child tests had errors"); - - break; - - case TestStatus.Skipped: - - switch (result.ResultState.Label) - { - case "Invalid": - - if (this.ResultState != ResultState.NotRunnable && this.ResultState.Status != TestStatus.Failed) - SetResult(ResultState.Failure, "One or more child tests had errors"); - - break; - - case "Ignored": - - if (this.ResultState.Status == TestStatus.Inconclusive || this.ResultState.Status == TestStatus.Passed) - SetResult(ResultState.Ignored, "One or more child tests were ignored"); - - break; - - default: - - // Tests skipped for other reasons do not change the outcome - // of the containing suite when added. - - break; - } - - break; - - case TestStatus.Inconclusive: - - // An inconclusive result does not change the outcome - // of the containing suite when added. - - break; - } - } - - /// - /// Set the result of the test - /// - /// The ResultState to use in the result - public void SetResult(ResultState resultState) - { - SetResult(resultState, null, null); - } - - /// - /// Set the result of the test - /// - /// The ResultState to use in the result - /// A message associated with the result state - public void SetResult(ResultState resultState, string message) - { - SetResult(resultState, message, null); - } - - /// - /// Set the result of the test - /// - /// The ResultState to use in the result - /// A message associated with the result state - /// Stack trace giving the location of the command - public void SetResult(ResultState resultState, string message, string stackTrace) - { - this.resultState = resultState; - this.message = message; - this.stackTrace = stackTrace; - } - - /// - /// Set the test result based on the type of exception thrown - /// - /// The exception that was thrown - public void RecordException(Exception ex) - { - if (ex is NUnitException) - ex = ex.InnerException; - - if (ex is System.Threading.ThreadAbortException) - SetResult(ResultState.Cancelled, "Test cancelled by user", ex.StackTrace); - else if (ex is AssertionException) - SetResult(ResultState.Failure, ex.Message, StackFilter.Filter(ex.StackTrace)); - else if (ex is IgnoreException) - SetResult(ResultState.Ignored, ex.Message, StackFilter.Filter(ex.StackTrace)); - else if (ex is InconclusiveException) - SetResult(ResultState.Inconclusive, ex.Message, StackFilter.Filter(ex.StackTrace)); - else if (ex is SuccessException) - SetResult(ResultState.Success, ex.Message, StackFilter.Filter(ex.StackTrace)); - else - SetResult(ResultState.Error, - ExceptionHelper.BuildMessage(ex), - ExceptionHelper.BuildStackTrace(ex)); - } - - #endregion - - #region Helper Methods - - /// - /// Adds a reason element to a node and returns it. - /// - /// The target node. - /// The new reason element. - private XmlNode AddReasonElement(XmlNode targetNode) - { - XmlNode reasonNode = targetNode.AddElement("reason"); - reasonNode.AddElement("message").TextContent = this.Message; - return reasonNode; - } - - /// - /// Adds a failure element to a node and returns it. - /// - /// The target node. - /// The new failure element. - private XmlNode AddFailureElement(XmlNode targetNode) - { - XmlNode failureNode = targetNode.AddElement("failure"); - - if (this.Message != null) - { - failureNode.AddElement("message").TextContent = this.Message; - } - - if (this.StackTrace != null) - { - failureNode.AddElement("stack-trace").TextContent = this.StackTrace; - } - - return failureNode; - } - - //private static bool IsTestCase(ITest test) - //{ - // return !(test is TestSuite); - //} - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Results/TestSuiteResult.cs b/test/NUnitLite/src/framework/Internal/Results/TestSuiteResult.cs deleted file mode 100644 index 6c09a318e..000000000 --- a/test/NUnitLite/src/framework/Internal/Results/TestSuiteResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// Represents the result of running a test suite - /// - public class TestSuiteResult : TestResult - { - private int passCount = 0; - private int failCount = 0; - private int skipCount = 0; - private int inconclusiveCount = 0; - - /// - /// Construct a TestSuiteResult base on a TestSuite - /// - /// The TestSuite to which the result applies - public TestSuiteResult(TestSuite suite) : base(suite) { } - - /// - /// Gets the number of test cases that failed - /// when running the test and all its children. - /// - public override int FailCount - { - get { return this.failCount; } - } - - /// - /// Gets the number of test cases that passed - /// when running the test and all its children. - /// - public override int PassCount - { - get { return this.passCount; } - } - - /// - /// Gets the number of test cases that were skipped - /// when running the test and all its children. - /// - public override int SkipCount - { - get { return this.skipCount; } - } - - /// - /// Gets the number of test cases that were inconclusive - /// when running the test and all its children. - /// - public override int InconclusiveCount - { - get { return this.inconclusiveCount; } - } - - /// - /// Add a child result - /// - /// The child result to be added - public override void AddResult(TestResult result) - { - base.AddResult(result); - - this.passCount += result.PassCount; - this.failCount += result.FailCount; - this.skipCount += result.SkipCount; - this.inconclusiveCount += result.InconclusiveCount; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/RuntimeFramework.cs b/test/NUnitLite/src/framework/Internal/RuntimeFramework.cs deleted file mode 100644 index 8ca395bc6..000000000 --- a/test/NUnitLite/src/framework/Internal/RuntimeFramework.cs +++ /dev/null @@ -1,396 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.IO; -using System.Reflection; -using Microsoft.Win32; - -namespace NUnit.Framework.Internal -{ - /// - /// Enumeration identifying a common language - /// runtime implementation. - /// - public enum RuntimeType - { - /// Any supported runtime framework - Any, - /// Microsoft .NET Framework - Net, - /// Microsoft .NET Compact Framework - NetCF, - /// Microsoft Shared Source CLI - SSCLI, - /// Mono - Mono, - /// Silverlight - Silverlight, - /// MonoTouch - MonoTouch - } - - /// - /// RuntimeFramework represents a particular version - /// of a common language runtime implementation. - /// - [Serializable] - public sealed class RuntimeFramework - { - #region Static and Instance Fields - - /// - /// DefaultVersion is an empty Version, used to indicate that - /// NUnit should select the CLR version to use for the test. - /// - public static readonly Version DefaultVersion = new Version(0,0); - - private static RuntimeFramework currentFramework; - - private RuntimeType runtime; - private Version frameworkVersion; - private Version clrVersion; - private string displayName; - #endregion - - #region Constructor - - /// - /// Construct from a runtime type and version. If the version has - /// two parts, it is taken as a framework version. If it has three - /// or more, it is taken as a CLR version. In either case, the other - /// version is deduced based on the runtime type and provided version. - /// - /// The runtime type of the framework - /// The version of the framework - public RuntimeFramework( RuntimeType runtime, Version version) - { - this.runtime = runtime; - - this.frameworkVersion = runtime == RuntimeType.Mono && version.Major == 1 - ? new Version(1, 0) - : new Version(version.Major, version.Minor); - this.clrVersion = version; - - if (version.Build < 0) - this.clrVersion = GetClrVersion(runtime, version); - - this.displayName = GetDefaultDisplayName(runtime, version); - } - - private static Version GetClrVersion(RuntimeType runtime, Version version) - { - switch (runtime) - { - case RuntimeType.Silverlight: - return version.Major >= 4 - ? new Version(4, 0, 60310) - : new Version(2, 0, 50727); - - default: - switch (version.Major) - { - case 4: - return new Version(4, 0, 30319); - - case 2: - case 3: - return new Version(2, 0, 50727); - - case 1: - return version.Minor == 0 && runtime != RuntimeType.Mono - ? new Version(1, 0, 3705) - : new Version(1, 1, 4322); - - default: - return version; - } - } - } - - #endregion - - #region Properties - /// - /// Static method to return a RuntimeFramework object - /// for the framework that is currently in use. - /// - public static RuntimeFramework CurrentFramework - { - get - { - if (currentFramework == null) - { -#if SILVERLIGHT - currentFramework = new RuntimeFramework( - RuntimeType.Silverlight, - new Version(Environment.Version.Major, Environment.Version.Minor)); -#else - Type monoRuntimeType = Type.GetType("Mono.Runtime", false); - Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate, monotouch"); - bool isMonoTouch = monoTouchType != null; - bool isMono = monoRuntimeType != null; - - RuntimeType runtime = isMonoTouch - ? RuntimeType.MonoTouch - : isMono - ? RuntimeType.Mono - : Environment.OSVersion.Platform == PlatformID.WinCE - ? RuntimeType.NetCF - : RuntimeType.Net; - - int major = Environment.Version.Major; - int minor = Environment.Version.Minor; - - if (isMono) - { - switch (major) - { - case 1: - minor = 0; - break; - case 2: - major = 3; - minor = 5; - break; - } - } - else /* It's windows */ - if (major == 2) - { - RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"); - if (key != null) - { - string installRoot = key.GetValue("InstallRoot") as string; - if (installRoot != null) - { - if (Directory.Exists(Path.Combine(installRoot, "v3.5"))) - { - major = 3; - minor = 5; - } - else if (Directory.Exists(Path.Combine(installRoot, "v3.0"))) - { - major = 3; - minor = 0; - } - } - } - } - - currentFramework = new RuntimeFramework(runtime, new Version(major, minor)); - currentFramework.clrVersion = Environment.Version; - - if (isMono) - { - MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod( - "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding); - if (getDisplayNameMethod != null) - currentFramework.displayName = (string)getDisplayNameMethod.Invoke(null, new object[0]); - } -#endif - } - - return currentFramework; - } - } - - /// - /// The type of this runtime framework - /// - public RuntimeType Runtime - { - get { return runtime; } - } - - /// - /// The framework version for this runtime framework - /// - public Version FrameworkVersion - { - get { return frameworkVersion; } - } - - /// - /// The CLR version for this runtime framework - /// - public Version ClrVersion - { - get { return clrVersion; } - } - - /// - /// Return true if any CLR version may be used in - /// matching this RuntimeFramework object. - /// - public bool AllowAnyVersion - { - get { return this.clrVersion == DefaultVersion; } - } - - /// - /// Returns the Display name for this framework - /// - public string DisplayName - { - get { return displayName; } - } - - #endregion - - #region Public Methods - - /// - /// Parses a string representing a RuntimeFramework. - /// The string may be just a RuntimeType name or just - /// a Version or a hyphentated RuntimeType-Version or - /// a Version prefixed by 'v'. - /// - /// - /// - public static RuntimeFramework Parse(string s) - { - RuntimeType runtime = RuntimeType.Any; - Version version = DefaultVersion; - - string[] parts = s.Split(new char[] { '-' }); - if (parts.Length == 2) - { - runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true); - string vstring = parts[1]; - if (vstring != "") - version = new Version(vstring); - } - else if (char.ToLower(s[0]) == 'v') - { - version = new Version(s.Substring(1)); - } - else if (IsRuntimeTypeName(s)) - { - runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true); - } - else - { - version = new Version(s); - } - - return new RuntimeFramework(runtime, version); - } - - /// - /// Overridden to return the short name of the framework - /// - /// - public override string ToString() - { - if (this.AllowAnyVersion) - { - return runtime.ToString().ToLower(); - } - else - { - string vstring = frameworkVersion.ToString(); - if (runtime == RuntimeType.Any) - return "v" + vstring; - else - return runtime.ToString().ToLower() + "-" + vstring; - } - } - - /// - /// Returns true if the current framework matches the - /// one supplied as an argument. Two frameworks match - /// if their runtime types are the same or either one - /// is RuntimeType.Any and all specified version components - /// are equal. Negative (i.e. unspecified) version - /// components are ignored. - /// - /// The RuntimeFramework to be matched. - /// True on match, otherwise false - public bool Supports(RuntimeFramework target) - { - if (this.Runtime != RuntimeType.Any - && target.Runtime != RuntimeType.Any - && this.Runtime != target.Runtime) - return false; - - if (this.AllowAnyVersion || target.AllowAnyVersion) - return true; - - if (!VersionsMatch(this.ClrVersion, target.ClrVersion)) - return false; - - return Runtime == RuntimeType.Silverlight - ? this.frameworkVersion.Major == target.FrameworkVersion.Major && this.frameworkVersion.Minor == target.FrameworkVersion.Minor - : this.FrameworkVersion.Major >= target.FrameworkVersion.Major && this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor; - } - - #endregion - - #region Helper Methods - - private static bool IsRuntimeTypeName(string name) - { - foreach (string item in TypeHelper.GetEnumNames(typeof(RuntimeType))) - if (item.ToLower() == name.ToLower()) - return true; - - return false; - } - - private static string GetDefaultDisplayName(RuntimeType runtime, Version version) - { - if (version == DefaultVersion) - return runtime.ToString(); - else if (runtime == RuntimeType.Any) - return "v" + version.ToString(); - else - return runtime.ToString() + " " + version.ToString(); - } - - private static bool VersionsMatch(Version v1, Version v2) - { - return v1.Major == v2.Major && - v1.Minor == v2.Minor && - (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) && - (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision); - } - -#if CLR_2_0 || CLR_4_0 - class FrameworkList : System.Collections.Generic.List { } -#else - class FrameworkList : System.Collections.ArrayList - { - public new RuntimeFramework[] ToArray() - { - return (RuntimeFramework[])base.ToArray(typeof(RuntimeFramework)); - } - } -#endif - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/StackFilter.cs b/test/NUnitLite/src/framework/Internal/StackFilter.cs deleted file mode 100644 index 34d571b62..000000000 --- a/test/NUnitLite/src/framework/Internal/StackFilter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using System.IO; - -namespace NUnit.Framework.Internal -{ - /// - /// StackFilter class is used to remove internal NUnit - /// entries from a stack trace so that the resulting - /// trace provides better information about the test. - /// - public class StackFilter - { - /// - /// Filters a raw stack trace and returns the result. - /// - /// The original stack trace - /// A filtered stack trace - public static string Filter(string rawTrace) - { - if (rawTrace == null) return null; - - StringReader sr = new StringReader(rawTrace); - StringWriter sw = new StringWriter(); - - try - { - string line; - while ((line = sr.ReadLine()) != null && line.IndexOf("NUnit.Framework.Assert") >= 0) - /*Skip*/ - ; - - while (line != null) - { - sw.WriteLine(line); - line = sr.ReadLine(); - } - } - catch (Exception) - { - return rawTrace; - } - - return sw.ToString(); - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/StringUtil.cs b/test/NUnitLite/src/framework/Internal/StringUtil.cs deleted file mode 100644 index c98bc60e1..000000000 --- a/test/NUnitLite/src/framework/Internal/StringUtil.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; - -namespace NUnit.Framework.Internal -{ - /// - /// Provides methods to support legacy string comparison methods. - /// - public class StringUtil - { - /// - /// Compares two strings for equality, ignoring case if requested. - /// - /// The first string. - /// The second string.. - /// if set to true, the case of the letters in the strings is ignored. - /// Zero if the strings are equivalent, a negative number if strA is sorted first, a positive number if - /// strB is sorted first - public static int Compare(string strA, string strB, bool ignoreCase) - { -#if SILVERLIGHT - StringComparison comparison = ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture; - return string.Compare(strA, strB, comparison); -#else - return string.Compare(strA, strB, ignoreCase); -#endif - } - - /// - /// Compares two strings for equality, ignoring case if requested. - /// - /// The first string. - /// The second string.. - /// if set to true, the case of the letters in the strings is ignored. - /// True if the strings are equivalent, false if not. - public static bool StringsEqual(string strA, string strB, bool ignoreCase) - { - return Compare(strA, strB, ignoreCase) == 0; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/TestExecutionContext.cs b/test/NUnitLite/src/framework/Internal/TestExecutionContext.cs deleted file mode 100644 index e96ef740c..000000000 --- a/test/NUnitLite/src/framework/Internal/TestExecutionContext.cs +++ /dev/null @@ -1,568 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Collections.Specialized; -using System.IO; -using System.Diagnostics; -using System.Globalization; -using System.Threading; - -#if !NUNITLITE -using System.Security.Principal; -#endif - -using NUnit.Framework.Api; -#if !SILVERLIGHT && !NETCF -using System.Runtime.Remoting.Messaging; -#endif - -namespace NUnit.Framework.Internal -{ - /// - /// Helper class used to save and restore certain static or - /// singleton settings in the environment that affect tests - /// or which might be changed by the user tests. - /// - /// An internal class is used to hold settings and a stack - /// of these objects is pushed and popped as Save and Restore - /// are called. - /// - /// Static methods for each setting forward to the internal - /// object on the top of the stack. - /// - public class TestExecutionContext -#if !SILVERLIGHT && !NETCF - : ILogicalThreadAffinative -#endif - { - #region Instance Fields - - /// - /// Link to a prior saved context - /// - public TestExecutionContext prior; - - /// - /// The currently executing test - /// - private Test currentTest; - - /// - /// The time the test began execution - /// - private DateTime startTime; - - /// - /// The active TestResult for the current test - /// - private TestResult currentResult; - - /// - /// The work directory to receive test output - /// - private string workDirectory; - - /// - /// The object on which tests are currently being executed - i.e. the user fixture object - /// - private object testObject; - - /// - /// The event listener currently receiving notifications - /// - private ITestListener listener = TestListener.NULL; - - /// - /// The number of assertions for the current test - /// - private int assertCount; - - /// - /// Indicates whether execution should terminate after the first error - /// - private bool stopOnError; - - /// - /// Default timeout for test cases - /// - private int testCaseTimeout; - - private RandomGenerator randomGenerator; - -#if !NETCF && !SILVERLIGHT - /// - /// Destination for standard output - /// - private TextWriter outWriter; - - /// - /// Destination for standard error - /// - private TextWriter errorWriter; - - /// - /// Indicates whether trace is enabled - /// - private bool tracing; - - /// - /// Destination for Trace output - /// - private TextWriter traceWriter; -#endif - -#if !NUNITLITE - /// - /// Indicates whether logging is enabled - /// - private bool logging; - - /// - /// The current working directory - /// - private string currentDirectory; - - private Log4NetCapture logCapture; - - /// - /// The current Principal. - /// - private IPrincipal currentPrincipal; -#endif - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - public TestExecutionContext() - { - this.prior = null; - this.testCaseTimeout = 0; - -#if !NETCF && !SILVERLIGHT - this.outWriter = Console.Out; - this.errorWriter = Console.Error; - this.traceWriter = null; - this.tracing = false; -#endif - -#if !NUNITLITE - this.logging = false; - this.currentDirectory = Environment.CurrentDirectory; - this.logCapture = new Log4NetCapture(); - this.currentPrincipal = Thread.CurrentPrincipal; -#endif - } - - /// - /// Initializes a new instance of the class. - /// - /// An existing instance of TestExecutionContext. - public TestExecutionContext( TestExecutionContext other ) - { - this.prior = other; - - this.currentTest = other.currentTest; - this.currentResult = other.currentResult; - this.testObject = other.testObject; - this.workDirectory = other.workDirectory; - this.listener = other.listener; - this.stopOnError = other.stopOnError; - this.testCaseTimeout = other.testCaseTimeout; - -#if !NETCF && !SILVERLIGHT - this.outWriter = other.outWriter; - this.errorWriter = other.errorWriter; - this.traceWriter = other.traceWriter; - this.tracing = other.tracing; -#endif - -#if !NUNITLITE - this.logging = other.logging; - this.currentDirectory = Environment.CurrentDirectory; - this.logCapture = other.logCapture; - this.currentPrincipal = Thread.CurrentPrincipal; -#endif - } - - #endregion - - #region Static Singleton Instance - - /// - /// The current context, head of the list of saved contexts. - /// -#if SILVERLIGHT || NETCF -#if (CLR_2_0 || CLR_4_0) && !NETCF - [ThreadStatic] -#endif - private static TestExecutionContext current; -#else - private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext"; -#endif - - /// - /// Gets the current context. - /// - /// The current context. - public static TestExecutionContext CurrentContext - { - get - { -#if SILVERLIGHT || NETCF - if (current == null) - current = new TestExecutionContext(); - - return current; -#else - return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext; -#endif - } - } - - #endregion - - #region Static Methods - - internal static void SetCurrentContext(TestExecutionContext ec) - { -#if SILVERLIGHT || NETCF - current = ec; -#else - CallContext.SetData(CONTEXT_KEY, ec); -#endif - } - - #endregion - - #region Properties - - /// - /// Gets or sets the current test - /// - public Test CurrentTest - { - get { return currentTest; } - set { currentTest = value; } - } - - /// - /// The time the current test started execution - /// - public DateTime StartTime - { - get { return startTime; } - set { startTime = value; } - } - - /// - /// Gets or sets the current test result - /// - public TestResult CurrentResult - { - get { return currentResult; } - set { currentResult = value; } - } - - /// - /// The current test object - that is the user fixture - /// object on which tests are being executed. - /// - public object TestObject - { - get { return testObject; } - set { testObject = value; } - } - - /// - /// Get or set the working directory - /// - public string WorkDirectory - { - get { return workDirectory; } - set { workDirectory = value; } - } - - /// - /// Get or set indicator that run should stop on the first error - /// - public bool StopOnError - { - get { return stopOnError; } - set { stopOnError = value; } - } - - /// - /// The current test event listener - /// - internal ITestListener Listener - { - get { return listener; } - set { listener = value; } - } - - /// - /// Gets the RandomGenerator specific to this Test - /// - public RandomGenerator RandomGenerator - { - get - { - if (randomGenerator == null) - { - randomGenerator = new RandomGenerator(currentTest.Seed); - } - return randomGenerator; - } - } - - /// - /// Gets the assert count. - /// - /// The assert count. - internal int AssertCount - { - get { return assertCount; } - set { assertCount = value; } - } - - /// - /// Gets or sets the test case timeout value - /// - public int TestCaseTimeout - { - get { return testCaseTimeout; } - set { testCaseTimeout = value; } - } - -#if !NETCF && !SILVERLIGHT - /// - /// Controls where Console.Out is directed - /// - internal TextWriter Out - { - get { return outWriter; } - set - { - if ( outWriter != value ) - { - outWriter = value; - Console.Out.Flush(); - Console.SetOut( outWriter ); - } - } - } - - /// - /// Controls where Console.Error is directed - /// - internal TextWriter Error - { - get { return errorWriter; } - set - { - if ( errorWriter != value ) - { - errorWriter = value; - Console.Error.Flush(); - Console.SetError( errorWriter ); - } - } - } - - /// - /// Controls whether trace and debug output are written - /// to the standard output. - /// - internal bool Tracing - { - get { return tracing; } - set - { - if (tracing != value) - { - if (traceWriter != null && tracing) - StopTracing(); - - tracing = value; - - if (traceWriter != null && tracing) - StartTracing(); - } - } - } - - /// - /// Controls where Trace output is directed - /// - internal TextWriter TraceWriter - { - get { return traceWriter; } - set - { - if ( traceWriter != value ) - { - if ( traceWriter != null && tracing ) - StopTracing(); - - traceWriter = value; - - if ( traceWriter != null && tracing ) - StartTracing(); - } - } - } - - private void StopTracing() - { - traceWriter.Close(); - System.Diagnostics.Trace.Listeners.Remove( "NUnit" ); - } - - private void StartTracing() - { - System.Diagnostics.Trace.Listeners.Add( new TextWriterTraceListener( traceWriter, "NUnit" ) ); - } -#endif - -#if !NUNITLITE - /// - /// Controls whether log output is captured - /// - public bool Logging - { - get { return logCapture.Enabled; } - set { logCapture.Enabled = value; } - } - - /// - /// Gets or sets the Log writer, which is actually held by a log4net - /// TextWriterAppender. When first set, the appender will be created - /// and will thereafter send any log events to the writer. - /// - /// In normal operation, LogWriter is set to an EventListenerTextWriter - /// connected to the EventQueue in the test domain. The events are - /// subsequently captured in the Gui an the output displayed in - /// the Log tab. The application under test does not need to define - /// any additional appenders. - /// - public TextWriter LogWriter - { - get { return logCapture.Writer; } - set { logCapture.Writer = value; } - } - - /// - /// Saves and restores the CurrentDirectory - /// - public string CurrentDirectory - { - get { return currentDirectory; } - set - { - currentDirectory = value; - Environment.CurrentDirectory = currentDirectory; - } - } - - /// - /// Gets or sets the current for the Thread. - /// - public IPrincipal CurrentPrincipal - { - get { return this.currentPrincipal; } - set - { - this.currentPrincipal = value; - Thread.CurrentPrincipal = this.currentPrincipal; - } - } -#endif - - #endregion - - #region Instance Methods - - /// - /// Saves the old context and returns a fresh one - /// with the same settings. - /// - public TestExecutionContext Save() - { - return new TestExecutionContext(this); - } - - /// - /// Restores the last saved context and puts - /// any saved settings back into effect. - /// - public TestExecutionContext Restore() - { - if (prior == null) - throw new InvalidOperationException("TestContext: too many Restores"); - - this.TestCaseTimeout = prior.TestCaseTimeout; - -#if !NETCF && !SILVERLIGHT - this.Out = prior.Out; - this.Error = prior.Error; - this.Tracing = prior.Tracing; -#endif - -#if !NUNITLITE - this.CurrentDirectory = prior.CurrentDirectory; - this.CurrentPrincipal = prior.CurrentPrincipal; -#endif - - return prior; - } - - /// - /// Record any changes in the environment made by - /// the test code in the execution context so it - /// will be passed on to lower level tests. - /// - public void UpdateContext() - { -#if !NUNITLITE - this.currentDirectory = Environment.CurrentDirectory; - this.currentPrincipal = System.Threading.Thread.CurrentPrincipal; -#endif - } - - /// - /// Increments the assert count. - /// - public void IncrementAssertCount() - { - System.Threading.Interlocked.Increment(ref assertCount); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/TestFilter.cs b/test/NUnitLite/src/framework/Internal/TestFilter.cs deleted file mode 100644 index b2bfee0ae..000000000 --- a/test/NUnitLite/src/framework/Internal/TestFilter.cs +++ /dev/null @@ -1,183 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// Interface to be implemented by filters applied to tests. - /// The filter applies when running the test, after it has been - /// loaded, since this is the only time an ITest exists. - /// - [Serializable] - public abstract class TestFilter : ITestFilter - { - /// - /// Unique Empty filter. - /// - public static TestFilter Empty = new EmptyFilter(); - - /// - /// Indicates whether this is the EmptyFilter - /// - public bool IsEmpty - { - get { return this is TestFilter.EmptyFilter; } - } - - /// - /// Determine if a particular test passes the filter criteria. The default - /// implementation checks the test itself, its parents and any descendants. - /// - /// Derived classes may override this method or any of the Match methods - /// to change the behavior of the filter. - /// - /// The test to which the filter is applied - /// True if the test passes the filter, otherwise false - public virtual bool Pass( ITest test ) - { - return Match(test) || MatchParent(test) || MatchDescendant(test); - } - - /// - /// Determine whether the test itself matches the filter criteria, without - /// examining either parents or descendants. - /// - /// The test to which the filter is applied - /// True if the filter matches the any parent of the test - public abstract bool Match(ITest test); - - /// - /// Determine whether any ancestor of the test matches the filter criteria - /// - /// The test to which the filter is applied - /// True if the filter matches the an ancestor of the test - protected virtual bool MatchParent(ITest test) - { - return (test.RunState != RunState.Explicit && test.Parent != null && - (Match(test.Parent) || MatchParent(test.Parent))); - } - - /// - /// Determine whether any descendant of the test matches the filter criteria. - /// - /// The test to be matched - /// True if at least one descendant matches the filter criteria - protected virtual bool MatchDescendant(ITest test) - { - if (test.Tests == null) - return false; - - foreach (ITest child in test.Tests) - { - if (Match(child) || MatchDescendant(child)) - return true; - } - - return false; - } - -#if !NUNITLITE - public static TestFilter FromXml(string xmlText) - { - XmlDocument doc = new XmlDocument(); - doc.LoadXml(xmlText); - XmlNode topNode = doc.FirstChild; - - if (topNode.Name != "filter") - throw new Exception("Expected filter element at top level"); - - // Initially, an empty filter - TestFilter result = TestFilter.Empty; - bool isEmptyResult = true; - - XmlNodeList testNodes = topNode.SelectNodes("tests/test"); - XmlNodeList includeNodes = topNode.SelectNodes("include/category"); - XmlNodeList excludeNodes = topNode.SelectNodes("exclude/category"); - - if (testNodes.Count > 0) - { - SimpleNameFilter nameFilter = new SimpleNameFilter(); - foreach (XmlNode testNode in topNode.SelectNodes("tests/test")) - nameFilter.Add(testNode.InnerText); - - result = nameFilter; - isEmptyResult = false; - } - - if (includeNodes.Count > 0) - { - //CategoryFilter includeFilter = new CategoryFilter(); - //foreach (XmlNode includeNode in includeNodes) - // includeFilter.AddCategory(includeNode.InnerText); - - // Temporarily just look at the first element - XmlNode includeNode = includeNodes[0]; - TestFilter includeFilter = new CategoryExpression(includeNode.InnerText).Filter; - - if (isEmptyResult) - result = includeFilter; - else - result = new AndFilter(result, includeFilter); - isEmptyResult = false; - } - - if (excludeNodes.Count > 0) - { - CategoryFilter categoryFilter = new CategoryFilter(); - foreach (XmlNode excludeNode in excludeNodes) - categoryFilter.AddCategory(excludeNode.InnerText); - TestFilter excludeFilter = new NotFilter(categoryFilter); - - if (isEmptyResult) - result = excludeFilter; - else - result = new AndFilter(result, excludeFilter); - isEmptyResult = false; - } - - return result; - } -#endif - - /// - /// Nested class provides an empty filter - one that always - /// returns true when called, unless the test is marked explicit. - /// - [Serializable] - private class EmptyFilter : TestFilter - { - public override bool Match( ITest test ) - { - return test.RunState != RunState.Explicit; - } - - public override bool Pass( ITest test ) - { - return test.RunState != RunState.Explicit; - } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/TestFixtureBuilder.cs b/test/NUnitLite/src/framework/Internal/TestFixtureBuilder.cs deleted file mode 100644 index 44a36e69b..000000000 --- a/test/NUnitLite/src/framework/Internal/TestFixtureBuilder.cs +++ /dev/null @@ -1,80 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Builders; - -namespace NUnit.Framework.Internal -{ - /// - /// TestFixtureBuilder contains static methods for building - /// TestFixtures from types. It uses builtin SuiteBuilders - /// and any installed extensions to do it. - /// - public class TestFixtureBuilder - { - private static Extensibility.ISuiteBuilder builder = new NUnitTestFixtureBuilder(); - - /// - /// Determines whether this instance [can build from] the specified type. - /// - /// The type. - /// - /// true if this instance [can build from] the specified type; otherwise, false. - /// - public static bool CanBuildFrom( Type type ) - { - return builder.CanBuildFrom(type); - } - - /// - /// Build a test fixture from a given type. - /// - /// The type to be used for the fixture - /// A TestSuite if the fixture can be built, null if not - public static Test BuildFrom( Type type ) - { - return builder.BuildFrom( type ); - } - - /// - /// Build a fixture from an object. - /// - /// The object to be used for the fixture - /// A TestSuite if fixture type can be built, null if not - public static Test BuildFrom( object fixture ) - { - Test suite = BuildFrom( fixture.GetType() ); - if( suite != null) - suite.Fixture = fixture; - return suite; - } - - /// - /// Private constructor to prevent instantiation - /// - private TestFixtureBuilder() { } - } -} diff --git a/test/NUnitLite/src/framework/Internal/TestListener.cs b/test/NUnitLite/src/framework/Internal/TestListener.cs deleted file mode 100644 index 14ee08209..000000000 --- a/test/NUnitLite/src/framework/Internal/TestListener.cs +++ /dev/null @@ -1,66 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// TestListener provides an implementation of ITestListener that - /// does nothing. It is used only throught its NULL property. - /// - public class TestListener : ITestListener - { - /// - /// Called when a test has just started - /// - /// The test that is starting - public void TestStarted(ITest test){} - - /// - /// Called when a test case has finished - /// - /// The result of the test - public void TestFinished(ITestResult result){} - - /// - /// Called when the test creates text output. - /// - /// A console message - public void TestOutput(TestOutput testOutput) {} - - /// - /// Construct a new TestListener - private so it may not be used. - /// - private TestListener() { } - - /// - /// Get a listener that does nothing - /// - public static ITestListener NULL - { - get { return new TestListener();} - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/ParameterizedFixtureSuite.cs b/test/NUnitLite/src/framework/Internal/Tests/ParameterizedFixtureSuite.cs deleted file mode 100644 index d9257992d..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/ParameterizedFixtureSuite.cs +++ /dev/null @@ -1,71 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Internal -{ - /// - /// ParameterizedFixtureSuite serves as a container for the set of test - /// fixtures created from a given Type using various parameters. - /// - public class ParameterizedFixtureSuite : TestSuite - { - private Type type; - - /// - /// Initializes a new instance of the class. - /// - /// The type. - public ParameterizedFixtureSuite(Type type) : base(type.Namespace, TypeHelper.GetDisplayName(type)) - { - this.type = type; - } - - /// - /// Gets the Type represented by this suite. - /// - /// A Sysetm.Type. - public Type ParameterizedType - { - get { return type; } - } - - /// - /// Gets a string representing the type of test - /// - /// - public override string TestType - { - get - { -#if CLR_2_0 || CLR_4_0 - if (this.ParameterizedType.ContainsGenericParameters) - return "GenericFixture"; -#endif - - return "ParameterizedFixture"; - } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/ParameterizedMethodSuite.cs b/test/NUnitLite/src/framework/Internal/Tests/ParameterizedMethodSuite.cs deleted file mode 100644 index 444fbe3ac..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/ParameterizedMethodSuite.cs +++ /dev/null @@ -1,95 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Reflection; -using NUnit.Framework.Internal.Commands; - -namespace NUnit.Framework.Internal -{ - /// - /// ParameterizedMethodSuite holds a collection of individual - /// TestMethods with their arguments applied. - /// - public class ParameterizedMethodSuite : TestSuite - { - private MethodInfo _method; - private bool _isTheory; - - /// - /// Construct from a MethodInfo - /// - /// - public ParameterizedMethodSuite(MethodInfo method) - : base(method.ReflectedType.FullName, method.Name) - { - _method = method; - _isTheory = method.IsDefined(typeof(TheoryAttribute), true); - this.maintainTestOrder = true; - } - - /// - /// Gets the MethodInfo for which this suite is being built. - /// - public MethodInfo Method - { - get { return _method; } - } - - /// - /// Gets a string representing the type of test - /// - /// - public override string TestType - { - get - { - if (_isTheory) - return "Theory"; - -#if CLR_2_0 || CLR_4_0 - if (this.Method.ContainsGenericParameters) - return "GenericMethod"; -#endif - - return "ParameterizedMethod"; - } - } - - /// - /// Gets the command to be executed after all the child - /// tests are run. Overridden in ParameterizedMethodSuite - /// to set the result to failure if all the child tests - /// were inconclusive. - /// - /// - public override TestCommand GetOneTimeTearDownCommand() - { - TestCommand command = base.GetOneTimeTearDownCommand(); - - if (_isTheory) - command = new TheoryResultCommand(command); - - return command; - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/Test.cs b/test/NUnitLite/src/framework/Internal/Tests/Test.cs deleted file mode 100644 index a07773168..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/Test.cs +++ /dev/null @@ -1,416 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Internal.WorkItems; - -namespace NUnit.Framework.Internal -{ - /// - /// The Test abstract class represents a test within the framework. - /// - public abstract class Test : ITest, IComparable - { - #region Fields - - /// - /// Static value to seed ids. It's started at 1000 so any - /// uninitialized ids will stand out. - /// - private static int nextID = 1000; - - private int id; - private string name; - private string fullName; - private int seed; - - /// - /// Indicates whether the test should be executed - /// - private RunState runState; - - /// - /// Test suite containing this test, or null - /// - private ITest parent; - - /// - /// A dictionary of properties, used to add information - /// to tests without requiring the class to change. - /// - private PropertyBag properties; - - /// - /// The System.Type of the fixture for this test, if there is one - /// - private Type fixtureType; - - /// - /// The fixture object, if it has been created - /// - private object fixture; - - /// - /// The SetUp methods. - /// - protected MethodInfo[] setUpMethods; - - /// - /// The teardown methods - /// - protected MethodInfo[] tearDownMethods; - - #endregion - - #region Construction - - /// - /// Constructs a test given its name - /// - /// The name of the test - protected Test( string name ) - { - this.fullName = name; - this.name = name; - this.id = unchecked(nextID++); - - this.runState = RunState.Runnable; - } - - /// - /// Constructs a test given the path through the - /// test hierarchy to its parent and a name. - /// - /// The parent tests full name - /// The name of the test - protected Test( string pathName, string name ) - { - this.fullName = pathName == null || pathName == string.Empty - ? name : pathName + "." + name; - this.name = name; - this.id = unchecked(nextID++); - - this.runState = RunState.Runnable; - } - - /// - /// TODO: Documentation needed for constructor - /// - /// - protected Test(Type fixtureType) : this(fixtureType.FullName) - { - this.fixtureType = fixtureType; - } - - #endregion - - #region ITest Members - - /// - /// Gets or sets the id of the test - /// - /// - public int Id - { - get { return id; } - set { id = value; } - } - - /// - /// Gets or sets the name of the test - /// - public string Name - { - get { return name; } - set { name = value; } - } - - /// - /// Gets or sets the fully qualified name of the test - /// - /// - public string FullName - { - get { return fullName; } - set { fullName = value; } - } - - /// - /// Gets the Type of the fixture used in running this test - /// or null if no fixture type is associated with it. - /// - public Type FixtureType - { - get { return fixtureType; } - } - - /// - /// Whether or not the test should be run - /// - public RunState RunState - { - get { return runState; } - set { runState = value; } - } - - /// - /// Gets the name used for the top-level element in the - /// XML representation of this test - /// - public abstract string XmlElementName - { - get; - } - - /// - /// Gets a string representing the type of test. Used as an attribute - /// value in the XML representation of a test and has no other - /// function in the framework. - /// - public virtual string TestType - { - get { return this.GetType().Name; } - } - - /// - /// Gets a count of test cases represented by - /// or contained under this test. - /// - public virtual int TestCaseCount - { - get { return 1; } - } - - /// - /// Gets the properties for this test - /// - public IPropertyBag Properties - { - get - { - if ( properties == null ) - properties = new PropertyBag(); - - return properties; - } - } - - /// - /// Returns true if this is a TestSuite - /// - public bool IsSuite - { - get { return this is TestSuite; } - } - - /// - /// Gets a bool indicating whether the current test - /// has any descendant tests. - /// - public abstract bool HasChildren { get; } - - /// - /// Gets the parent as a Test object. - /// Used by the core to set the parent. - /// - public ITest Parent - { - get { return parent; } - set { parent = value; } - } - - /// - /// Gets or Sets the Int value representing the seed for the RandomGenerator - /// - /// - public int Seed - { - get { return seed; } - set { seed = value; } - } - - /// - /// Gets this test's child tests - /// - /// A list of child tests - -#if CLR_2_0 || CLR_4_0 - public abstract System.Collections.Generic.IList Tests { get; } -#else - public abstract System.Collections.IList Tests { get; } -#endif - - #endregion - - #region IXmlNodeBuilder Members - - /// - /// Returns the Xml representation of the test - /// - /// If true, include child tests recursively - /// - public XmlNode ToXml(bool recursive) - { - XmlNode topNode = XmlNode.CreateTopLevelElement("dummy"); - - XmlNode thisNode = AddToXml(topNode, recursive); - - return thisNode; - } - - /// - /// Returns an XmlNode representing the current result after - /// adding it as a child of the supplied parent node. - /// - /// The parent node. - /// If true, descendant results are included - /// - public abstract XmlNode AddToXml(XmlNode parentNode, bool recursive); - - #endregion - - #region IComparable Members - - /// - /// Compares this test to another test for sorting purposes - /// - /// The other test - /// Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test - public int CompareTo(object obj) - { - Test other = obj as Test; - - if (other == null) - return -1; - - return this.FullName.CompareTo(other.FullName); - } - - #endregion - - #region Other Public Methods - - /// - /// Creates a TestResult for this test. - /// - /// A TestResult suitable for this type of test. - public abstract TestResult MakeTestResult(); - - /// - /// Creates a WorkItem for executing this test. - /// - /// A filter to be used in selecting child tests - /// A new WorkItem - public abstract WorkItem CreateWorkItem(ITestFilter childFilter); - - /// - /// Modify a newly constructed test by applying any of NUnit's common - /// attributes, based on a supplied ICustomAttributeProvider, which is - /// usually the reflection element from which the test was constructed, - /// but may not be in some instances. The attributes retrieved are - /// saved for use in subsequent operations. - /// - /// An object implementing ICustomAttributeProvider - public void ApplyAttributesToTest(ICustomAttributeProvider provider) - { - foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true)) - iApply.ApplyToTest(this); - } - - #endregion - - #region Protected Methods - - /// - /// Add standard attributes and members to a test node. - /// - /// - /// - protected void PopulateTestNode(XmlNode thisNode, bool recursive) - { - thisNode.AddAttribute("id", this.Id.ToString()); - thisNode.AddAttribute("name", this.Name); - thisNode.AddAttribute("fullname", this.FullName); - - if (Properties.Count > 0) - Properties.AddToXml(thisNode, recursive); - } - - #endregion - - #region Internal Properties - - /// - /// Gets or sets a fixture object for running this test. - /// Provided for use by LegacySuiteBuilder. - /// - public object Fixture - { - get { return fixture; } - set { fixture = value; } - } - - /// - /// Gets the set up methods. - /// - /// - internal virtual MethodInfo[] SetUpMethods - { - get - { - if (setUpMethods == null && this.Parent != null) - { - TestSuite suite = this.Parent as TestSuite; - if (suite != null) - setUpMethods = suite.SetUpMethods; - } - - return setUpMethods; - } - } - - /// - /// Gets the tear down methods. - /// - /// - internal virtual MethodInfo[] TearDownMethods - { - get - { - if (tearDownMethods == null && this.Parent != null) - { - TestSuite suite = this.Parent as TestSuite; - if (suite != null) - tearDownMethods = suite.TearDownMethods; - } - - return tearDownMethods; - } - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/TestAssembly.cs b/test/NUnitLite/src/framework/Internal/Tests/TestAssembly.cs deleted file mode 100644 index b50ec7ddd..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/TestAssembly.cs +++ /dev/null @@ -1,57 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.IO; -using System.Reflection; - -namespace NUnit.Framework.Internal -{ - /// - /// TestAssembly is a TestSuite that represents the execution - /// of tests in a managed assembly. - /// - public class TestAssembly : TestSuite - { - /// - /// Initializes a new instance of the class. - /// - /// The assembly containing the tests. - /// The path used to load the assembly. - public TestAssembly(Assembly assembly, string path) : base(path) - { - this.Name = Path.GetFileName(path); - } - - /// - /// Gets the name used for the top-level element in the - /// XML representation of this test - /// - public override string TestType - { - get - { - return "Assembly"; - } - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/TestFixture.cs b/test/NUnitLite/src/framework/Internal/Tests/TestFixture.cs deleted file mode 100644 index d5c6d7360..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/TestFixture.cs +++ /dev/null @@ -1,60 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - /// - /// TestFixture is a surrogate for a user test fixture class, - /// containing one or more tests. - /// - public class TestFixture : TestSuite - { - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// Type of the fixture. - public TestFixture(Type fixtureType) - : this(fixtureType, null) { } - - /// - /// Initializes a new instance of the class. - /// - /// Type of the fixture. - /// The arguments. - public TestFixture(Type fixtureType, object[] arguments) - : base(fixtureType, arguments) - { - this.setUpMethods = Reflect.GetMethodsWithAttribute(FixtureType, typeof(SetUpAttribute), true); - this.tearDownMethods = Reflect.GetMethodsWithAttribute(FixtureType, typeof(TearDownAttribute), true); - } - - #endregion - - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/TestMethod.cs b/test/NUnitLite/src/framework/Internal/Tests/TestMethod.cs deleted file mode 100644 index e4fa1099b..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/TestMethod.cs +++ /dev/null @@ -1,268 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Internal.WorkItems; - -namespace NUnit.Framework.Internal -{ - /// - /// The TestMethod class represents a Test implemented as a method. - /// Because of how exceptions are handled internally, this class - /// must incorporate processing of expected exceptions. A change to - /// the Test interface might make it easier to process exceptions - /// in an object that aggregates a TestMethod in the future. - /// - public class TestMethod : Test - { - #region Fields - - /// - /// The test method - /// - internal MethodInfo method; - - /// - /// A list of all decorators applied to the test by attributes or parameterset arguments - /// -#if CLR_2_0 || CLR_4_0 - private List decorators = new List(); -#else - private System.Collections.ArrayList decorators = new System.Collections.ArrayList(); -#endif - - /// - /// The ParameterSet used to create this test method - /// - internal ParameterSet parms; - - #endregion - - #region Constructor - - /// - /// Initializes a new instance of the class. - /// - /// The method to be used as a test. - /// The suite or fixture to which the new test will be added - public TestMethod(MethodInfo method, Test parentSuite) - : base( method.ReflectedType ) - { - this.Name = method.Name; - this.FullName += "." + this.Name; - - // Disambiguate call to base class methods - // TODO: This should not be here - it's a presentation issue - if( method.DeclaringType != method.ReflectedType) - this.Name = method.DeclaringType.Name + "." + method.Name; - - // Needed to give proper fullname to test in a parameterized fixture. - // Without this, the arguments to the fixture are not included. - string prefix = method.ReflectedType.FullName; - if (parentSuite != null) - { - prefix = parentSuite.FullName; - this.FullName = prefix + "." + this.Name; - } - - this.method = method; - } - - #endregion - - #region Properties - - /// - /// Gets the method. - /// - /// The method that performs the test. - public MethodInfo Method - { - get { return method; } - } - - /// - /// Gets a list of custom decorators for this test. - /// -#if CLR_2_0 || CLR_4_0 - public IList CustomDecorators -#else - public System.Collections.IList CustomDecorators -#endif - { - get { return decorators; } - } - - internal bool HasExpectedResult - { - get { return parms != null && parms.HasExpectedResult; } - } - - internal object ExpectedResult - { - get { return parms != null ? parms.ExpectedResult : null; } - } - - internal object[] Arguments - { - get { return parms != null ? parms.Arguments : null; } - } - - internal bool IsAsync - { - get - { -#if NET_4_5 - return method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false); -#else - return false; -#endif - } - } - - #endregion - - #region Test Overrides - - /// - /// Overridden to return a TestCaseResult. - /// - /// A TestResult for this test. - public override TestResult MakeTestResult() - { - return new TestCaseResult(this); - } - - /// - /// Gets a bool indicating whether the current test - /// has any descendant tests. - /// - public override bool HasChildren - { - get { return false; } - } - - /// - /// Returns an XmlNode representing the current result after - /// adding it as a child of the supplied parent node. - /// - /// The parent node. - /// If true, descendant results are included - /// - public override XmlNode AddToXml(XmlNode parentNode, bool recursive) - { - XmlNode thisNode = parentNode.AddElement(XmlElementName); - - PopulateTestNode(thisNode, recursive); - - thisNode.AddAttribute("seed", this.Seed.ToString()); - - return thisNode; - } - - /// - /// Gets this test's child tests - /// - /// A list of child tests -#if CLR_2_0 || CLR_4_0 - public override IList Tests -#else - public override System.Collections.IList Tests -#endif - { - get { return new ITest[0]; } - } - - /// - /// Gets the name used for the top-level element in the - /// XML representation of this test - /// - public override string XmlElementName - { - get { return "test-case"; } - } - - /// - /// Creates a test command for use in running this test. - /// - /// - public virtual TestCommand MakeTestCommand() - { - if (RunState != RunState.Runnable && RunState != RunState.Explicit) - return new SkipCommand(this); - - TestCommand command = new TestMethodCommand(this); - - command = ApplyDecoratorsToCommand(command); - - IApplyToContext[] changes = (IApplyToContext[])this.Method.GetCustomAttributes(typeof(IApplyToContext), true); - if (changes.Length > 0) - command = new ApplyChangesToContextCommand(command, changes); - - return command; - } - - /// - /// Creates a WorkItem for executing this test. - /// - /// A filter to be used in selecting child tests - /// A new WorkItem - public override WorkItem CreateWorkItem(ITestFilter childFilter) - { - // For simple test cases, we ignore the filter - return new SimpleWorkItem(this); - } - - #endregion - - #region Helper Methods - - private TestCommand ApplyDecoratorsToCommand(TestCommand command) - { - CommandDecoratorList decorators = new CommandDecoratorList(); - - // Add Standard stuff - decorators.Add(new SetUpTearDownDecorator()); - - // Add Decorators supplied by attributes and parameter sets - foreach (ICommandDecorator decorator in CustomDecorators) - decorators.Add(decorator); - - decorators.OrderByStage(); - - foreach (ICommandDecorator decorator in decorators) - { - command = decorator.Decorate(command); - } - - return command; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/Tests/TestSuite.cs b/test/NUnitLite/src/framework/Internal/Tests/TestSuite.cs deleted file mode 100644 index 96589f460..000000000 --- a/test/NUnitLite/src/framework/Internal/Tests/TestSuite.cs +++ /dev/null @@ -1,317 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#else -using System.Collections; -#endif -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Internal.WorkItems; - -namespace NUnit.Framework.Internal -{ - /// - /// TestSuite represents a composite test, which contains other tests. - /// - public class TestSuite : Test - { - #region Fields - - /// - /// Our collection of child tests - /// -#if CLR_2_0 || CLR_4_0 - private List tests = new List(); -#else - private ArrayList tests = new ArrayList(); -#endif - - /// - /// Set to true to suppress sorting this suite's contents - /// - protected bool maintainTestOrder; - - /// - /// Argument list for use in creating the fixture. - /// - internal object[] arguments; - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The name of the suite. - public TestSuite( string name ) - : base( name ) { } - - /// - /// Initializes a new instance of the class. - /// - /// Name of the parent suite. - /// The name of the suite. - public TestSuite( string parentSuiteName, string name ) - : base( parentSuiteName, name ) { } - - /// - /// Initializes a new instance of the class. - /// - /// Type of the fixture. - public TestSuite(Type fixtureType) - : this(fixtureType, null) { } - - /// - /// Initializes a new instance of the class. - /// - /// Type of the fixture. - /// The arguments. - public TestSuite(Type fixtureType, object[] arguments) - : base(fixtureType) - { - string name = TypeHelper.GetDisplayName(fixtureType, arguments); - this.Name = name; - - this.FullName = name; - string nspace = fixtureType.Namespace; - if (nspace != null && nspace != "") - this.FullName = nspace + "." + name; - this.arguments = arguments; - } - - #endregion - - #region Public Methods - - /// - /// Sorts tests under this suite. - /// - public void Sort() - { - if (!maintainTestOrder) - { - this.tests.Sort(); - - foreach (Test test in Tests) - { - TestSuite suite = test as TestSuite; - if (suite != null) - suite.Sort(); - } - } - } - -#if false - /// - /// Sorts tests under this suite using the specified comparer. - /// - /// The comparer. - public void Sort(IComparer comparer) - { - this.tests.Sort(comparer); - - foreach( Test test in Tests ) - { - TestSuite suite = test as TestSuite; - if ( suite != null ) - suite.Sort(comparer); - } - } -#endif - - /// - /// Adds a test to the suite. - /// - /// The test. - public void Add( Test test ) - { -// if( test.RunState == RunState.Runnable ) -// { -// test.RunState = this.RunState; -// test.IgnoreReason = this.IgnoreReason; -// } - test.Parent = this; - tests.Add(test); - } - -#if !NUNITLITE - /// - /// Adds a pre-constructed test fixture to the suite. - /// - /// The fixture. - public void Add( object fixture ) - { - Test test = TestFixtureBuilder.BuildFrom( fixture ); - if ( test != null ) - Add( test ); - } -#endif - - /// - /// Gets the command to be executed before any of - /// the child tests are run. - /// - /// A TestCommand - public virtual TestCommand GetOneTimeSetUpCommand() - { - if (RunState != RunState.Runnable && RunState != RunState.Explicit) - return new SkipCommand(this); - - TestCommand command = new OneTimeSetUpCommand(this); - - if (this.FixtureType != null) - { - IApplyToContext[] changes = (IApplyToContext[])this.FixtureType.GetCustomAttributes(typeof(IApplyToContext), true); - if (changes.Length > 0) - command = new ApplyChangesToContextCommand(command, changes); - } - - return command; - } - - /// - /// Gets the command to be executed after all of the - /// child tests are run. - /// - /// A TestCommand - public virtual TestCommand GetOneTimeTearDownCommand() - { - TestCommand command = new OneTimeTearDownCommand(this); - - return command; - } - - #endregion - - #region Properties - - /// - /// Gets this test's child tests - /// - /// The list of child tests -#if CLR_2_0 || CLR_4_0 - public override IList Tests -#else - public override IList Tests -#endif - { - get { return tests; } - } - - /// - /// Gets a count of test cases represented by - /// or contained under this test. - /// - /// - public override int TestCaseCount - { - get - { - int count = 0; - - foreach(Test test in Tests) - { - count += test.TestCaseCount; - } - return count; - } - } - - #endregion - - #region Test Overrides - - /// - /// Overridden to return a TestSuiteResult. - /// - /// A TestResult for this test. - public override TestResult MakeTestResult() - { - return new TestSuiteResult(this); - } - - /// - /// Creates a WorkItem for executing this test. - /// - /// A filter to be used in selecting child tests - /// A new WorkItem - public override WorkItem CreateWorkItem(ITestFilter childFilter) - { - //return RunState == Api.RunState.Runnable || RunState == Api.RunState.Explicit - // ? (WorkItem)new CompositeWorkItem(this, childFilter) - // : (WorkItem)new SimpleWorkItem(this); - return new CompositeWorkItem(this, childFilter); - } - - /// - /// Gets a bool indicating whether the current test - /// has any descendant tests. - /// - public override bool HasChildren - { - get - { - return tests.Count > 0; - } - } - - /// - /// Gets the name used for the top-level element in the - /// XML representation of this test - /// - public override string XmlElementName - { - get { return "test-suite"; } - } - - /// - /// Returns an XmlNode representing the current result after - /// adding it as a child of the supplied parent node. - /// - /// The parent node. - /// If true, descendant results are included - /// - public override XmlNode AddToXml(XmlNode parentNode, bool recursive) - { - XmlNode thisNode = parentNode.AddElement("test-suite"); - thisNode.AddAttribute("type", this.TestType); - - PopulateTestNode(thisNode, recursive); - thisNode.AddAttribute("testcasecount", this.TestCaseCount.ToString()); - - - if (recursive) - foreach (Test test in this.Tests) - test.AddToXml(thisNode, recursive); - - return thisNode; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/TextMessageWriter.cs b/test/NUnitLite/src/framework/Internal/TextMessageWriter.cs deleted file mode 100644 index 1de2ca483..000000000 --- a/test/NUnitLite/src/framework/Internal/TextMessageWriter.cs +++ /dev/null @@ -1,489 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Globalization; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Internal -{ - /// - /// TextMessageWriter writes constraint descriptions and messages - /// in displayable form as a text stream. It tailors the display - /// of individual message components to form the standard message - /// format of NUnit assertion failure messages. - /// - public class TextMessageWriter : MessageWriter - { - #region Message Formats and Constants - private static readonly int DEFAULT_LINE_LENGTH = 78; - - // Prefixes used in all failure messages. All must be the same - // length, which is held in the PrefixLength field. Should not - // contain any tabs or newline characters. - /// - /// Prefix used for the expected value line of a message - /// - public static readonly string Pfx_Expected = " Expected: "; - /// - /// Prefix used for the actual value line of a message - /// - public static readonly string Pfx_Actual = " But was: "; - /// - /// Length of a message prefix - /// - public static readonly int PrefixLength = Pfx_Expected.Length; - - private static readonly string Fmt_Connector = " {0} "; - private static readonly string Fmt_Predicate = "{0} "; - //private static readonly string Fmt_Label = "{0}"; - private static readonly string Fmt_Modifier = ", {0}"; - - private static readonly string Fmt_Null = "null"; - private static readonly string Fmt_EmptyString = ""; - private static readonly string Fmt_EmptyCollection = ""; - - private static readonly string Fmt_String = "\"{0}\""; - private static readonly string Fmt_Char = "'{0}'"; - private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff"; - private static readonly string Fmt_ValueType = "{0}"; - private static readonly string Fmt_Default = "<{0}>"; - #endregion - - private int maxLineLength = DEFAULT_LINE_LENGTH; - - #region Constructors - /// - /// Construct a TextMessageWriter - /// - public TextMessageWriter() { } - - /// - /// Construct a TextMessageWriter, specifying a user message - /// and optional formatting arguments. - /// - /// - /// - public TextMessageWriter(string userMessage, params object[] args) - { - if ( userMessage != null && userMessage != string.Empty) - this.WriteMessageLine(userMessage, args); - } - #endregion - - #region Properties - /// - /// Gets or sets the maximum line length for this writer - /// - public override int MaxLineLength - { - get { return maxLineLength; } - set { maxLineLength = value; } - } - #endregion - - #region Public Methods - High Level - /// - /// Method to write single line message with optional args, usually - /// written to precede the general failure message, at a givel - /// indentation level. - /// - /// The indentation level of the message - /// The message to be written - /// Any arguments used in formatting the message - public override void WriteMessageLine(int level, string message, params object[] args) - { - if (message != null) - { - while (level-- >= 0) Write(" "); - - if (args != null && args.Length > 0) - message = string.Format(message, args); - - WriteLine(message); - } - } - - /// - /// Display Expected and Actual lines for a constraint. This - /// is called by MessageWriter's default implementation of - /// WriteMessageTo and provides the generic two-line display. - /// - /// The constraint that failed - public override void DisplayDifferences(Constraint constraint) - { - WriteExpectedLine(constraint); - WriteActualLine(constraint); - } - - /// - /// Display Expected and Actual lines for given values. This - /// method may be called by constraints that need more control over - /// the display of actual and expected values than is provided - /// by the default implementation. - /// - /// The expected value - /// The actual value causing the failure - public override void DisplayDifferences(object expected, object actual) - { - WriteExpectedLine(expected); - WriteActualLine(actual); - } - - /// - /// Display Expected and Actual lines for given values, including - /// a tolerance value on the expected line. - /// - /// The expected value - /// The actual value causing the failure - /// The tolerance within which the test was made - public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) - { - WriteExpectedLine(expected, tolerance); - WriteActualLine(actual); - } - - /// - /// Display the expected and actual string values on separate lines. - /// If the mismatch parameter is >=0, an additional line is displayed - /// line containing a caret that points to the mismatch point. - /// - /// The expected string value - /// The actual string value - /// The point at which the strings don't match or -1 - /// If true, case is ignored in string comparisons - /// If true, clip the strings to fit the max line length - public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) - { - // Maximum string we can display without truncating - int maxDisplayLength = MaxLineLength - - PrefixLength // Allow for prefix - - 2; // 2 quotation marks - - if ( clipping ) - MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); - - expected = MsgUtils.EscapeControlChars(expected); - actual = MsgUtils.EscapeControlChars(actual); - - // The mismatch position may have changed due to clipping or white space conversion - mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); - - Write( Pfx_Expected ); - WriteExpectedValue( expected ); - if ( ignoreCase ) - WriteModifier( "ignoring case" ); - WriteLine(); - WriteActualLine( actual ); - //DisplayDifferences(expected, actual); - if (mismatch >= 0) - WriteCaretLine(mismatch); - } - #endregion - - #region Public Methods - Low Level - /// - /// Writes the text for a connector. - /// - /// The connector. - public override void WriteConnector(string connector) - { - Write(Fmt_Connector, connector); - } - - /// - /// Writes the text for a predicate. - /// - /// The predicate. - public override void WritePredicate(string predicate) - { - Write(Fmt_Predicate, predicate); - } - - //public override void WriteLabel(string label) - //{ - // Write(Fmt_Label, label); - //} - - /// - /// Write the text for a modifier. - /// - /// The modifier. - public override void WriteModifier(string modifier) - { - Write(Fmt_Modifier, modifier); - } - - - /// - /// Writes the text for an expected value. - /// - /// The expected value. - public override void WriteExpectedValue(object expected) - { - WriteValue(expected); - } - - /// - /// Writes the text for an actual value. - /// - /// The actual value. - public override void WriteActualValue(object actual) - { - WriteValue(actual); - } - - /// - /// Writes the text for a generalized value. - /// - /// The value. - public override void WriteValue(object val) - { - if (val == null) - Write(Fmt_Null); - else if (val.GetType().IsArray) - WriteArray((Array)val); - else if (val is string) - WriteString((string)val); - else if (val is IEnumerable) - WriteCollectionElements((IEnumerable)val, 0, 10); - else if (val is char) - WriteChar((char)val); - else if (val is double) - WriteDouble((double)val); - else if (val is float) - WriteFloat((float)val); - else if (val is decimal) - WriteDecimal((decimal)val); - else if (val is DateTime) - WriteDateTime((DateTime)val); - else if (val.GetType().IsValueType) - Write(Fmt_ValueType, val); - else - Write(Fmt_Default, val); - } - - /// - /// Writes the text for a collection value, - /// starting at a particular point, to a max length - /// - /// The collection containing elements to write. - /// The starting point of the elements to write - /// The maximum number of elements to write - public override void WriteCollectionElements(IEnumerable collection, int start, int max) - { - int count = 0; - int index = 0; - - foreach (object obj in collection) - { - if ( index++ >= start) - { - if (++count > max) - break; - Write(count == 1 ? "< " : ", "); - WriteValue(obj); - } - } - - if (count == 0) - { - Write(Fmt_EmptyCollection); - return; - } - - if (count > max) - Write("..."); - - Write(" >"); - } - - private void WriteArray(Array array) - { - if ( array.Length == 0 ) - { - Write( Fmt_EmptyCollection ); - return; - } - - int rank = array.Rank; - int[] products = new int[rank]; - - for (int product = 1, r = rank; --r >= 0; ) - products[r] = product *= array.GetLength(r); - - int count = 0; - foreach (object obj in array) - { - if (count > 0) - Write(", "); - - bool startSegment = false; - for (int r = 0; r < rank; r++) - { - startSegment = startSegment || count % products[r] == 0; - if (startSegment) Write("< "); - } - - WriteValue(obj); - - ++count; - - bool nextSegment = false; - for (int r = 0; r < rank; r++) - { - nextSegment = nextSegment || count % products[r] == 0; - if (nextSegment) Write(" >"); - } - } - } - - private void WriteString(string s) - { - if (s == string.Empty) - Write(Fmt_EmptyString); - else - Write(Fmt_String, s); - } - - private void WriteChar(char c) - { - Write(Fmt_Char, c); - } - - private void WriteDouble(double d) - { - - if (double.IsNaN(d) || double.IsInfinity(d)) - Write(d); - else - { - string s = d.ToString("G17", CultureInfo.InvariantCulture); - - if (s.IndexOf('.') > 0) - Write(s + "d"); - else - Write(s + ".0d"); - } - } - - private void WriteFloat(float f) - { - if (float.IsNaN(f) || float.IsInfinity(f)) - Write(f); - else - { - string s = f.ToString("G9", CultureInfo.InvariantCulture); - - if (s.IndexOf('.') > 0) - Write(s + "f"); - else - Write(s + ".0f"); - } - } - - private void WriteDecimal(Decimal d) - { - Write(d.ToString("G29", CultureInfo.InvariantCulture) + "m"); - } - - private void WriteDateTime(DateTime dt) - { - Write(dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture)); - } - #endregion - - #region Helper Methods - /// - /// Write the generic 'Expected' line for a constraint - /// - /// The constraint that failed - private void WriteExpectedLine(Constraint constraint) - { - Write(Pfx_Expected); - constraint.WriteDescriptionTo(this); - WriteLine(); - } - - /// - /// Write the generic 'Expected' line for a given value - /// - /// The expected value - private void WriteExpectedLine(object expected) - { - WriteExpectedLine(expected, null); - } - - /// - /// Write the generic 'Expected' line for a given value - /// and tolerance. - /// - /// The expected value - /// The tolerance within which the test was made - private void WriteExpectedLine(object expected, Tolerance tolerance) - { - Write(Pfx_Expected); - WriteExpectedValue(expected); - - if (tolerance != null && !tolerance.IsEmpty) - { - WriteConnector("+/-"); - WriteExpectedValue(tolerance.Value); - if (tolerance.Mode != ToleranceMode.Linear) - Write(" {0}", tolerance.Mode); - } - - WriteLine(); - } - - /// - /// Write the generic 'Actual' line for a constraint - /// - /// The constraint for which the actual value is to be written - private void WriteActualLine(Constraint constraint) - { - Write(Pfx_Actual); - constraint.WriteActualValueTo(this); - WriteLine(); - } - - /// - /// Write the generic 'Actual' line for a given value - /// - /// The actual value causing a failure - private void WriteActualLine(object actual) - { - Write(Pfx_Actual); - WriteActualValue(actual); - WriteLine(); - } - - private void WriteCaretLine(int mismatch) - { - // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote - WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); - } - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/TypeHelper.cs b/test/NUnitLite/src/framework/Internal/TypeHelper.cs deleted file mode 100644 index 9a0ed0666..000000000 --- a/test/NUnitLite/src/framework/Internal/TypeHelper.cs +++ /dev/null @@ -1,340 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using System.Text; - -namespace NUnit.Framework.Internal -{ - /// - /// TypeHelper provides static methods that operate on Types. - /// - public class TypeHelper - { - /// - /// Gets the display name for a Type as used by NUnit. - /// - /// The Type for which a display name is needed. - /// The display name for the Type - public static string GetDisplayName(Type type) - { -#if CLR_2_0 || CLR_4_0 - if (type.IsGenericParameter) - return type.Name; - - if (type.IsGenericType) - { - string name = type.FullName; - int index = name.IndexOf('['); - if (index >= 0) name = name.Substring(0, index); - - index = name.LastIndexOf('.'); - if (index >= 0) name = name.Substring(index+1); - - index = name.IndexOf('`'); - if (index >= 0) name = name.Substring(0, index); - - StringBuilder sb = new StringBuilder(name); - - sb.Append("<"); - int cnt = 0; - foreach (Type t in type.GetGenericArguments()) - { - if (cnt++ > 0) sb.Append(","); - sb.Append(GetDisplayName(t)); - } - sb.Append(">"); - - return sb.ToString(); - } -#endif - - int lastdot = type.FullName.LastIndexOf('.'); - return lastdot >= 0 - ? type.FullName.Substring(lastdot+1) - : type.FullName; - } - - /// - /// Gets the display name for a Type as used by NUnit. - /// - /// The Type for which a display name is needed. - /// The arglist provided. - /// The display name for the Type - public static string GetDisplayName(Type type, object[] arglist) - { - string baseName = GetDisplayName(type); - if (arglist == null || arglist.Length == 0) - return baseName; - - StringBuilder sb = new StringBuilder( baseName ); - - sb.Append("("); - for (int i = 0; i < arglist.Length; i++) - { - if (i > 0) sb.Append(","); - - object arg = arglist[i]; - string display = arg == null ? "null" : arg.ToString(); - - if (arg is double || arg is float) - { - if (display.IndexOf('.') == -1) - display += ".0"; - display += arg is double ? "d" : "f"; - } - else if (arg is decimal) display += "m"; - else if (arg is long) display += "L"; - else if (arg is ulong) display += "UL"; - else if (arg is string) display = "\"" + display + "\""; - - sb.Append(display); - } - sb.Append(")"); - - return sb.ToString(); - } - - /// - /// Returns the best fit for a common type to be used in - /// matching actual arguments to a methods Type parameters. - /// - /// The first type. - /// The second type. - /// Either type1 or type2, depending on which is more general. - public static Type BestCommonType(Type type1, Type type2) - { - if (type1 == type2) return type1; - if (type1 == null) return type2; - if (type2 == null) return type1; - - if (TypeHelper.IsNumeric(type1) && TypeHelper.IsNumeric(type2)) - { - if (type1 == typeof(double)) return type1; - if (type2 == typeof(double)) return type2; - - if (type1 == typeof(float)) return type1; - if (type2 == typeof(float)) return type2; - - if (type1 == typeof(decimal)) return type1; - if (type2 == typeof(decimal)) return type2; - - if (type1 == typeof(UInt64)) return type1; - if (type2 == typeof(UInt64)) return type2; - - if (type1 == typeof(Int64)) return type1; - if (type2 == typeof(Int64)) return type2; - - if (type1 == typeof(UInt32)) return type1; - if (type2 == typeof(UInt32)) return type2; - - if (type1 == typeof(Int32)) return type1; - if (type2 == typeof(Int32)) return type2; - - if (type1 == typeof(UInt16)) return type1; - if (type2 == typeof(UInt16)) return type2; - - if (type1 == typeof(Int16)) return type1; - if (type2 == typeof(Int16)) return type2; - - if (type1 == typeof(byte)) return type1; - if (type2 == typeof(byte)) return type2; - - if (type1 == typeof(sbyte)) return type1; - if (type2 == typeof(sbyte)) return type2; - } - - return type1; - } - - /// - /// Determines whether the specified type is numeric. - /// - /// The type to be examined. - /// - /// true if the specified type is numeric; otherwise, false. - /// - public static bool IsNumeric(Type type) - { - return type == typeof(double) || - type == typeof(float) || - type == typeof(decimal) || - type == typeof(Int64) || - type == typeof(Int32) || - type == typeof(Int16) || - type == typeof(UInt64) || - type == typeof(UInt32) || - type == typeof(UInt16) || - type == typeof(byte) || - type == typeof(sbyte); - } - - /// - /// Convert an argument list to the required paramter types. - /// Currently, only widening numeric conversions are performed. - /// - /// An array of args to be converted - /// A ParamterInfo[] whose types will be used as targets - public static void ConvertArgumentList(object[] arglist, ParameterInfo[] parameters) - { - System.Diagnostics.Debug.Assert(arglist.Length == parameters.Length); - - for (int i = 0; i < parameters.Length; i++) - { - object arg = arglist[i]; - - if (arg != null && arg is IConvertible) - { - Type argType = arg.GetType(); - Type targetType = parameters[i].ParameterType; - bool convert = false; - - if (argType != targetType && !argType.IsAssignableFrom(targetType)) - { - if (IsNumeric(argType) && IsNumeric(targetType)) - { - if (targetType == typeof(double) || targetType == typeof(float)) - convert = arg is int || arg is long || arg is short || arg is byte || arg is sbyte; - else - if (targetType == typeof(long)) - convert = arg is int || arg is short || arg is byte || arg is sbyte; - else - if (targetType == typeof(short)) - convert = arg is byte || arg is sbyte; - } - } - - if (convert) - arglist[i] = Convert.ChangeType(arg, targetType, - System.Globalization.CultureInfo.InvariantCulture); - } - } - } - -#if CLR_2_0 || CLR_4_0 - /// - /// Creates an instance of a generic Type using the supplied Type arguments - /// - /// The generic type to be specialized. - /// The type args. - /// An instance of the generic type. - public static Type MakeGenericType(Type type, Type[] typeArgs) - { - // TODO: Add error handling - return type.MakeGenericType(typeArgs); - } - - /// - /// Determines whether this instance can deduce type args for a generic type from the supplied arguments. - /// - /// The type to be examined. - /// The arglist. - /// The type args to be used. - /// - /// true if this the provided args give sufficient information to determine the type args to be used; otherwise, false. - /// - public static bool CanDeduceTypeArgsFromArgs(Type type, object[] arglist, ref Type[] typeArgsOut) - { - Type[] typeParameters = type.GetGenericArguments(); - - foreach (ConstructorInfo ctor in type.GetConstructors()) - { - ParameterInfo[] parameters = ctor.GetParameters(); - if (parameters.Length != arglist.Length) - continue; - - Type[] typeArgs = new Type[typeParameters.Length]; - for (int i = 0; i < typeArgs.Length; i++) - { - for (int j = 0; j < arglist.Length; j++) - { - if (parameters[j].ParameterType.Equals(typeParameters[i])) - typeArgs[i] = TypeHelper.BestCommonType( - typeArgs[i], - arglist[j].GetType()); - } - - if (typeArgs[i] == null) - { - typeArgs = null; - break; - } - } - - if (typeArgs != null) - { - typeArgsOut = typeArgs; - return true; - } - } - - return false; - } -#endif - - /// - /// Gets the values for an enumeration, using Enum.GetTypes - /// where available, otherwise through reflection. - /// - /// - /// - public static Array GetEnumValues(Type enumType) - { -#if NETCF || SILVERLIGHT - FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); - - Array enumValues = Array.CreateInstance(enumType, fields.Length); - - for (int index = 0; index < fields.Length; index++) - enumValues.SetValue(fields[index].GetValue(enumType), index); - - return enumValues; -#else - return Enum.GetValues(enumType); -#endif - } - - /// - /// Gets the names defined for an enumeration, using Enum.GetNames - /// where available, otherwise through reflection. - /// - /// - /// - public static string[] GetEnumNames(Type enumType) - { -#if NETCF || SILVERLIGHT - FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); - - string[] names = new string[fields.Length]; - - for (int index = 0; index < fields.Length; index++) - names[index] = fields[index].Name; - - return names; -#else - return Enum.GetNames(enumType); -#endif - } - } -} diff --git a/test/NUnitLite/src/framework/Internal/WorkItems/CompositeWorkItem.cs b/test/NUnitLite/src/framework/Internal/WorkItems/CompositeWorkItem.cs deleted file mode 100644 index 0fe2f4c57..000000000 --- a/test/NUnitLite/src/framework/Internal/WorkItems/CompositeWorkItem.cs +++ /dev/null @@ -1,220 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Threading; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.WorkItems -{ - /// - /// A CompositeWorkItem represents a test suite and - /// encapsulates the execution of the suite as well - /// as all its child tests. - /// - public class CompositeWorkItem : WorkItem - { - private TestSuite _suite; - private ITestFilter _childFilter; -#if CLR_2_0 || CLR_4_0 - private System.Collections.Generic.Queue _children = new System.Collections.Generic.Queue(); -#else - private System.Collections.Queue _children = new System.Collections.Queue(); -#endif - private TestCommand _setupCommand; - private TestCommand _teardownCommand; - - private CountdownEvent _childTestCountdown; - - /// - /// Construct a CompositeWorkItem for executing a test suite - /// using a filter to select child tests. - /// - /// The TestSuite to be executed - /// A filter used to select child tests - public CompositeWorkItem(TestSuite suite, ITestFilter childFilter) - : base(suite) - { - _suite = suite; - _setupCommand = suite.GetOneTimeSetUpCommand(); - _teardownCommand = suite.GetOneTimeTearDownCommand(); - _childFilter = childFilter; - } - - /// - /// Method that actually performs the work. Overridden - /// in CompositeWorkItem to do setup, run all child - /// items and then do teardown. - /// - protected override void PerformWork() - { - if (_suite.HasChildren) - foreach (Test test in _suite.Tests) - if (_childFilter.Pass(test)) - _children.Enqueue(test.CreateWorkItem(_childFilter)); - - switch (Test.RunState) - { - default: - case RunState.Runnable: - case RunState.Explicit: - // Assume success, since the result will be inconclusive - // if there is no setup method to run or if the - // context initialization fails. - Result.SetResult(ResultState.Success); - - PerformOneTimeSetUp(); - - if (_children.Count > 0) - switch (Result.ResultState.Status) - { - case TestStatus.Passed: - RunChildren(); - return; - // Just return: completion event will take care - // of TestFixtureTearDown when all tests are done. - - case TestStatus.Skipped: - case TestStatus.Inconclusive: - case TestStatus.Failed: - SkipChildren(); - break; - } - - PerformOneTimeTearDown(); - break; - - case RunState.Skipped: - SkipFixture(ResultState.Skipped, GetSkipReason(), null); - break; - - case RunState.Ignored: - SkipFixture(ResultState.Ignored, GetSkipReason(), null); - break; - - case RunState.NotRunnable: - SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace()); - break; - } - - // Fall through in case no child tests were run. - // Otherwise, this is done in the completion event. - WorkItemComplete(); - } - - #region Helper Methods - - private void PerformOneTimeSetUp() - { - try - { - _setupCommand.Execute(Context); - - // SetUp may have changed some things - Context.UpdateContext(); - } - catch (Exception ex) - { - if (ex is NUnitException || ex is System.Reflection.TargetInvocationException) - ex = ex.InnerException; - - Result.RecordException(ex); - } - } - - private void RunChildren() - { - _childTestCountdown = new CountdownEvent(_children.Count); - - while (_children.Count > 0) - { - WorkItem child = (WorkItem)_children.Dequeue(); - child.Completed += new EventHandler(OnChildCompleted); - child.Execute(this.Context); - } - } - - private void SkipFixture(ResultState resultState, string message, string stackTrace) - { - Result.SetResult(resultState, message, stackTrace); - SkipChildren(); - } - - private void SkipChildren() - { - while (_children.Count > 0) - { - WorkItem child = (WorkItem)_children.Dequeue(); - Test test = child.Test; - TestResult result = test.MakeTestResult(); - if (Result.ResultState.Status == TestStatus.Failed) - result.SetResult(ResultState.Failure, "TestFixtureSetUp Failed"); - else - result.SetResult(Result.ResultState, Result.Message); - Result.AddResult(result); - } - } - - private void PerformOneTimeTearDown() - { - TestExecutionContext.SetCurrentContext(Context); - _teardownCommand.Execute(Context); - } - - - private string GetSkipReason() - { - return (string)Test.Properties.Get(PropertyNames.SkipReason); - } - - private string GetProviderStackTrace() - { - return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace); - } - - private object _completionLock = new object(); - - private void OnChildCompleted(object sender, EventArgs e) - { - lock (_completionLock) - { - WorkItem childTask = sender as WorkItem; - if (childTask != null) - { - childTask.Completed -= new EventHandler(OnChildCompleted); - Result.AddResult(childTask.Result); - _childTestCountdown.Signal(); - - if (_childTestCountdown.CurrentCount == 0) - { - PerformOneTimeTearDown(); - WorkItemComplete(); - } - } - } - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Internal/WorkItems/WorkItem.cs b/test/NUnitLite/src/framework/Internal/WorkItems/WorkItem.cs deleted file mode 100644 index c467ccb95..000000000 --- a/test/NUnitLite/src/framework/Internal/WorkItems/WorkItem.cs +++ /dev/null @@ -1,235 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Diagnostics; -using System.Threading; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal.WorkItems -{ - /// - /// A WorkItem may be an individual test case, a fixture or - /// a higher level grouping of tests. All WorkItems inherit - /// from the abstract WorkItem class, which uses the template - /// pattern to allow derived classes to perform work in - /// whatever way is needed. - /// - public abstract class WorkItem - { - // The current state of the WorkItem - private WorkItemState _state; - - // The test this WorkItem represents - private Test _test; - - /// - /// The result of running the test - /// - protected TestResult testResult; - - // The execution context used by this work item - private TestExecutionContext _context; - - #region Constructor - - /// - /// Construct a WorkItem for a particular test. - /// - /// The test that the WorkItem will run - public WorkItem(Test test) - { - _test = test; - testResult = test.MakeTestResult(); - _state = WorkItemState.Ready; - } - - #endregion - - #region Properties and Events - - /// - /// Event triggered when the item is complete - /// - public event EventHandler Completed; - - /// - /// Gets the current state of the WorkItem - /// - public WorkItemState State - { - get { return _state; } - } - - /// - /// The test being executed by the work item - /// - public Test Test - { - get { return _test; } - } - - /// - /// The execution context - /// - protected TestExecutionContext Context - { - get { return _context; } - } - - /// - /// The test result - /// - public TestResult Result - { - get { return testResult; } - } - - #endregion - - #region Public Methods - - /// - /// Execute the current work item, including any - /// child work items. - /// - public virtual void Execute(TestExecutionContext context) - { - _context = new TestExecutionContext(context); - -#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT - // Timeout set at a higher level - int timeout = _context.TestCaseTimeout; - - // Timeout set on this test - if (Test.Properties.ContainsKey(PropertyNames.Timeout)) - timeout = (int)Test.Properties.Get(PropertyNames.Timeout); - - if (Test is TestMethod && timeout > 0) - RunTestWithTimeout(timeout); - else - RunTest(); -#else - RunTest(); -#endif - } - -#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT - private void RunTestWithTimeout(int timeout) - { - Thread thread = new Thread(new ThreadStart(RunTest)); - - thread.Start(); - - if (timeout <= 0) - timeout = Timeout.Infinite; - -#if NETCF - // NETCF doesn't support IsAlive as well as various - // members required by our ThreadUtilitity.Kill - if (!thread.Join(timeout)) - { - thread.Abort(); -#else - thread.Join(timeout); - - if (thread.IsAlive) - { - ThreadUtility.Kill(thread); -#endif - // NOTE: Without the use of Join, there is a race condition here. - // The thread sets the result to Cancelled and our code below sets - // it to Failure. In order for the result to be shown as a failure, - // we need to ensure that the following code executes after the - // thread has terminated. There is a risk here: the test code might - // refuse to terminate. However, it's more important to deal with - // the normal rather than a pathological case. - thread.Join(); - - Result.SetResult(ResultState.Failure, - string.Format("Test exceeded Timeout value of {0}ms", timeout)); - - WorkItemComplete(); - } - } -#endif - - private void RunTest() - { - _context.CurrentTest = this.Test; - _context.CurrentResult = this.Result; - _context.Listener.TestStarted(this.Test); - _context.StartTime = DateTime.Now; - - TestExecutionContext.SetCurrentContext(_context); - -#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT && !NETCF_2_0 - long startTicks = Stopwatch.GetTimestamp(); -#endif - - try - { - PerformWork(); - } - finally - { -#if (CLR_2_0 || CLR_4_0) && !SILVERLIGHT && !NETCF_2_0 - long tickCount = Stopwatch.GetTimestamp() - startTicks; - double seconds = (double)tickCount / Stopwatch.Frequency; - Result.Duration = TimeSpan.FromSeconds(seconds); -#else - Result.Duration = DateTime.Now - Context.StartTime; -#endif - - Result.AssertCount = _context.AssertCount; - - _context.Listener.TestFinished(Result); - - _context = _context.Restore(); - _context.AssertCount += Result.AssertCount; - } - } - - #endregion - - #region Protected Methods - - /// - /// Method that performs actually performs the work. It should - /// set the State to WorkItemState.Complete when done. - /// - protected abstract void PerformWork(); - - /// - /// Method called by the derived class when all work is complete - /// - protected void WorkItemComplete() - { - _state = WorkItemState.Complete; - if (Completed != null) - Completed(this, EventArgs.Empty); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/ListMapper.cs b/test/NUnitLite/src/framework/ListMapper.cs deleted file mode 100644 index 00d00f00f..000000000 --- a/test/NUnitLite/src/framework/ListMapper.cs +++ /dev/null @@ -1,69 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Reflection; - -namespace NUnit.Framework -{ - /// - /// ListMapper is used to transform a collection used as an actual argument - /// producing another collection to be used in the assertion. - /// - public class ListMapper - { - ICollection original; - - /// - /// Construct a ListMapper based on a collection - /// - /// The collection to be transformed - public ListMapper( ICollection original ) - { - this.original = original; - } - - /// - /// Produces a collection containing all the values of a property - /// - /// The collection of property values - /// - public ICollection Property( string name ) - { - ObjectList propList = new ObjectList(); - foreach( object item in original ) - { - PropertyInfo property = item.GetType().GetProperty( name, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ); - if ( property == null ) - throw new ArgumentException( string.Format( - "{0} does not have a {1} property", item, name ) ); - - propList.Add( property.GetValue( item, null ) ); - } - - return propList; - } - } -} diff --git a/test/NUnitLite/src/framework/MessageMatch.cs b/test/NUnitLite/src/framework/MessageMatch.cs deleted file mode 100644 index c90a08836..000000000 --- a/test/NUnitLite/src/framework/MessageMatch.cs +++ /dev/null @@ -1,40 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework -{ - /// - /// Enumeration indicating how the expected message parameter is to be used - /// - public enum MessageMatch - { - /// Expect an exact match - Exact, - /// Expect a message containing the parameter string - Contains, - /// Match the regular expression provided as a parameter - Regex, - /// Expect a message that starts with the parameter string - StartsWith - } -} diff --git a/test/NUnitLite/src/framework/ObjectList.cs b/test/NUnitLite/src/framework/ObjectList.cs deleted file mode 100644 index 3ba6f0e0d..000000000 --- a/test/NUnitLite/src/framework/ObjectList.cs +++ /dev/null @@ -1,52 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit -{ - /// - /// ObjectList represents a collection of objects. It is implemented - /// as a List<object> in .NET 2.0 or higher and as an ArrayList otherwise. - /// ObjectList does not attempt to be a general replacement for either of - /// these classes but only implements what is needed within the framework. - /// -#if CLR_2_0 || CLR_4_0 - public class ObjectList : System.Collections.Generic.List - { - /// - /// Adds a range of values to the collection. - /// - /// The collection. - public void AddRange(System.Collections.ICollection collection) - { - foreach (object item in collection) - Add(item); - } - } -#else - public class ObjectList : System.Collections.ArrayList - { - } -#endif -} diff --git a/test/NUnitLite/src/framework/Runner/CommandLineOptions.cs b/test/NUnitLite/src/framework/Runner/CommandLineOptions.cs deleted file mode 100644 index 7a7fa5524..000000000 --- a/test/NUnitLite/src/framework/Runner/CommandLineOptions.cs +++ /dev/null @@ -1,459 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using System.Text; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework; - -namespace NUnitLite.Runner -{ - /// - /// The CommandLineOptions class parses and holds the values of - /// any options entered at the command line. - /// - public class CommandLineOptions - { - private string optionChars; - private static string NL = NUnit.Env.NewLine; - - private bool wait = false; - private bool noheader = false; - private bool help = false; - private bool full = false; - private bool explore = false; - private bool labelTestsInOutput = false; - - private string exploreFile; - private string resultFile; - private string resultFormat; - private string outFile; - private string includeCategory; - private string excludeCategory; - - private bool error = false; - - private StringList tests = new StringList(); - private StringList invalidOptions = new StringList(); - private StringList parameters = new StringList(); - - private int randomSeed = -1; - - #region Properties - - /// - /// Gets a value indicating whether the 'wait' option was used. - /// - public bool Wait - { - get { return wait; } - } - - /// - /// Gets a value indicating whether the 'nologo' option was used. - /// - public bool NoHeader - { - get { return noheader; } - } - - /// - /// Gets a value indicating whether the 'help' option was used. - /// - public bool ShowHelp - { - get { return help; } - } - - /// - /// Gets a list of all tests specified on the command line - /// - public string[] Tests - { - get { return (string[])tests.ToArray(); } - } - - /// - /// Gets a value indicating whether a full report should be displayed - /// - public bool Full - { - get { return full; } - } - - /// - /// Gets a value indicating whether tests should be listed - /// rather than run. - /// - public bool Explore - { - get { return explore; } - } - - /// - /// Gets the name of the file to be used for listing tests - /// - public string ExploreFile - { - get { return exploreFile; } - } - - /// - /// Gets the name of the file to be used for test results - /// - public string ResultFile - { - get { return resultFile; } - } - - /// - /// Gets the format to be used for test results - /// - public string ResultFormat - { - get { return resultFormat; } - } - - /// - /// Gets the full path of the file to be used for output - /// - public string OutFile - { - get - { - return outFile; - } - } - - /// - /// Gets the list of categories to include - /// - public string Include - { - get - { - return includeCategory; - } - } - - /// - /// Gets the list of categories to exclude - /// - public string Exclude - { - get - { - return excludeCategory; - } - } - - /// - /// Gets a flag indicating whether each test should - /// be labeled in the output. - /// - public bool LabelTestsInOutput - { - get { return labelTestsInOutput; } - } - - private string ExpandToFullPath(string path) - { - if (path == null) return null; - -#if NETCF - return Path.Combine(NUnit.Env.DocumentFolder, path); -#else - return Path.GetFullPath(path); -#endif - } - - /// - /// Gets the test count - /// - public int TestCount - { - get { return tests.Count; } - } - - /// - /// Gets the seed to be used for generating random values - /// - public int InitialSeed - { - get - { - if (randomSeed < 0) - randomSeed = new Random().Next(); - - return randomSeed; - } - } - - #endregion - - /// - /// Construct a CommandLineOptions object using default option chars - /// - public CommandLineOptions() - { - this.optionChars = System.IO.Path.DirectorySeparatorChar == '/' ? "-" : "/-"; - } - - /// - /// Construct a CommandLineOptions object using specified option chars - /// - /// - public CommandLineOptions(string optionChars) - { - this.optionChars = optionChars; - } - - /// - /// Parse command arguments and initialize option settings accordingly - /// - /// The argument list - public void Parse(params string[] args) - { - foreach( string arg in args ) - { - if (optionChars.IndexOf(arg[0]) >= 0 ) - ProcessOption(arg); - else - ProcessParameter(arg); - } - } - - /// - /// Gets the parameters provided on the commandline - /// - public string[] Parameters - { - get { return (string[])parameters.ToArray(); } - } - - private void ProcessOption(string option) - { - string opt = option; - int pos = opt.IndexOfAny( new char[] { ':', '=' } ); - string val = string.Empty; - - if (pos >= 0) - { - val = opt.Substring(pos + 1); - opt = opt.Substring(0, pos); - } - - switch (opt.Substring(1)) - { - case "wait": - wait = true; - break; - case "noheader": - case "noh": - noheader = true; - break; - case "help": - case "h": - help = true; - break; - case "test": - tests.Add(val); - break; - case "full": - full = true; - break; - case "explore": - explore = true; - if (val == null || val.Length == 0) - val = "tests.xml"; - try - { - exploreFile = ExpandToFullPath(val); - } - catch - { - InvalidOption(option); - } - break; - case "result": - if (val == null || val.Length == 0) - val = "TestResult.xml"; - try - { - resultFile = ExpandToFullPath(val); - } - catch - { - InvalidOption(option); - } - break; - case "format": - resultFormat = val; - if (resultFormat != "nunit3" && resultFormat != "nunit2") - InvalidOption(option); - break; - case "out": - try - { - outFile = ExpandToFullPath(val); - } - catch - { - InvalidOption(option); - } - break; - case "labels": - labelTestsInOutput = true; - break; - case "include": - includeCategory = val; - break; - case "exclude": - excludeCategory = val; - break; - case "seed": - try - { - randomSeed = int.Parse(val); - } - catch - { - InvalidOption(option); - } - break; - default: - InvalidOption(option); - break; - } - } - - private void InvalidOption(string option) - { - error = true; - invalidOptions.Add(option); - } - - private void ProcessParameter(string param) - { - parameters.Add(param); - } - - /// - /// Gets a value indicating whether there was an error in parsing the options. - /// - /// true if error; otherwise, false. - public bool Error - { - get { return error; } - } - - /// - /// Gets the error message. - /// - /// The error message. - public string ErrorMessage - { - get - { - StringBuilder sb = new StringBuilder(); - foreach (string opt in invalidOptions) - sb.Append( "Invalid option: " + opt + NL ); - return sb.ToString(); - } - } - - /// - /// Gets the help text. - /// - /// The help text. - public string HelpText - { - get - { - StringBuilder sb = new StringBuilder(); - -#if PocketPC || WindowsCE || NETCF || SILVERLIGHT - string name = "NUnitLite"; -#else - string name = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; -#endif - - sb.Append("Usage: " + name + " [assemblies] [options]" + NL + NL); - sb.Append("Runs a set of NUnitLite tests from the console." + NL + NL); - sb.Append("You may specify one or more test assemblies by name, without a path or" + NL); - sb.Append("extension. They must be in the same in the same directory as the exe" + NL); - sb.Append("or on the probing path. If no assemblies are provided, tests in the" + NL); - sb.Append("executing assembly itself are run." + NL + NL); - sb.Append("Options:" + NL); - sb.Append(" -test:testname Provides the name of a test to run. This option may be" + NL); - sb.Append(" repeated. If no test names are given, all tests are run." + NL + NL); - sb.Append(" -out:FILE File to which output is redirected. If this option is not" + NL); - sb.Append(" used, output is to the Console, which means it is lost" + NL); - sb.Append(" on devices without a Console." + NL + NL); - sb.Append(" -full Prints full report of all test results." + NL + NL); - sb.Append(" -result:FILE File to which the xml test result is written." + NL + NL); - sb.Append(" -format:FORMAT Format in which the result is to be written. FORMAT must be" + NL); - sb.Append(" either nunit3 or nunit2. The default is nunit3." + NL + NL); - sb.Append(" -explore:FILE If provided, this option indicates that the tests" + NL); - sb.Append(" should be listed rather than executed. They are listed" + NL); - sb.Append(" to the specified file in XML format." + NL); - sb.Append(" -help,-h Displays this help" + NL + NL); - sb.Append(" -noheader,-noh Suppresses display of the initial message" + NL + NL); - sb.Append(" -labels Displays the name of each test when it starts" + NL + NL); - sb.Append(" -seed:SEED If provided, this option allows you to set the seed for the" + NL + NL); - sb.Append(" random generator in the test context." + NL + NL); - sb.Append(" -include:CAT List of categories to include" + NL + NL); - sb.Append(" -exclude:CAT List of categories to exclude" + NL + NL); - sb.Append(" -wait Waits for a key press before exiting" + NL + NL); - - sb.Append("Notes:" + NL); - sb.Append(" * File names may be listed by themselves, with a relative path or " + NL); - sb.Append(" using an absolute path. Any relative path is based on the current " + NL); - sb.Append(" directory or on the Documents folder if running on a under the " +NL); - sb.Append(" compact framework." + NL + NL); - if (System.IO.Path.DirectorySeparatorChar != '/') - sb.Append(" * On Windows, options may be prefixed by a '/' character if desired" + NL + NL); - sb.Append(" * Options that take values may use an equal sign or a colon" + NL); - sb.Append(" to separate the option from its value." + NL + NL); - - return sb.ToString(); - } - } - -#if CLR_2_0 || CLR_4_0 - class StringList : List { } -#else - class StringList : ArrayList - { - public new string[] ToArray() - { - return (string[])ToArray(typeof(string)); - } - } -#endif - } -} diff --git a/test/NUnitLite/src/framework/Runner/ConsoleWriter.cs b/test/NUnitLite/src/framework/Runner/ConsoleWriter.cs deleted file mode 100644 index 0d2038d98..000000000 --- a/test/NUnitLite/src/framework/Runner/ConsoleWriter.cs +++ /dev/null @@ -1,113 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; - -namespace NUnitLite.Runner -{ - /// - /// Provide an alternative to Console.Out for - /// version 1.0 of the compact framework. - /// - public class ConsoleWriter : TextWriter - { - private static TextWriter writer; - - /// - /// Gets the underlying TextWriter, creating it if it does not already exist. - /// - /// The underlying TextWriter. - public static TextWriter Out - { - get - { - if ( writer == null ) - writer = new ConsoleWriter(); - - return writer; - } - } - - /// - /// Writes a character to the text stream. - /// - /// The character to write to the text stream. - /// - /// The is closed. - /// - /// - /// An I/O error occurs. - /// - public override void Write(char value) - { - Console.Write(value); - } - - /// - /// Writes a string to the text stream. - /// - /// The string to write. - /// - /// The is closed. - /// - /// - /// An I/O error occurs. - /// - public override void Write(string value) - { - Console.Write(value); - } - - /// - /// Writes a string followed by a line terminator to the text stream. - /// - /// The string to write. If is null, only the line termination characters are written. - /// - /// The is closed. - /// - /// - /// An I/O error occurs. - /// - public override void WriteLine(string value) - { - Console.WriteLine(value); - } - - /// - /// When overridden in a derived class, returns the in which the output is written. - /// - /// - /// - /// The Encoding in which the output is written. - /// - public override System.Text.Encoding Encoding - { -#if SILVERLIGHT - get { return System.Text.Encoding.UTF8; } -#else - get { return System.Text.Encoding.Default; } -#endif - } - } -} diff --git a/test/NUnitLite/src/framework/Runner/OutputWriters/NUnit3XmlOutputWriter.cs b/test/NUnitLite/src/framework/Runner/OutputWriters/NUnit3XmlOutputWriter.cs deleted file mode 100644 index 7df2181d4..000000000 --- a/test/NUnitLite/src/framework/Runner/OutputWriters/NUnit3XmlOutputWriter.cs +++ /dev/null @@ -1,153 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using System.Reflection; -using System.Xml; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnitLite.Runner -{ - /// - /// NUnit3XmlOutputWriter is responsible for writing the results - /// of a test to a file in NUnit 3.0 format. - /// - public class NUnit3XmlOutputWriter : OutputWriter - { - private DateTime runStartTime; - private XmlWriter xmlWriter; - - public NUnit3XmlOutputWriter(DateTime runStartTime) - { - this.runStartTime = runStartTime; - } - /// - /// Writes the test result to the specified TextWriter - /// - /// The result to be written to a file - /// A TextWriter to which the result is written - public override void WriteResultFile(ITestResult result, TextWriter writer) - { - // NOTE: Under .NET 1.1, XmlTextWriter does not implement IDisposable, - // but does implement Close(). Hence we cannot use a 'using' clause. -#if CLR_2_0 || CLR_4_0 - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Indent = true; - XmlWriter xmlWriter = XmlWriter.Create(writer, settings); -#else - XmlTextWriter xmlWriter = new XmlTextWriter(writer); - xmlWriter.Formatting = Formatting.Indented; -#endif - - try - { - WriteXmlOutput(result, xmlWriter); - } - finally - { - xmlWriter.Close(); - } - } - - private void WriteXmlOutput(ITestResult result, XmlWriter xmlWriter) - { - this.xmlWriter = xmlWriter; - - InitializeXmlFile(result); - - result.ToXml(true).WriteTo(xmlWriter); - - TerminateXmlFile(); - } - - private void InitializeXmlFile(ITestResult result) - { - xmlWriter.WriteStartDocument(false); - - // In order to match the format used by NUnit 3.0, we - // wrap the entire result from the framework in a - // element. - xmlWriter.WriteStartElement("test-run"); - - xmlWriter.WriteAttributeString("id", "2"); // TODO: Should not be hard-coded - xmlWriter.WriteAttributeString("name", result.Name); - xmlWriter.WriteAttributeString("fullname", result.FullName); - xmlWriter.WriteAttributeString("testcasecount", result.Test.TestCaseCount.ToString()); - - xmlWriter.WriteAttributeString("result", result.ResultState.Status.ToString()); - if (result.ResultState.Label != string.Empty) // && result.ResultState.Label != ResultState.Status.ToString()) - xmlWriter.WriteAttributeString("label", result.ResultState.Label); - - xmlWriter.WriteAttributeString("time", result.Duration.ToString()); - - xmlWriter.WriteAttributeString("total", (result.PassCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString()); - xmlWriter.WriteAttributeString("passed", result.PassCount.ToString()); - xmlWriter.WriteAttributeString("failed", result.FailCount.ToString()); - xmlWriter.WriteAttributeString("inconclusive", result.InconclusiveCount.ToString()); - xmlWriter.WriteAttributeString("skipped", result.SkipCount.ToString()); - xmlWriter.WriteAttributeString("asserts", result.AssertCount.ToString()); - - xmlWriter.WriteAttributeString("run-date", XmlConvert.ToString(runStartTime, "yyyy-MM-dd")); - xmlWriter.WriteAttributeString("start-time", XmlConvert.ToString(runStartTime, "HH:mm:ss")); - - xmlWriter.WriteAttributeString("random-seed", Randomizer.InitialSeed.ToString()); - - WriteEnvironmentElement(); - } - - private void WriteEnvironmentElement() - { - xmlWriter.WriteStartElement("environment"); - - Assembly assembly = Assembly.GetExecutingAssembly(); - AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(assembly); - xmlWriter.WriteAttributeString("nunit-version", assemblyName.Version.ToString()); - - xmlWriter.WriteAttributeString("clr-version", Environment.Version.ToString()); - xmlWriter.WriteAttributeString("os-version", Environment.OSVersion.ToString()); - xmlWriter.WriteAttributeString("platform", Environment.OSVersion.Platform.ToString()); -#if !NETCF - xmlWriter.WriteAttributeString("cwd", Environment.CurrentDirectory); -#if !SILVERLIGHT - xmlWriter.WriteAttributeString("machine-name", Environment.MachineName); - xmlWriter.WriteAttributeString("user", Environment.UserName); - xmlWriter.WriteAttributeString("user-domain", Environment.UserDomainName); -#endif -#endif - xmlWriter.WriteAttributeString("culture", System.Globalization.CultureInfo.CurrentCulture.ToString()); - xmlWriter.WriteAttributeString("uiculture", System.Globalization.CultureInfo.CurrentUICulture.ToString()); - - xmlWriter.WriteEndElement(); - } - - private void TerminateXmlFile() - { - xmlWriter.WriteEndElement(); // test-run - xmlWriter.WriteEndDocument(); - xmlWriter.Flush(); - xmlWriter.Close(); - } - } -} diff --git a/test/NUnitLite/src/framework/Runner/OutputWriters/OutputWriter.cs b/test/NUnitLite/src/framework/Runner/OutputWriters/OutputWriter.cs deleted file mode 100644 index 3f4d5c3de..000000000 --- a/test/NUnitLite/src/framework/Runner/OutputWriters/OutputWriter.cs +++ /dev/null @@ -1,57 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.IO; -using System.Text; -using NUnit.Framework.Api; - -namespace NUnitLite.Runner -{ - /// - /// OutputWriter is an abstract class used to write test - /// results to a file in various formats. Specific - /// OutputWriters are derived from this class. - /// - public abstract class OutputWriter - { - /// - /// Writes a test result to a file - /// - /// The result to be written - /// Path to the file to which the result is written - public void WriteResultFile(ITestResult result, string outputPath) - { - using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8)) - { - WriteResultFile(result, writer); - } - } - - /// - /// Abstract method that writes a test result to a TextWriter - /// - /// The result to be written - /// A TextWriter to which the result is written - public abstract void WriteResultFile(ITestResult result, TextWriter writer); - } -} diff --git a/test/NUnitLite/src/framework/Runner/ResultReporter.cs b/test/NUnitLite/src/framework/Runner/ResultReporter.cs deleted file mode 100644 index 335b2fea6..000000000 --- a/test/NUnitLite/src/framework/Runner/ResultReporter.cs +++ /dev/null @@ -1,196 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.IO; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnitLite.Runner -{ - /// - /// ResultReporter writes the NUnitLite results to a TextWriter. - /// - public class ResultReporter - { - private TextWriter writer; - private ITestResult result; - private ResultSummary summary; - private int reportCount = 0; - - /// - /// Constructs an instance of ResultReporter - /// - /// The top-level result being reported - /// A TextWriter to which the report is written - public ResultReporter(ITestResult result, TextWriter writer) - { - this.result = result; - this.writer = writer; - - this.summary = new ResultSummary(this.result); - } - - /// - /// Gets the ResultSummary created by the ResultReporter - /// - public ResultSummary Summary - { - get { return summary; } - } - - /// - /// Produces the standard output reports. - /// - public void ReportResults() - { - PrintSummaryReport(); - - if (summary.FailureCount > 0 || summary.ErrorCount > 0) - PrintErrorReport(); - - if (summary.NotRunCount > 0) - PrintNotRunReport(); - - //if (commandLineOptions.Full) - // PrintFullReport(result); - } - - /// - /// Prints the Summary Report - /// - public void PrintSummaryReport() - { - writer.WriteLine( - "Tests run: {0}, Passed: {1}, Errors: {2}, Failures: {3}, Inconclusive: {4}", - summary.TestCount, summary.PassCount, summary.ErrorCount, summary.FailureCount, summary.InconclusiveCount); - writer.WriteLine( - " Not run: {0}, Invalid: {1}, Ignored: {2}, Skipped: {3}", - summary.NotRunCount, summary.InvalidCount, summary.IgnoreCount, summary.SkipCount); - writer.WriteLine("Elapsed time: {0}", result.Duration); - } - - /// - /// Prints the Error Report - /// - public void PrintErrorReport() - { - reportCount = 0; - writer.WriteLine(); - writer.WriteLine("Errors and Failures:"); - PrintErrorResults(this.result); - } - - /// - /// Prints the Not Run Report - /// - public void PrintNotRunReport() - { - reportCount = 0; - writer.WriteLine(); - writer.WriteLine("Tests Not Run:"); - PrintNotRunResults(this.result); - } - - /// - /// Prints a full report of all results - /// - public void PrintFullReport() - { - writer.WriteLine(); - writer.WriteLine("All Test Results:"); - PrintAllResults(this.result, " "); - } - - #region Helper Methods - - private void PrintErrorResults(ITestResult result) - { - if (result.ResultState.Status == TestStatus.Failed) - if (!result.HasChildren) - WriteSingleResult(result); - - if (result.HasChildren) - foreach (ITestResult childResult in result.Children) - PrintErrorResults(childResult); - } - - private void PrintNotRunResults(ITestResult result) - { - if (result.HasChildren) - foreach (ITestResult childResult in result.Children) - PrintNotRunResults(childResult); - else if (result.ResultState.Status == TestStatus.Skipped) - WriteSingleResult(result); - } - - private void PrintTestProperties(ITest test) - { - foreach (PropertyEntry entry in test.Properties) - writer.WriteLine(" {0}: {1}", entry.Name, entry.Value); - } - - private void PrintAllResults(ITestResult result, string indent) - { - string status = null; - switch (result.ResultState.Status) - { - case TestStatus.Failed: - status = "FAIL"; - break; - case TestStatus.Skipped: - status = "SKIP"; - break; - case TestStatus.Inconclusive: - status = "INC "; - break; - case TestStatus.Passed: - status = "OK "; - break; - } - - writer.Write(status); - writer.Write(indent); - writer.WriteLine(result.Name); - - if (result.HasChildren) - foreach (ITestResult childResult in result.Children) - PrintAllResults(childResult, indent + " "); - } - - private void WriteSingleResult(ITestResult result) - { - writer.WriteLine(); - writer.WriteLine("{0}) {1} ({2})", ++reportCount, result.Name, result.FullName); - - if (result.Message != null && result.Message != string.Empty) - writer.WriteLine(" {0}", result.Message); - - if (result.StackTrace != null && result.StackTrace != string.Empty) - writer.WriteLine(result.ResultState == ResultState.Failure - ? StackFilter.Filter(result.StackTrace) - : result.StackTrace + NUnit.Env.NewLine); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Runner/ResultSummary.cs b/test/NUnitLite/src/framework/Runner/ResultSummary.cs deleted file mode 100644 index c79db6bad..000000000 --- a/test/NUnitLite/src/framework/Runner/ResultSummary.cs +++ /dev/null @@ -1,168 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Api; - -namespace NUnitLite.Runner -{ - /// - /// Helper class used to summarize the result of a test run - /// - public class ResultSummary - { - private int testCount; - private int passCount; - private int errorCount; - private int failureCount; - private int notRunCount; - private int inconclusiveCount; - private int ignoreCount; - private int skipCount; - private int invalidCount; - - /// - /// Initializes a new instance of the class. - /// - /// The result. - public ResultSummary(ITestResult result) - { - Visit(result); - } - - /// - /// Gets the test count. - /// - /// The test count. - public int TestCount - { - get { return testCount; } - } - - /// - /// Gets the count of passed tests - /// - public int PassCount - { - get { return passCount; } - } - - /// - /// Gets the error count. - /// - /// The error count. - public int ErrorCount - { - get { return errorCount; } - } - - /// - /// Gets the failure count. - /// - /// The failure count. - public int FailureCount - { - get { return failureCount; } - } - - /// - /// Gets the not run count. - /// - /// The not run count. - public int NotRunCount - { - get { return notRunCount; } - } - - /// - /// Gets the ignore count - /// - public int IgnoreCount - { - get { return ignoreCount; } - } - - /// - /// Gets the skip count - /// - public int SkipCount - { - get { return skipCount; } - } - - /// - /// Gets the invalid count - /// - public int InvalidCount - { - get { return invalidCount; } - } - - /// - /// Gets the count of inconclusive results - /// - public int InconclusiveCount - { - get { return inconclusiveCount; } - } - - private void Visit(ITestResult result) - { - if (result.Test.IsSuite) - { - foreach (ITestResult r in result.Children) - Visit(r); - } - else - { - testCount++; - - switch (result.ResultState.Status) - { - case TestStatus.Passed: - passCount++; - break; - case TestStatus.Skipped: - if (result.ResultState == ResultState.Ignored) - ignoreCount++; - else if (result.ResultState == ResultState.Skipped) - skipCount++; - else if (result.ResultState == ResultState.NotRunnable) - invalidCount++; - notRunCount++; - break; - case TestStatus.Failed: - if (result.ResultState == ResultState.Failure) - failureCount++; - else - errorCount++; - break; - case TestStatus.Inconclusive: - inconclusiveCount++; - break; - } - - return; - } - } - } -} diff --git a/test/NUnitLite/src/framework/Runner/Silverlight/TestPage.g.cs b/test/NUnitLite/src/framework/Runner/Silverlight/TestPage.g.cs deleted file mode 100644 index 4a74714c5..000000000 --- a/test/NUnitLite/src/framework/Runner/Silverlight/TestPage.g.cs +++ /dev/null @@ -1,80 +0,0 @@ -#pragma checksum "D:\Dev\NUnit\nunitlite\silverlight\src\framework\Runner\Silverlight\TestPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "6F6202F16BB641581768BCB53F5200C8" -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.17626 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System; -using System.Windows; -using System.Windows.Automation; -using System.Windows.Automation.Peers; -using System.Windows.Automation.Provider; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Ink; -using System.Windows.Input; -using System.Windows.Interop; -using System.Windows.Markup; -using System.Windows.Media; -using System.Windows.Media.Animation; -using System.Windows.Media.Imaging; -using System.Windows.Resources; -using System.Windows.Shapes; -using System.Windows.Threading; - - -namespace NUnitLite.Runner.Silverlight { - - - public partial class TestPage : System.Windows.Controls.UserControl { - - internal System.Windows.Controls.Grid LayoutRoot; - - internal System.Windows.Controls.TextBlock Total; - - internal System.Windows.Controls.TextBlock Passed; - - internal System.Windows.Controls.TextBlock Failures; - - internal System.Windows.Controls.TextBlock Errors; - - internal System.Windows.Controls.TextBlock Inconclusive; - - internal System.Windows.Controls.TextBlock NotRun; - - internal System.Windows.Controls.TextBlock ScratchArea; - - internal System.Windows.Controls.TextBlock Notice; - - private bool _contentLoaded; - - /// - /// InitializeComponent - /// - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public void InitializeComponent() { - if (_contentLoaded) { - return; - } - _contentLoaded = true; - System.Windows.Application.LoadComponent(this, new System.Uri("/nunitlite;component/Runner/Silverlight/TestPage.xaml", System.UriKind.Relative)); - this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); - this.Total = ((System.Windows.Controls.TextBlock)(this.FindName("Total"))); - this.Passed = ((System.Windows.Controls.TextBlock)(this.FindName("Passed"))); - this.Failures = ((System.Windows.Controls.TextBlock)(this.FindName("Failures"))); - this.Errors = ((System.Windows.Controls.TextBlock)(this.FindName("Errors"))); - this.Inconclusive = ((System.Windows.Controls.TextBlock)(this.FindName("Inconclusive"))); - this.NotRun = ((System.Windows.Controls.TextBlock)(this.FindName("NotRun"))); - this.ScratchArea = ((System.Windows.Controls.TextBlock)(this.FindName("ScratchArea"))); - this.Notice = ((System.Windows.Controls.TextBlock)(this.FindName("Notice"))); - } - } -} - diff --git a/test/NUnitLite/src/framework/Runner/Silverlight/TestPage.xaml.cs b/test/NUnitLite/src/framework/Runner/Silverlight/TestPage.xaml.cs deleted file mode 100644 index 161bdffb2..000000000 --- a/test/NUnitLite/src/framework/Runner/Silverlight/TestPage.xaml.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Windows; -using System.Windows.Controls; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnitLite.Runner.Silverlight -{ - /// - /// TestPage is the display page for the test results - /// - public partial class TestPage : UserControl - { - private Assembly callingAssembly; - private ITestAssemblyRunner runner; - private TextWriter writer; - - public TestPage() - { - InitializeComponent(); - - this.runner = new NUnitLiteTestAssemblyRunner(new NUnitLiteTestAssemblyBuilder()); - this.callingAssembly = Assembly.GetCallingAssembly(); - this.writer = new TextBlockWriter(this.ScratchArea); - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - TextUI.WriteHeader(this.writer); - TextUI.WriteRuntimeEnvironment(this.writer); - - if (!LoadTestAssembly()) - writer.WriteLine("No tests found in assembly {0}", GetAssemblyName(callingAssembly)); - else - Dispatcher.BeginInvoke(() => ExecuteTests()); - } - - #region Helper Methods - - private bool LoadTestAssembly() - { - return runner.Load(callingAssembly, new Dictionary()); - } - - private string GetAssemblyName(Assembly assembly) - { - return new AssemblyName(assembly.FullName).Name; - } - - private void ExecuteTests() - { - ITestResult result = runner.Run(TestListener.NULL, TestFilter.Empty); - ResultReporter reporter = new ResultReporter(result, writer); - - reporter.ReportResults(); - - ResultSummary summary = reporter.Summary; - - this.Total.Text = summary.TestCount.ToString(); - this.Failures.Text = summary.FailureCount.ToString(); - this.Errors.Text = summary.ErrorCount.ToString(); - this.NotRun.Text = summary.NotRunCount.ToString(); - this.Passed.Text = summary.PassCount.ToString(); - this.Inconclusive.Text = summary.InconclusiveCount.ToString(); - - this.Notice.Visibility = Visibility.Collapsed; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/Runner/Silverlight/TextBlockWriter.cs b/test/NUnitLite/src/framework/Runner/Silverlight/TextBlockWriter.cs deleted file mode 100644 index 740294f2c..000000000 --- a/test/NUnitLite/src/framework/Runner/Silverlight/TextBlockWriter.cs +++ /dev/null @@ -1,106 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if SILVERLIGHT -using System; -using System.Diagnostics; -using System.IO; -using System.Windows.Controls; -using System.Windows.Documents; - -namespace NUnitLite.Runner.Silverlight -{ - /// - /// TextBlockWriter is a TextWriter that sends it's - /// output to a Silverlight TextBlock. - /// - public class TextBlockWriter : TextWriter - { - private TextBlock textBlock; - - public TextBlockWriter(TextBlock textBlock) - { - this.textBlock = textBlock; - } - - /// - /// Writes a character to the text stream. - /// - /// The character to write to the text stream. - /// - /// The is closed. - /// - /// - /// An I/O error occurs. - /// - public override void Write(char value) - { - textBlock.Text += value; - } - - /// - /// Writes a string to the text stream. - /// - /// The string to write. - /// - /// The is closed. - /// - /// - /// An I/O error occurs. - /// - public override void Write(string value) - { - textBlock.Text += value; - } - - /// - /// Writes a string followed by a line terminator to the text stream. - /// - /// The string to write. If is null, only the line termination characters are written. - /// - /// The is closed. - /// - /// - /// An I/O error occurs. - /// - public override void WriteLine(string value) - { - textBlock.Inlines.Add(value); - textBlock.Inlines.Add(new LineBreak()); - Debug.WriteLine(value); - } - - /// - /// When overridden in a derived class, returns the in which the output is written. - /// - /// - /// - /// The Encoding in which the output is written. - /// - public override System.Text.Encoding Encoding - { - get { return System.Text.Encoding.UTF8; } - } - } -} -#endif diff --git a/test/NUnitLite/src/framework/Runner/TextUI.cs b/test/NUnitLite/src/framework/Runner/TextUI.cs deleted file mode 100644 index e356cfdc0..000000000 --- a/test/NUnitLite/src/framework/Runner/TextUI.cs +++ /dev/null @@ -1,362 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using System.Collections; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.Framework.Internal.Filters; -using System.Diagnostics; - -namespace NUnitLite.Runner -{ - /// - /// TextUI is a general purpose class that runs tests and - /// outputs to a TextWriter. - /// - /// Call it from your Main like this: - /// new TextUI(textWriter).Execute(args); - /// OR - /// new TextUI().Execute(args); - /// The provided TextWriter is used by default, unless the - /// arguments to Execute override it using -out. The second - /// form uses the Console, provided it exists on the platform. - /// - /// NOTE: When running on a platform without a Console, such - /// as Windows Phone, the results will simply not appear if - /// you fail to specify a file in the call itself or as an option. - /// - public class TextUI : ITestListener - { - private CommandLineOptions commandLineOptions; - - private NUnit.ObjectList assemblies = new NUnit.ObjectList(); - - private TextWriter writer; - - private ITestListener listener; - - private ITestAssemblyRunner runner; - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - public TextUI() : this(ConsoleWriter.Out, TestListener.NULL) { } - - /// - /// Initializes a new instance of the class. - /// - /// The TextWriter to use. - public TextUI(TextWriter writer) : this(writer, TestListener.NULL) { } - - /// - /// Initializes a new instance of the class. - /// - /// The TextWriter to use. - /// The Test listener to use. - public TextUI(TextWriter writer, ITestListener listener) - { - // Set the default writer - may be overridden by the args specified - this.writer = writer; - this.runner = new NUnitLiteTestAssemblyRunner(new NUnitLiteTestAssemblyBuilder()); - this.listener = listener; - } - - #endregion - - #region Public Methods - - /// - /// Execute a test run based on the aruments passed - /// from Main. - /// - /// An array of arguments - public void Execute(string[] args) - { - // NOTE: Execute must be directly called from the - // test assembly in order for the mechanism to work. - Assembly callingAssembly = Assembly.GetCallingAssembly(); - - this.commandLineOptions = new CommandLineOptions(); - commandLineOptions.Parse(args); - - if (commandLineOptions.OutFile != null) - this.writer = new StreamWriter(commandLineOptions.OutFile); - - if (!commandLineOptions.NoHeader) - WriteHeader(this.writer); - - if (commandLineOptions.ShowHelp) - writer.Write(commandLineOptions.HelpText); - else if (commandLineOptions.Error) - { - writer.WriteLine(commandLineOptions.ErrorMessage); - writer.WriteLine(commandLineOptions.HelpText); - } - else - { - WriteRuntimeEnvironment(this.writer); - - if (commandLineOptions.Wait && commandLineOptions.OutFile != null) - writer.WriteLine("Ignoring /wait option - only valid for Console"); - -#if SILVERLIGHT - IDictionary loadOptions = new System.Collections.Generic.Dictionary(); -#else - IDictionary loadOptions = new Hashtable(); -#endif - //if (options.Load.Count > 0) - // loadOptions["LOAD"] = options.Load; - - //IDictionary runOptions = new Hashtable(); - //if (commandLineOptions.TestCount > 0) - // runOptions["RUN"] = commandLineOptions.Tests; - - ITestFilter filter = commandLineOptions.TestCount > 0 - ? new SimpleNameFilter(commandLineOptions.Tests) - : TestFilter.Empty; - - try - { - foreach (string name in commandLineOptions.Parameters) - assemblies.Add(Assembly.Load(name)); - - if (assemblies.Count == 0) - assemblies.Add(callingAssembly); - - // TODO: For now, ignore all but first assembly - Assembly assembly = assemblies[0] as Assembly; - - Randomizer.InitialSeed = commandLineOptions.InitialSeed; - - if (!runner.Load(assembly, loadOptions)) - { - AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(assembly); - Console.WriteLine("No tests found in assembly {0}", assemblyName.Name); - return; - } - - if (commandLineOptions.Explore) - ExploreTests(); - else - { - if (commandLineOptions.Include != null && commandLineOptions.Include != string.Empty) - { - TestFilter includeFilter = new SimpleCategoryExpression(commandLineOptions.Include).Filter; - - if (filter.IsEmpty) - filter = includeFilter; - else - filter = new AndFilter(filter, includeFilter); - } - - if (commandLineOptions.Exclude != null && commandLineOptions.Exclude != string.Empty) - { - TestFilter excludeFilter = new NotFilter(new SimpleCategoryExpression(commandLineOptions.Exclude).Filter); - - if (filter.IsEmpty) - filter = excludeFilter; - else if (filter is AndFilter) - ((AndFilter)filter).Add(excludeFilter); - else - filter = new AndFilter(filter, excludeFilter); - } - - RunTests(filter); - } - } - catch (FileNotFoundException ex) - { - writer.WriteLine(ex.Message); - } - catch (Exception ex) - { - writer.WriteLine(ex.ToString()); - } - finally - { - if (commandLineOptions.OutFile == null) - { - if (commandLineOptions.Wait) - { - Console.WriteLine("Press Enter key to continue . . ."); - Console.ReadLine(); - } - } - else - { - writer.Close(); - } - } - } - } - - /// - /// Write the standard header information to a TextWriter. - /// - /// The TextWriter to use - public static void WriteHeader(TextWriter writer) - { - Assembly executingAssembly = Assembly.GetExecutingAssembly(); -#if NUNITLITE - string title = "NUnitLite"; -#else - string title = "NUNit Framework"; -#endif - AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly); - System.Version version = assemblyName.Version; - string copyright = "Copyright (C) 2012, Charlie Poole"; - string build = ""; - - object[] attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); - if (attrs.Length > 0) - { - AssemblyTitleAttribute titleAttr = (AssemblyTitleAttribute)attrs[0]; - title = titleAttr.Title; - } - - attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); - if (attrs.Length > 0) - { - AssemblyCopyrightAttribute copyrightAttr = (AssemblyCopyrightAttribute)attrs[0]; - copyright = copyrightAttr.Copyright; - } - - attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false); - if (attrs.Length > 0) - { - AssemblyConfigurationAttribute configAttr = (AssemblyConfigurationAttribute)attrs[0]; - if (configAttr.Configuration.Length > 0) - build = string.Format("({0})", configAttr.Configuration); - } - - writer.WriteLine(String.Format("{0} {1} {2}", title, version.ToString(3), build)); - writer.WriteLine(copyright); - writer.WriteLine(); - } - - /// - /// Write information about the current runtime environment - /// - /// The TextWriter to be used - public static void WriteRuntimeEnvironment(TextWriter writer) - { - string clrPlatform = Type.GetType("Mono.Runtime", false) == null ? ".NET" : "Mono"; - - writer.WriteLine("Runtime Environment -"); - writer.WriteLine(" OS Version: {0}", Environment.OSVersion); - writer.WriteLine(" {0} Version: {1}", clrPlatform, Environment.Version); - writer.WriteLine(); - } - - #endregion - - #region Helper Methods - - private void RunTests(ITestFilter filter) - { - DateTime startTime = DateTime.Now; - - ITestResult result = runner.Run(this, filter); - new ResultReporter(result, writer).ReportResults(); - string resultFile = commandLineOptions.ResultFile; - string resultFormat = commandLineOptions.ResultFormat; - - if (resultFile != null || commandLineOptions.ResultFormat != null) - { - if (resultFile == null) - resultFile = "TestResult.xml"; - - if (resultFormat == "nunit2") - new NUnit2XmlOutputWriter(startTime).WriteResultFile(result, resultFile); - else - new NUnit3XmlOutputWriter(startTime).WriteResultFile(result, resultFile); - - Console.WriteLine(); - Console.WriteLine("Results saved as {0}.", resultFile); - } - } - - private void ExploreTests() - { - XmlNode testNode = runner.LoadedTest.ToXml(true); - - string listFile = commandLineOptions.ExploreFile; - TextWriter textWriter = listFile != null && listFile.Length > 0 - ? new StreamWriter(listFile) - : Console.Out; - -#if CLR_2_0 || CLR_4_0 - System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); - settings.Indent = true; - settings.Encoding = System.Text.Encoding.UTF8; - System.Xml.XmlWriter testWriter = System.Xml.XmlWriter.Create(textWriter, settings); -#else - System.Xml.XmlTextWriter testWriter = new System.Xml.XmlTextWriter(textWriter); - testWriter.Formatting = System.Xml.Formatting.Indented; -#endif - - testNode.WriteTo(testWriter); - testWriter.Close(); - - Console.WriteLine(); - Console.WriteLine("Test info saved as {0}.", listFile); - } - - #endregion - - #region ITestListener Members - - /// - /// A test has just started - /// - /// The test - public void TestStarted(ITest test) - { - if (commandLineOptions.LabelTestsInOutput) - writer.WriteLine("***** {0}", test.Name); - } - - /// - /// A test has just finished - /// - /// The result of the test - public void TestFinished(ITestResult result) - { - } - - /// - /// A test has produced some text output - /// - /// A TestOutput object holding the text that was written - public void TestOutput(TestOutput testOutput) - { - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/TestCaseData.cs b/test/NUnitLite/src/framework/TestCaseData.cs deleted file mode 100644 index dd14de690..000000000 --- a/test/NUnitLite/src/framework/TestCaseData.cs +++ /dev/null @@ -1,389 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Collections.Specialized; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -// TODO: Remove conditional code -namespace NUnit.Framework -{ - /// - /// The TestCaseData class represents a set of arguments - /// and other parameter info to be used for a parameterized - /// test case. It provides a number of instance modifiers - /// for use in initializing the test case. - /// - /// Note: Instance modifiers are getters that return - /// the same instance after modifying it's state. - /// - public class TestCaseData : ITestCaseData - { - - #region Instance Fields - - /// - /// The argument list to be provided to the test - /// - private object[] arguments; - - /// - /// The expected result to be returned - /// - private object expectedResult; - - /// - /// Data about any expected exception. - /// - private ExpectedExceptionData exceptionData; - - /// - /// A dictionary of properties, used to add information - /// to tests without requiring the class to change. - /// - private IPropertyBag properties; - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// The arguments. - public TestCaseData(params object[] args) - { - this.RunState = RunState.Runnable; - - if (args == null) - this.arguments = new object[] { null }; - else - this.arguments = args; - } - - /// - /// Initializes a new instance of the class. - /// - /// The argument. - public TestCaseData(object arg) - { - this.RunState = RunState.Runnable; - this.arguments = new object[] { arg }; - } - - /// - /// Initializes a new instance of the class. - /// - /// The first argument. - /// The second argument. - public TestCaseData(object arg1, object arg2) - { - this.RunState = RunState.Runnable; - this.arguments = new object[] { arg1, arg2 }; - } - - /// - /// Initializes a new instance of the class. - /// - /// The first argument. - /// The second argument. - /// The third argument. - public TestCaseData(object arg1, object arg2, object arg3) - { - this.RunState = RunState.Runnable; - this.arguments = new object[] { arg1, arg2, arg3 }; - } - - #endregion - - #region ITestCaseData Members - - /// - /// Gets the argument list to be provided to the test - /// - public object[] Arguments - { - get { return arguments; } - } - - /// - /// Gets the expected result - /// - public object ExpectedResult - { - get { return expectedResult; } - set - { - expectedResult = value; - HasExpectedResult = true; - } - } - - private bool hasExpectedResult; - /// - /// Returns true if the expected result has been set - /// - public bool HasExpectedResult - { - get { return hasExpectedResult; } - set { hasExpectedResult = value; } - } - - /// - /// Gets data about any expected exception. - /// - public ExpectedExceptionData ExceptionData - { - get { return exceptionData; } - } - - private string testName; - /// - /// Gets the name to be used for the test - /// - public string TestName - { - get { return testName; } - set { testName = value; } - } - - private RunState runState; - /// - /// Gets the RunState for this test case. - /// - public RunState RunState - { - get { return runState; } - set { runState = value; } - } - - /// - /// Gets the property dictionary for this test - /// - public IPropertyBag Properties - { - get - { - if (properties == null) - properties = new NUnit.Framework.Internal.PropertyBag(); - - return properties; - } - } - - #endregion - - #region Public Properties - NUnit 2.6 Compatibility - - /// - /// Gets the expected result. - /// - public object Result - { - get { return expectedResult; } - } - - /// - /// The type of exception expected - /// - public Type ExpectedException - { - get { return exceptionData.ExpectedExceptionType; } - } - - /// - /// The full name of the expected exception type - /// - public string ExpectedExceptionName - { - get { return exceptionData.ExpectedExceptionName; } - } - - /// - /// The message to expect on any exception - /// - public string ExpectedExceptionMessage - { - get { return exceptionData.ExpectedMessage; } - } - - /// - /// The type of match to be made on the message - /// - public MessageMatch MatchType - { - get { return exceptionData.MatchType; } - } - - #endregion - - #region Fluent Instance Modifiers - - /// - /// Sets the expected result for the test - /// - /// The expected result - /// A modified TestCaseData - public TestCaseData Returns(object result) - { - this.ExpectedResult = result; - return this; - } - - /// - /// Sets the expected exception type for the test - /// - /// Type of the expected exception. - /// The modified TestCaseData instance - public TestCaseData Throws(Type exceptionType) - { - //this.expectedExceptionType = exceptionType; - exceptionData.ExpectedExceptionName = exceptionType.FullName; - return this; - } - - /// - /// Sets the expected exception type for the test - /// - /// FullName of the expected exception. - /// The modified TestCaseData instance - public TestCaseData Throws(string exceptionName) - { - exceptionData.ExpectedExceptionName = exceptionName; - return this; - } - - /// - /// Sets the name of the test case - /// - /// The modified TestCaseData instance - public TestCaseData SetName(string name) - { - this.TestName = name; - return this; - } - - /// - /// Sets the description for the test case - /// being constructed. - /// - /// The description. - /// The modified TestCaseData instance. - public TestCaseData SetDescription(string description) - { - this.Properties.Set(PropertyNames.Description, description); - return this; - } - - /// - /// Applies a category to the test - /// - /// - /// - public TestCaseData SetCategory(string category) - { - this.Properties.Add(PropertyNames.Category, category); - return this; - } - - /// - /// Applies a named property to the test - /// - /// - /// - /// - public TestCaseData SetProperty(string propName, string propValue) - { - this.Properties.Add(propName, propValue); - return this; - } - - /// - /// Applies a named property to the test - /// - /// - /// - /// - public TestCaseData SetProperty(string propName, int propValue) - { - this.Properties.Add(propName, propValue); - return this; - } - - /// - /// Applies a named property to the test - /// - /// - /// - /// - public TestCaseData SetProperty(string propName, double propValue) - { - this.Properties.Add(propName, propValue); - return this; - } - - /// - /// Ignores this TestCase. - /// - /// - public TestCaseData Ignore() - { - this.RunState = RunState.Ignored; - return this; - } - - /// - /// Marks the test case as explicit. - /// - public TestCaseData Explicit() { - this.RunState = RunState.Explicit; - return this; - } - - /// - /// Marks the test case as explicit, specifying the reason. - /// - public TestCaseData Explicit(string reason) - { - this.RunState = RunState.Explicit; - this.Properties.Set(PropertyNames.SkipReason, reason); - return this; - } - - /// - /// Ignores this TestCase, specifying the reason. - /// - /// The reason. - /// - public TestCaseData Ignore(string reason) - { - this.RunState = RunState.Ignored; - this.Properties.Set(PropertyNames.SkipReason, reason); - return this; - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/TestContext.cs b/test/NUnitLite/src/framework/TestContext.cs deleted file mode 100644 index 9b86806d8..000000000 --- a/test/NUnitLite/src/framework/TestContext.cs +++ /dev/null @@ -1,257 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework -{ - /// - /// Provide the context information of the current test. - /// This is an adapter for the internal ExecutionContext - /// class, hiding the internals from the user test. - /// - public class TestContext - { - private TestExecutionContext ec; - private TestAdapter test; - private ResultAdapter result; - - #region Constructor - - /// - /// Construct a TestContext for an ExecutionContext - /// - /// The ExecutionContext to adapt - public TestContext(TestExecutionContext ec) - { - this.ec = ec; - } - - #endregion - - #region Properties - - /// - /// Get the current test context. This is created - /// as needed. The user may save the context for - /// use within a test, but it should not be used - /// outside the test for which it is created. - /// - public static TestContext CurrentContext - { - get { return new TestContext(TestExecutionContext.CurrentContext); } - } - - /// - /// Get a representation of the current test. - /// - public TestAdapter Test - { - get - { - if (test == null) - test = new TestAdapter(ec.CurrentTest); - - return test; - } - } - - /// - /// Gets a Representation of the TestResult for the current test. - /// - public ResultAdapter Result - { - get - { - if (result == null) - result = new ResultAdapter(ec.CurrentResult); - - return result; - } - } - -#if !NETCF - /// - /// Gets the directory containing the current test assembly. - /// - public string TestDirectory - { - get - { - return AssemblyHelper.GetDirectoryName(ec.CurrentTest.FixtureType.Assembly); - } - } -#endif - - /// - /// Gets the directory to be used for outputing files created - /// by this test run. - /// - public string WorkDirectory - { - get - { - return ec.WorkDirectory; - } - } - - public RandomGenerator Random - { - get - { - return ec.RandomGenerator; - } - } - - #endregion - - #region Nested TestAdapter Class - - /// - /// TestAdapter adapts a Test for consumption by - /// the user test code. - /// - public class TestAdapter - { - private Test test; - - #region Constructor - - /// - /// Construct a TestAdapter for a Test - /// - /// The Test to be adapted - public TestAdapter(Test test) - { - this.test = test; - } - - #endregion - - #region Properties - - /// - /// Gets the unique Id of a test - /// - public int ID - { - get { return test.Id; } - } - - /// - /// The name of the test, which may or may not be - /// the same as the method name. - /// - public string Name - { - get - { - return test.Name; - } - } - - /// - /// The name of the method representing the test. - /// - public string MethodName - { - get - { - return test is TestMethod - ? ((TestMethod)test).Method.Name - : null; - } - } - - /// - /// The FullName of the test - /// - public string FullName - { - get - { - return test.FullName; - } - } - - /// - /// The properties of the test. - /// - public IPropertyBag Properties - { - get - { - return test.Properties; - } - } - - #endregion - } - - #endregion - - #region Nested ResultAdapter Class - - /// - /// ResultAdapter adapts a TestResult for consumption by - /// the user test code. - /// - public class ResultAdapter - { - private TestResult result; - - #region Constructor - - /// - /// Construct a ResultAdapter for a TestResult - /// - /// The TestResult to be adapted - public ResultAdapter(TestResult result) - { - this.result = result; - } - - #endregion - - #region Properties - - /// - /// Gets a ResultState representing the outcome of the test. - /// - public ResultState Outcome - { - get - { - return result.ResultState; - } - } - - #endregion - } - - #endregion - } -} diff --git a/test/NUnitLite/src/framework/nunitlite-2.0.csproj b/test/NUnitLite/src/framework/nunitlite-2.0.csproj deleted file mode 100644 index 2414648b7..000000000 --- a/test/NUnitLite/src/framework/nunitlite-2.0.csproj +++ /dev/null @@ -1,382 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {C24A3FC4-2541-4E9C-BADD-564777610B75} - Library - Properties - NUnitLite - nunitlite - - - 3.5 - - - v2.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - obj\$(Configuration)\net-2.0\ - - - true - full - false - TRACE;DEBUG;NET_2_0,CLR_2_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Debug\net-2.0\nunitlite.xml - ..\..\bin\Debug\net-2.0\ - - - pdbonly - true - TRACE;NET_2_0,CLR_2_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Release\net-2.0\nunitlite.xml - ..\..\bin\Release\net-2.0\ - - - true - - - nunit.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-3.5.csproj b/test/NUnitLite/src/framework/nunitlite-3.5.csproj deleted file mode 100644 index e9a088ab8..000000000 --- a/test/NUnitLite/src/framework/nunitlite-3.5.csproj +++ /dev/null @@ -1,367 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {43B24DC5-16D6-45EF-93F1-B021B785A892} - Library - Properties - NUnitLite - nunitlite - - - 3.5 - - - v3.5 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-3.5\ - - - true - full - false - ..\..\bin\Debug\net-3.5\ - TRACE;DEBUG;NET_3_5, CLR_2_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Debug\net-3.5\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\net-3.5\ - TRACE;NET_3_5, CLR_2_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Release\net-3.5\nunitlite.xml - - - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-4.0.csproj b/test/NUnitLite/src/framework/nunitlite-4.0.csproj deleted file mode 100644 index e7fbc333a..000000000 --- a/test/NUnitLite/src/framework/nunitlite-4.0.csproj +++ /dev/null @@ -1,368 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {1567BCCE-7BE9-4815-84D7-7F794DB39081} - Library - Properties - NUnitLite - nunitlite - - - 3.5 - - - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-4.0\ - - - true - full - false - ..\..\bin\Debug\net-4.0\ - TRACE;DEBUG;NET_4_0, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Debug\net-4.0\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\net-4.0\ - TRACE;NET_4_0, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Release\net-4.0\nunitlite.xml - - - true - - - nunit.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-4.5.csproj b/test/NUnitLite/src/framework/nunitlite-4.5.csproj deleted file mode 100644 index 1e8a2790d..000000000 --- a/test/NUnitLite/src/framework/nunitlite-4.5.csproj +++ /dev/null @@ -1,372 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {D12F0F7B-8DE3-43EC-BA49-41052D065A9B} - Library - Properties - NUnitLite - nunitlite - - - 3.5 - - - v4.5 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-4.5\ - - - true - full - false - ..\..\bin\Debug\net-4.5\ - TRACE;DEBUG;NET_4_5, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Debug\net-4.5\nunitlite.xml - false - - - pdbonly - true - ..\..\bin\Release\net-4.5\ - TRACE;NET_4_5, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - ..\..\bin\Release\net-4.5\nunitlite.xml - false - - - true - - - nunit.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-netcf-2.0.csproj b/test/NUnitLite/src/framework/nunitlite-netcf-2.0.csproj deleted file mode 100644 index 6bac0efb0..000000000 --- a/test/NUnitLite/src/framework/nunitlite-netcf-2.0.csproj +++ /dev/null @@ -1,336 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {BED999D7-F594-4CE4-A037-E40E2B9C1288} - Library - Properties - NUnit.Framework - nunitlite - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - NUnitLite - v2.0 - Windows CE - - - obj\$(Configuration)\netcf-2.0\ - - - true - full - false - ..\..\bin\Debug\netcf-2.0 - TRACE;DEBUG;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - ..\..\bin\Debug\netcf-2.0\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\netcf-2.0 - TRACE;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - ..\..\bin\Release\netcf-2.0\nunitlite.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-netcf-3.5.csproj b/test/NUnitLite/src/framework/nunitlite-netcf-3.5.csproj deleted file mode 100644 index aaa029076..000000000 --- a/test/NUnitLite/src/framework/nunitlite-netcf-3.5.csproj +++ /dev/null @@ -1,339 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {5F6CB3DC-5CE5-4C6A-AB23-936DB3B35DCC} - Library - Properties - NUnit.Framework - nunitlite - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - nunitlite_netcf_3._5 - v3.5 - Windows CE - - - obj\$(Configuration)\netcf-3.5\ - - - true - full - false - ..\..\bin\Debug\netcf-3.5\ - TRACE;DEBUG;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - ..\..\bin\Debug\netcf-3.5\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\netcf-3.5\ - TRACE;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - ..\..\bin\Release\netcf-3.5\nunitlite.xml - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-sl-3.0.csproj b/test/NUnitLite/src/framework/nunitlite-sl-3.0.csproj deleted file mode 100644 index edc8e7357..000000000 --- a/test/NUnitLite/src/framework/nunitlite-sl-3.0.csproj +++ /dev/null @@ -1,353 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {02B02379-2596-4E45-8B10-835D62EA2D9E} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnit.Framework - nunitlite - Silverlight - v3.0 - $(TargetFrameworkVersion) - false - true - true - false - - obj\$(Configuration)\sl-3.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-3.0\ - TRACE;DEBUG;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - ..\..\bin\Debug\sl-3.0\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\sl-3.0\ - TRACE;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - ..\..\bin\Release\sl-3.0\nunitlite.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TestPage.xaml - - - - Code - - - - - - - - - - - - MSBuild:Compile - Designer - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-sl-4.0.csproj b/test/NUnitLite/src/framework/nunitlite-sl-4.0.csproj deleted file mode 100644 index e12b3386e..000000000 --- a/test/NUnitLite/src/framework/nunitlite-sl-4.0.csproj +++ /dev/null @@ -1,361 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {41326141-EB24-4984-9D9B-5CFAA55946BA} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnit.Framework - nunitlite - Silverlight - v4.0 - $(TargetFrameworkVersion) - false - true - true - obj\$(Configuration)\sl-4.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-4.0\ - TRACE;DEBUG;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - ..\..\bin\Debug\sl-4.0\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\sl-4.0\ - TRACE;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - ..\..\bin\Release\sl-4.0\nunitlite.xml - - - true - - - nunit.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TestPage.xaml - - - - - - - - Code - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite-sl-5.0.csproj b/test/NUnitLite/src/framework/nunitlite-sl-5.0.csproj deleted file mode 100644 index 23b801512..000000000 --- a/test/NUnitLite/src/framework/nunitlite-sl-5.0.csproj +++ /dev/null @@ -1,356 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnit.Framework - nunitlite - Silverlight - v5.0 - $(TargetFrameworkVersion) - false - true - true - - obj\$(Configuration)\sl-5.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-5.0\ - TRACE;DEBUG;SILVERLIGHT;SL_5_0;CLR_4_0;NUNITLITE - true - true - prompt - 4 - ..\..\bin\Debug\sl-5.0\nunitlite.xml - - - pdbonly - true - ..\..\bin\Release\sl-5.0\ - TRACE;SILVERLIGHT;SL_5_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - ..\..\bin\Release\sl-5.0\nunitlite.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TestPage.xaml - - - - Code - - - - - - - - - - - - MSBuild:Compile - Designer - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/framework/nunitlite.framework.build b/test/NUnitLite/src/framework/nunitlite.framework.build deleted file mode 100644 index 84b28dd0f..000000000 --- a/test/NUnitLite/src/framework/nunitlite.framework.build +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/NUnitLite/src/mock-assembly/MockAssembly.cs b/test/NUnitLite/src/mock-assembly/MockAssembly.cs deleted file mode 100644 index 11b28401d..000000000 --- a/test/NUnitLite/src/mock-assembly/MockAssembly.cs +++ /dev/null @@ -1,300 +0,0 @@ -// **************************************************************** -// This is free software licensed under the NUnit license. You -// may obtain a copy of the license as well as information regarding -// copyright ownership at http://nunit.org. -// **************************************************************** -using System; -using NUnit.Framework; -using NUnit.Framework.Internal; - -namespace NUnit.Tests -{ - namespace Assemblies - { - /// - /// Constant definitions for the mock-assembly dll. - /// - public class MockAssembly - { - public static int Classes = 9; - public static int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly - - public static int Tests = MockTestFixture.Tests - + Singletons.OneTestCase.Tests - + TestAssembly.MockTestFixture.Tests - + IgnoredFixture.Tests - + ExplicitFixture.Tests - + BadFixture.Tests - + FixtureWithTestCases.Tests - + ParameterizedFixture.Tests - + GenericFixtureConstants.Tests; - - public static int Suites = MockTestFixture.Suites - + Singletons.OneTestCase.Suites - + TestAssembly.MockTestFixture.Suites - + IgnoredFixture.Suites - + ExplicitFixture.Suites - + BadFixture.Suites - + FixtureWithTestCases.Suites - + ParameterizedFixture.Suites - + GenericFixtureConstants.Suites - + NamespaceSuites; - - public static readonly int Nodes = Tests + Suites; - - public static int ExplicitFixtures = 1; - public static int SuitesRun = Suites - ExplicitFixtures; - - public static int Ignored = MockTestFixture.Ignored + IgnoredFixture.Tests; - public static int Explicit = MockTestFixture.Explicit + ExplicitFixture.Tests; - public static int NotRunnable = MockTestFixture.NotRunnable + BadFixture.Tests; - public static int NotRun = Ignored + Explicit + NotRunnable; - public static int TestsRun = Tests - NotRun; - public static int ResultCount = Tests - Explicit; - - public static int Errors = MockTestFixture.Errors; - public static int Failures = MockTestFixture.Failures; - public static int ErrorsAndFailures = Errors + Failures; - - public static int Categories = MockTestFixture.Categories; - -#if !NETCF - public static string AssemblyPath = AssemblyHelper.GetAssemblyPath(typeof(MockAssembly).Assembly); -#endif - } - - //public class MockSuite - //{ - // [Suite] - // public static TestSuite Suite - // { - // get - // { - // return new TestSuite( "MockSuite" ); - // } - // } - //} - - [TestFixture(Description="Fake Test Fixture")] - [Category("FixtureCategory")] - public class MockTestFixture - { - public const int Tests = 11; - public const int Suites = 1; - - public const int Ignored = 1; - public const int Explicit = 1; - public const int NotRunnable = 2; - public const int NotRun = Ignored + Explicit + NotRunnable; - public const int TestsRun = Tests - NotRun; - public const int ResultCount = Tests - Explicit; - - public const int Failures = 1; - public const int Errors = 1; - public const int ErrorsAndFailures = Errors + Failures; - public const int Inconclusive = 1; - - public const int Categories = 5; - public const int MockCategoryTests = 2; - - [Test(Description="Mock Test #1")] - public void MockTest1() - {} - - [Test] - [Category("MockCategory")] - [Property("Severity","Critical")] - [Description("This is a really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long description")] - public void MockTest2() - {} - - [Test] - [Category("MockCategory")] - [Category("AnotherCategory")] - public void MockTest3() - { Assert.Pass("Succeeded!"); } - - [Test] - protected static void MockTest5() - {} - - [Test] - public void FailingTest() - { - Assert.Fail("Intentional failure"); - } - - [Test, Property("TargetMethod", "SomeClassName"), Property("Size", 5), /*Property("TargetType", typeof( System.Threading.Thread ))*/] - public void TestWithManyProperties() - {} - - [Test] - [Ignore("ignoring this test method for now")] - [Category("Foo")] - public void MockTest4() - {} - - [Test, Explicit] - [Category( "Special" )] - public void ExplicitlyRunTest() - {} - - [Test] - public void NotRunnableTest( int a, int b) - { - } - - [Test] - public void InconclusiveTest() - { - Assert.Inconclusive("No valid data"); - } - - [Test] - public void TestWithException() - { - MethodThrowsException(); - } - - private void MethodThrowsException() - { - throw new Exception("Intentional Exception"); - } - } - } - - namespace Singletons - { - [TestFixture] - public class OneTestCase - { - public static readonly int Tests = 1; - public static readonly int Suites = 1; - - [Test] - public virtual void TestCase() - {} - } - } - - namespace TestAssembly - { - [TestFixture] - public class MockTestFixture - { - public static readonly int Tests = 1; - public static readonly int Suites = 1; - - [Test] - public void MyTest() - { - } - } - } - - [TestFixture, Ignore] - public class IgnoredFixture - { - public static readonly int Tests = 3; - public static readonly int Suites = 1; - - [Test] - public void Test1() { } - - [Test] - public void Test2() { } - - [Test] - public void Test3() { } - } - - [TestFixture,Explicit] - public class ExplicitFixture - { - public static readonly int Tests = 2; - public static readonly int Suites = 1; - public static readonly int Nodes = Tests + Suites; - - [Test] - public void Test1() { } - - [Test] - public void Test2() { } - } - - [TestFixture] - public class BadFixture - { - public static readonly int Tests = 1; - public static readonly int Suites = 1; - - public BadFixture(int val) { } - - [Test] - public void SomeTest() { } - } - - [TestFixture] - public class FixtureWithTestCases - { - public static readonly int Tests = 4; - public static readonly int Suites = 3; - - [TestCase(2, 2, ExpectedResult=4)] - [TestCase(9, 11, ExpectedResult=20)] - public int MethodWithParameters(int x, int y) - { - return x+y; - } - -#if CLR_2_0 || CLR_4_0 - [TestCase(2, 4)] - [TestCase(9.2, 11.7)] - public void GenericMethod(T x, T y) - { - } -#endif - } - - [TestFixture(5)] - [TestFixture(42)] - public class ParameterizedFixture - { - public static readonly int Tests = 4; - public static readonly int Suites = 3; - - public ParameterizedFixture(int num) { } - - [Test] - public void Test1() { } - - [Test] - public void Test2() { } - } - - public class GenericFixtureConstants - { -#if CLR_2_0 || CLR_4_0 - public static readonly int Tests = 4; - public static readonly int Suites = 3; -#else - public static readonly int Tests = 0; - public static readonly int Suites = 0; -#endif - } - -#if CLR_2_0 || CLR_4_0 - [TestFixture(5)] - [TestFixture(11.5)] - public class GenericFixture - { - public GenericFixture(T num){ } - - [Test] - public void Test1() { } - - [Test] - public void Test2() { } - } -#endif -} diff --git a/test/NUnitLite/src/mock-assembly/Properties/AssemblyInfo.cs b/test/NUnitLite/src/mock-assembly/Properties/AssemblyInfo.cs deleted file mode 100644 index bd542a5fb..000000000 --- a/test/NUnitLite/src/mock-assembly/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("mock-assembly")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("mock-assembly")] -[assembly: AssemblyCopyright("Copyright © 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e33f0417-0b18-4d8c-9142-6ac47cd6c29a")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -#if !PocketPC && !WindowsCE && !NETCF -[assembly: AssemblyFileVersion("1.0.0.0")] -#endif diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-2.0.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-2.0.csproj deleted file mode 100644 index 41d6d117e..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-2.0.csproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B} - Library - Properties - mock_assembly - mock-assembly - v2.0 - 512 - - obj\$(Configuration)\net-2.0\ - - - true - full - ..\..\bin\Debug\net-2.0\ - false - TRACE;DEBUG;CLR_2_0 - prompt - 4 - - - pdbonly - true - TRACE;CLR_2_0 - prompt - 4 - ..\..\bin\Release\net-2.0\ - - - - - - - - - - - {C24A3FC4-2541-4E9C-BADD-564777610B75} - nunitlite-2.0 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-3.5.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-3.5.csproj deleted file mode 100644 index 321f0caef..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-3.5.csproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7} - Library - Properties - mock_assembly - mock-assembly - v3.5 - 512 - - obj\$(Configuration)\net-3.5\ - - - true - full - false - ..\..\bin\Debug\net-3.5\ - TRACE;DEBUG;CLR_2_0 - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\net-3.5\ - TRACE;CLR_2_0 - prompt - 4 - - - - - - - - - - - {43B24DC5-16D6-45EF-93F1-B021B785A892} - nunitlite-3.5 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-4.0.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-4.0.csproj deleted file mode 100644 index d6118f9ad..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-4.0.csproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A} - Library - Properties - mock_assembly - mock-assembly - v4.0 - 512 - - obj\$(Configuration)\net-4.0\ - - - true - full - false - ..\..\bin\Debug\net-4.0\ - TRACE;DEBUG;CLR_4_0 - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\net-4.0\ - TRACE;CLR_4_0 - prompt - 4 - - - - - - - - - - - {1567BCCE-7BE9-4815-84D7-7F794DB39081} - nunitlite-4.0 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-4.5.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-4.5.csproj deleted file mode 100644 index ee4b2a1e2..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-4.5.csproj +++ /dev/null @@ -1,58 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {A57FFBD8-684A-4868-A4E1-A5D28EC6EA3B} - Library - Properties - mock_assembly - mock-assembly - v4.5 - 512 - - obj\$(Configuration)\net-4.5\ - - - true - full - false - ..\..\bin\Debug\net-4.5\ - TRACE;DEBUG;CLR_4_0 - prompt - 4 - false - - - pdbonly - true - ..\..\bin\Release\net-4.5\ - TRACE;CLR_4_0 - prompt - 4 - false - - - - - - - - - - - {d12f0f7b-8de3-43ec-ba49-41052d065a9b} - nunitlite-4.5 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-netcf-2.0.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-netcf-2.0.csproj deleted file mode 100644 index 6c05f8589..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-netcf-2.0.csproj +++ /dev/null @@ -1,79 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {33EA4538-3452-42ED-92A9-4CC3B25032AD} - Library - Properties - mock_assembly_netcf_2._0 - mock-assembly-netcf-2.0 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 3C41C503-53EF-4c2a-8DD4-A8217CAD115E - 4.20 - mock_assembly_netcf_2._0 - v2.0 - Pocket PC 2003 - - - obj\$(Configuration)\netcf-2.0\ - - - true - full - false - ..\..\bin\Debug\netcf-2.0 - TRACE;DEBUG;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\..\bin\Release\netcf-2.0 - TRACE;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - {BED999D7-F594-4CE4-A037-E40E2B9C1288} - nunitlite-netcf-2.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-netcf-3.5.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-netcf-3.5.csproj deleted file mode 100644 index 80708506c..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-netcf-3.5.csproj +++ /dev/null @@ -1,82 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {B0C85907-1103-44F4-ACFF-6A1B9170C0B1} - Library - Properties - mock_assembly_netcf_3._5 - mock-assembly-netcf-3.5 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - mock_assembly_netcf_3._5 - v3.5 - Windows Mobile 5.0 Pocket PC SDK - - - obj\$(Configuration)\netcf-3.5\ - - - true - full - false - ..\..\bin\Debug\netcf-3.5\ - TRACE;DEBUG;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\..\bin\Release\netcf-3.5\ - TRACE;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - {5F6CB3DC-5CE5-4C6A-AB23-936DB3B35DCC} - nunitlite-netcf-3.5 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-sl-3.0.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-sl-3.0.csproj deleted file mode 100644 index c3abba8e9..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-sl-3.0.csproj +++ /dev/null @@ -1,80 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - mock_assembly - mock-assembly - Silverlight - v3.0 - $(TargetFrameworkVersion) - false - true - true - false - - obj\$(Configuration)\sl-3.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-3.0\ - TRACE;DEBUG;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-3.0\ - TRACE;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - - - - - - - - - - {02B02379-2596-4E45-8B10-835D62EA2D9E} - nunitlite-sl-3.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-sl-4.0.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-sl-4.0.csproj deleted file mode 100644 index 285795433..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-sl-4.0.csproj +++ /dev/null @@ -1,78 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {3C1249FC-B5DF-4E3A-ADDD-817526254876} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - mock_assembly - mock-assembly - Silverlight - v4.0 - $(TargetFrameworkVersion) - false - true - true - obj\$(Configuration)\sl-4.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-4.0\ - TRACE;DEBUG;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-4.0\ - TRACE;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - - - - - - - - - - {41326141-EB24-4984-9D9B-5CFAA55946BA} - nunitlite-sl-4.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly-sl-5.0.csproj b/test/NUnitLite/src/mock-assembly/mock-assembly-sl-5.0.csproj deleted file mode 100644 index 2a4b0224a..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly-sl-5.0.csproj +++ /dev/null @@ -1,79 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - mock_assembly - mock-assembly - Silverlight - v5.0 - $(TargetFrameworkVersion) - false - true - true - - obj\$(Configuration)\sl-5.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-5.0\ - TRACE;DEBUG;SILVERLIGHT;SL_5_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-5.0\ - TRACE;SILVERLIGHT;SL_5_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - - - - - - - - - - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3} - nunitlite-sl-5.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/mock-assembly/mock-assembly.build b/test/NUnitLite/src/mock-assembly/mock-assembly.build deleted file mode 100644 index bc8550b6d..000000000 --- a/test/NUnitLite/src/mock-assembly/mock-assembly.build +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/NUnitLite/src/testdata/AssemblyInfo.cs b/test/NUnitLite/src/testdata/AssemblyInfo.cs deleted file mode 100644 index fd9e52a38..000000000 --- a/test/NUnitLite/src/testdata/AssemblyInfo.cs +++ /dev/null @@ -1,44 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("NUnitLite Test Data")] -[assembly: AssemblyDescription("Data for the tests of the NUnitLite testing framework")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NUnitLite")] -[assembly: AssemblyCopyright("Copyright © 2007-2012, Charlie Poole")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] -#if !PocketPC && !WindowsCE && !NETCF -[assembly: AssemblyFileVersion("1.0.0.0")] -#endif - -// Under Silverlight, it's only possible to reflect -// over members that would be accessible normally. -#if SILVERLIGHT -[assembly: InternalsVisibleTo("nunitlite")] -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/AssertCountFixture.cs b/test/NUnitLite/src/testdata/AssertCountFixture.cs deleted file mode 100644 index 2b2076461..000000000 --- a/test/NUnitLite/src/testdata/AssertCountFixture.cs +++ /dev/null @@ -1,51 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework; - -namespace NUnit.TestData -{ - [TestFixture] - public class AssertCountFixture - { - public static readonly int ExpectedAssertCount = 5; - - [Test] - public void BooleanAssert() - { - Assert.That(2 + 2 == 4); - } - [Test] - public void ConstraintAssert() - { - Assert.That(2 + 2, Is.EqualTo(4)); - } - [Test] - public void ThreeAsserts() - { - Assert.That(2 + 2 == 4); - Assert.That(2 + 2, Is.EqualTo(4)); - Assert.That(2 + 2, Is.EqualTo(5)); - } - } -} diff --git a/test/NUnitLite/src/testdata/AssertFailFixture.cs b/test/NUnitLite/src/testdata/AssertFailFixture.cs deleted file mode 100644 index 6b3b8930f..000000000 --- a/test/NUnitLite/src/testdata/AssertFailFixture.cs +++ /dev/null @@ -1,50 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.AssertFailFixture -{ - [TestFixture] - public class AssertFailFixture - { - [Test] - public void CallAssertFail() - { - Assert.Fail(); - } - - [Test] - public void CallAssertFailWithMessage() - { - Assert.Fail("MESSAGE"); - } - - [Test] - public void CallAssertFailWithMessageAndArgs() - { - Assert.Fail("MESSAGE: {0}+{1}={2}", 2, 2, 4); - } - } -} diff --git a/test/NUnitLite/src/testdata/AssertIgnoreData.cs b/test/NUnitLite/src/testdata/AssertIgnoreData.cs deleted file mode 100644 index fc3ff0c39..000000000 --- a/test/NUnitLite/src/testdata/AssertIgnoreData.cs +++ /dev/null @@ -1,84 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.AssertIgnoreData -{ - [TestFixture] - public class IgnoredTestCaseFixture - { - [Test] - public void CallsIgnore() - { - Assert.Ignore("Ignore me"); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void CallsIgnoreWithExpectedException() - { - Assert.Ignore("Ignore me"); - } - } - - [TestFixture] - public class IgnoredTestSuiteFixture - { - [TestFixtureSetUp] - public void FixtureSetUp() - { - Assert.Ignore("Ignore this fixture"); - } - - [Test] - public void ATest() - { - } - - [Test] - public void AnotherTest() - { - } - } - - [TestFixture] - public class IgnoreInSetUpFixture - { - [SetUp] - public void SetUp() - { - Assert.Ignore( "Ignore this test" ); - } - - [Test] - public void Test1() - { - } - - [Test] - public void Test2() - { - } - } -} diff --git a/test/NUnitLite/src/testdata/AsyncDummyFixture.cs b/test/NUnitLite/src/testdata/AsyncDummyFixture.cs deleted file mode 100644 index c1f8e5fbe..000000000 --- a/test/NUnitLite/src/testdata/AsyncDummyFixture.cs +++ /dev/null @@ -1,92 +0,0 @@ -#if NET_4_5 -using System.Threading.Tasks; -using NUnit.Framework; -using System; - -namespace NUnit.TestData -{ - public class AsyncDummyFixture - { - [Test] - public async void AsyncVoid() - { - await Task.Delay(0); // To avoid warning message - } - - [Test] - public async Task AsyncTask() - { - await Task.Yield(); - } - - [Test] - public async Task AsyncGenericTask() - { - return await Task.FromResult(1); - } - - [Test] - public Task NonAsyncTask() - { - return Task.Delay(0); - } - - [Test] - public Task NonAsyncGenericTask() - { - return Task.FromResult(1); - } - - [TestCase(4)] - public async void AsyncVoidTestCase(int x) - { - await Task.Delay(0); - } - - [TestCase(ExpectedResult = 1)] - public async void AsyncVoidTestCaseWithExpectedResult() - { - await Task.Run(() => 1); - } - - [TestCase(4)] - public async Task AsyncTaskTestCase(int x) - { - await Task.Delay(0); - } - - [TestCase(ExpectedResult = 1)] - public async Task AsyncTaskTestCaseWithExpectedResult() - { - await Task.Run(() => 1); - } - - [TestCase(4)] - public async Task AsyncGenericTaskTestCase() - { - return await Task.Run(() => 1); - } - - [TestCase(ExpectedResult = 1)] - public async Task AsyncGenericTaskTestCaseWithExpectedResult() - { - return await Task.Run(() => 1); - } - - [TestCase(ExpectedException = typeof(Exception))] - public async Task AsyncGenericTaskTestCaseWithExpectedException() - { - return await Throw(); - } - - private async Task Throw() - { - return await Task.Run(() => - { - throw new InvalidOperationException(); - return 1; - }); - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/AsyncRealFixture.cs b/test/NUnitLite/src/testdata/AsyncRealFixture.cs deleted file mode 100644 index 5a94b92a8..000000000 --- a/test/NUnitLite/src/testdata/AsyncRealFixture.cs +++ /dev/null @@ -1,369 +0,0 @@ -#if NET_4_5 -using System; -using System.Threading; -using System.Threading.Tasks; -using NUnit.Framework; -using NUnit.Framework.Internal; - -namespace NUnit.TestData -{ - public class AsyncRealFixture - { - [Test] - public async void AsyncVoidSuccess() - { - var result = await ReturnOne(); - - Assert.AreEqual(1, result); - } - - [Test] - public async void AsyncVoidFailure() - { - var result = await ReturnOne(); - - Assert.AreEqual(2, result); - } - - [Test] - public async void AsyncVoidError() - { - await ThrowException(); - - Assert.Fail("Should never get here"); - } - - [Test] - public async Task AsyncTaskSuccess() - { - var result = await ReturnOne(); - - Assert.AreEqual(1, result); - } - - [Test] - public async Task AsyncTaskFailure() - { - var result = await ReturnOne(); - - Assert.AreEqual(2, result); - } - - [Test] - public async Task AsyncTaskError() - { - await ThrowException(); - - Assert.Fail("Should never get here"); - } - - [Test] // Not Runnable - public async Task AsyncTaskResultSuccess() - { - var result = await ReturnOne(); - - Assert.AreEqual(1, result); - - return result; - } - - [Test] // Not Runnable - public async Task AsyncTaskResultFailure() - { - var result = await ReturnOne(); - - Assert.AreEqual(2, result); - - return result; - } - - [Test] // Not Runnable - public async Task AsyncTaskResultError() - { - await ThrowException(); - - Assert.Fail("Should never get here"); - - return 0; - } - - [TestCase(ExpectedResult = 1)] - public async Task AsyncTaskResultCheckSuccess() - { - return await ReturnOne(); - } - - [TestCase(ExpectedResult = 2)] - public async Task AsyncTaskResultCheckFailure() - { - return await ReturnOne(); - } - - [TestCase(ExpectedResult = 0)] - public async Task AsyncTaskResultCheckError() - { - return await ThrowException(); - } - - [TestCase(ExpectedResult = null)] - public async Task AsyncTaskResultCheckSuccessReturningNull() - { - return await Task.Run(() => (object)null); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public async void AsyncVoidExpectedException() - { - await ThrowException(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public async Task AsyncTaskExpectedException() - { - await ThrowException(); - } - - [Test] // Not Runnable - [ExpectedException(typeof(InvalidOperationException))] - public async Task AsyncTaskResultExpectedException() - { - return await ThrowException(); - } - - [Test] - public async void AsyncVoidAssertSynchronizationContext() - { - await Task.Yield(); - } - - [Test] - public async void NestedAsyncVoidSuccess() - { - var result = await Task.Run(async () => await ReturnOne()); - - Assert.AreEqual(1, result); - } - - [Test] - public async void NestedAsyncVoidFailure() - { - var result = await Task.Run(async () => await ReturnOne()); - - Assert.AreEqual(2, result); - } - - [Test] - public async void NestedAsyncVoidError() - { - await Task.Run(async () => await ThrowException()); - - Assert.Fail("Should not get here"); - } - - [Test] - public async Task NestedAsyncTaskSuccess() - { - var result = await Task.Run(async () => await ReturnOne()); - - Assert.AreEqual(1, result); - } - - [Test] - public async Task NestedAsyncTaskFailure() - { - var result = await Task.Run(async () => await ReturnOne()); - - Assert.AreEqual(2, result); - } - - [Test] - public async Task NestedAsyncTaskError() - { - await Task.Run(async () => await ThrowException()); - - Assert.Fail("Should never get here"); - } - - [Test] - public async Task NestedAsyncTaskResultSuccess() - { - var result = await Task.Run(async () => await ReturnOne()); - - Assert.AreEqual(1, result); - - return result; - } - - [Test] - public async Task NestedAsyncTaskResultFailure() - { - var result = await Task.Run(async () => await ReturnOne()); - - Assert.AreEqual(2, result); - - return result; - } - - [Test] - public async Task NestedAsyncTaskResultError() - { - var result = await Task.Run(async () => await ThrowException()); - - Assert.Fail("Should never get here"); - - return result; - } - - [Test] - public async void AsyncVoidMultipleSuccess() - { - var result = await ReturnOne(); - - Assert.AreEqual(await ReturnOne(), result); - } - - [Test]// - public async void AsyncVoidMultipleFailure() - { - var result = await ReturnOne(); - - Assert.AreEqual(await ReturnOne() + 1, result); - } - - [Test] - public async void AsyncVoidMultipleError() - { - var result = await ReturnOne(); - await ThrowException(); - - Assert.Fail("Should never get here"); - } - - [Test] - public async void AsyncTaskMultipleSuccess() - { - var result = await ReturnOne(); - - Assert.AreEqual(await ReturnOne(), result); - } - - [Test] - public async void AsyncTaskMultipleFailure() - { - var result = await ReturnOne(); - - Assert.AreEqual(await ReturnOne() + 1, result); - } - - [Test] - public async void AsyncTaskMultipleError() - { - var result = await ReturnOne(); - await ThrowException(); - - Assert.Fail("Should never get here"); - } - - [TestCase(1, 2)] - public async void AsyncVoidTestCaseWithParametersSuccess(int a, int b) - { - Assert.AreEqual(await ReturnOne(), b - a); - } - - [Test] - public async void VoidCheckTestContextAcrossTasks() - { - var testName = await GetTestNameFromContext(); - - Assert.IsNotNull(testName); - Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); - } - - [Test] - public async Task TaskCheckTestContextAcrossTasks() - { - var testName = await GetTestNameFromContext(); - - Assert.IsNotNull(testName); - Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); - } - - [Test] - public async void VoidCheckTestContextWithinTestBody() - { - var testName = TestContext.CurrentContext.Test.Name; - - await ReturnOne(); - - Assert.IsNotNull(testName); - Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); - } - - [Test] - public async Task TaskCheckTestContextWithinTestBody() - { - var testName = TestContext.CurrentContext.Test.Name; - - await ReturnOne(); - - Assert.IsNotNull(testName); - Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public async void VoidAsyncVoidChildCompletingEarlierThanTest() - { - AsyncVoidMethod(); - - await ThrowExceptionIn(TimeSpan.FromSeconds(1)); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public async void VoidAsyncVoidChildThrowingImmediately() - { - AsyncVoidThrowException(); - - await Task.Run(() => Assert.Fail("Should never invoke this")); - } - - private static async void AsyncVoidThrowException() - { - await Task.Run(() => { throw new InvalidOperationException(); }); - } - - private static async Task ThrowExceptionIn(TimeSpan delay) - { - await Task.Delay(delay); - throw new InvalidOperationException(); - } - - private static async void AsyncVoidMethod() - { - await Task.Yield(); - } - - private static Task GetTestNameFromContext() - { - return Task.Run(() => TestContext.CurrentContext.Test.Name); - } - - private static Task ReturnOne() - { - return Task.Run(() => 1); - } - - private static Task ThrowException() - { - return Task.Run(() => - { - throw new InvalidOperationException(); - return 1; - }); - } - } -} -#endif diff --git a/test/NUnitLite/src/testdata/AttributeInheritanceData.cs b/test/NUnitLite/src/testdata/AttributeInheritanceData.cs deleted file mode 100644 index 1d6cb1518..000000000 --- a/test/NUnitLite/src/testdata/AttributeInheritanceData.cs +++ /dev/null @@ -1,60 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.AttributeInheritanceData -{ - // Sample Test from a post by Scott Bellware - - [AttributeUsage(AttributeTargets.Class, AllowMultiple=false)] - class ConcernAttribute : TestFixtureAttribute - { - private Type typeOfConcern; - - public ConcernAttribute( Type typeOfConcern ) - { - this.typeOfConcern = typeOfConcern; - } - } - - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] - class SpecAttribute : TestAttribute - { - } - - /// - /// Summary description for AttributeInheritance. - /// - [Concern(typeof(ClassUnderTest))] - public class When_collecting_test_fixtures - { - [Spec] - public void should_include_classes_with_an_attribute_derived_from_TestFixtureAttribute() - { - } - } - - class ClassUnderTest { } -} diff --git a/test/NUnitLite/src/testdata/CategoryAttributeData.cs b/test/NUnitLite/src/testdata/CategoryAttributeData.cs deleted file mode 100644 index a70c093f3..000000000 --- a/test/NUnitLite/src/testdata/CategoryAttributeData.cs +++ /dev/null @@ -1,61 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.CategoryAttributeData -{ - [TestFixture, InheritableCategory("MyCategory")] - public abstract class AbstractBase { } - - [TestFixture, Category( "DataBase" )] - public class FixtureWithCategories : AbstractBase - { - [Test, Category("Long")] - public void Test1() { } - - [Test, Critical] - public void Test2() { } - - [Test, Category("Top")] - [TestCaseSource("Test3Data")] - public void Test3(int x) { } - - [Test, Category("A-B")] - public void Test4() { } - - internal TestCaseData[] Test3Data = new TestCaseData[] { - new TestCaseData(5).SetCategory("Bottom") - }; - } - - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)] - public class CriticalAttribute : CategoryAttribute { } - - [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)] - public class InheritableCategoryAttribute : CategoryAttribute - { - public InheritableCategoryAttribute(string name) : base(name) { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/CultureAttributeData.cs b/test/NUnitLite/src/testdata/CultureAttributeData.cs deleted file mode 100644 index 29956b374..000000000 --- a/test/NUnitLite/src/testdata/CultureAttributeData.cs +++ /dev/null @@ -1,57 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.CultureAttributeData -{ - [TestFixture, Culture( "en,fr,de" )] - public class FixtureWithCultureAttribute - { - [Test, Culture("en,de")] - public void EnglishAndGermanTest() { } - - [Test, Culture("fr")] - public void FrenchTest() { } - - [Test, Culture("fr-CA")] - public void FrenchCanadaTest() { } - } - -#if !NETCF - [TestFixture, SetCulture("xx-XX")] - public class FixtureWithInvalidSetCultureAttribute - { - [Test] - public void SomeTest() { } - } - - [TestFixture] - public class FixtureWithInvalidSetCultureAttributeOnTest - { - [Test, SetCulture("xx-XX")] - public void InvalidCultureSet() { } - } -#endif -} \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/DatapointFixture.cs b/test/NUnitLite/src/testdata/DatapointFixture.cs deleted file mode 100644 index cf631d3bf..000000000 --- a/test/NUnitLite/src/testdata/DatapointFixture.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework; - -namespace NUnit.TestData.DatapointFixture -{ - public abstract class SquareRootTest - { - [Theory] - public void SqrtTimesItselfGivesOriginal(double num) - { - Assume.That(num >= 0.0 && num < double.MaxValue); - - double sqrt = Math.Sqrt(num); - - Assert.That(sqrt >= 0.0); - Assert.That(sqrt * sqrt, Is.EqualTo(num).Within(0.000001)); - } - } - - public class SquareRootTest_Field_Double : SquareRootTest - { - [Datapoint] - public double zero = 0; - - [Datapoint] - public double positive = 1; - - [Datapoint] - public double negative = -1; - - [Datapoint] - public double max = double.MaxValue; - - [Datapoint] - public double infinity = double.PositiveInfinity; - } - - public class SquareRootTest_Field_ArrayOfDouble : SquareRootTest - { - [Datapoints] - public double[] values = new double[] { 0.0, 1.0, -1.0, double.MaxValue, double.PositiveInfinity }; - } - - public class SquareRootTest_Property_ArrayOfDouble : SquareRootTest - { - [Datapoints] - public double[] Values - { - get { return new double[] { 0.0, 1.0, -1.0, double.MaxValue, double.PositiveInfinity }; } - } - } - - public class SquareRootTest_Method_ArrayOfDouble : SquareRootTest - { - [Datapoints] - public double[] GetValues() - { - return new double[] { 0.0, 1.0, -1.0, double.MaxValue, double.PositiveInfinity }; - } - } - -#if CLR_2_0 || CLR_4_0 - public class SquareRootTest_Field_IEnumerableOfDouble : SquareRootTest - { - [Datapoints] - public IEnumerable values = new List( new double[] { 0.0, 1.0, -1.0, double.MaxValue, double.PositiveInfinity } ); - } - - public class SquareRootTest_Property_IEnumerableOfDouble : SquareRootTest - { - [Datapoints] - public IEnumerable Values - { - get - { - List list = new List(); - list.Add(0.0); - list.Add(1.0); - list.Add(-1.0); - list.Add(double.MaxValue); - list.Add(double.PositiveInfinity); - return list; - } - } - } - - public class SquareRootTest_Method_IEnumerableOfDouble : SquareRootTest - { - [Datapoints] - public IEnumerable GetValues() - { - List list = new List(); - list.Add(0.0); - list.Add(1.0); - list.Add(-1.0); - list.Add(double.MaxValue); - list.Add(double.PositiveInfinity); - return list; - } - } - - public class SquareRootTest_Iterator_IEnumerableOfDouble : SquareRootTest - { - [Datapoints] - public IEnumerable GetValues() - { - yield return 0.0; - - yield return 1.0; - yield return -1.0; - yield return double.MaxValue; - yield return double.PositiveInfinity; - } - } -#endif -} diff --git a/test/NUnitLite/src/testdata/DescriptionFixture.cs b/test/NUnitLite/src/testdata/DescriptionFixture.cs deleted file mode 100644 index 079a10e29..000000000 --- a/test/NUnitLite/src/testdata/DescriptionFixture.cs +++ /dev/null @@ -1,50 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.DescriptionFixture -{ - [TestFixture(Description = "Fixture Description")] - public class DescriptionFixture - { - [Test(Description = "Test Description")] - public void Method() - {} - - [Test] - public void NoDescriptionMethod() - {} - - [Test] - [Description("Separate Description")] - public void SeparateDescriptionMethod() - { } - - [Test, Description("method description")] - [TestCase(5, Description = "case description")] - public void TestCaseWithDescription(int x) - { } - } -} diff --git a/test/NUnitLite/src/testdata/ExpectedExceptionData.cs b/test/NUnitLite/src/testdata/ExpectedExceptionData.cs deleted file mode 100644 index f6848d9ca..000000000 --- a/test/NUnitLite/src/testdata/ExpectedExceptionData.cs +++ /dev/null @@ -1,301 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.ExpectedExceptionData -{ - [TestFixture] - public class BaseException - { - [Test] - [ExpectedException(typeof(ArgumentException))] - public void BaseExceptionTest() - { - throw new Exception(); - } - } - - [TestFixture] - public class DerivedException - { - [Test] - [ExpectedException(typeof(Exception))] - public void DerivedExceptionTest() - { - throw new ArgumentException(); - } - } - - [TestFixture] - public class MismatchedException - { - [Test] - [ExpectedException(typeof(ArgumentException))] - public void MismatchedExceptionType() - { - throw new ArgumentOutOfRangeException(); - } - - [Test] - [ExpectedException(ExpectedException=typeof(ArgumentException))] - public void MismatchedExceptionTypeAsNamedParameter() - { - throw new ArgumentOutOfRangeException(); - } - - [Test] - [ExpectedException(typeof(ArgumentException), UserMessage="custom message")] - public void MismatchedExceptionTypeWithUserMessage() - { - throw new ArgumentOutOfRangeException(); - } - - [Test] - [ExpectedException("System.ArgumentException")] - public void MismatchedExceptionName() - { - throw new ArgumentOutOfRangeException(); - } - - [Test] - [ExpectedException("System.ArgumentException", UserMessage="custom message")] - public void MismatchedExceptionNameWithUserMessage() - { - throw new ArgumentOutOfRangeException(); - } - } - - [TestFixture] - public class SetUpExceptionTests - { - [SetUp] - public void Init() - { - throw new ArgumentException("SetUp Exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void Test() - { - } - } - - [TestFixture] - public class TearDownExceptionTests - { - [TearDown] - public void CleanUp() - { - throw new ArgumentException("TearDown Exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void Test() - {} - } - - [TestFixture] - public class TestThrowsExceptionFixture - { - [Test] - public void TestThrow() - { - throw new Exception(); - } - } - - [TestFixture] - public class TestDoesNotThrowExceptionFixture - { - [Test, ExpectedException("System.ArgumentException")] - public void TestDoesNotThrowExceptionName() - { - } - - [Test, ExpectedException("System.ArgumentException", UserMessage="custom message")] - public void TestDoesNotThrowExceptionNameWithUserMessage() - { - } - - [Test, ExpectedException( typeof( System.ArgumentException ) )] - public void TestDoesNotThrowExceptionType() - { - } - - [Test, ExpectedException( typeof( System.ArgumentException ), UserMessage="custom message" )] - public void TestDoesNotThrowExceptionTypeWithUserMessage() - { - } - - [Test, ExpectedException] - public void TestDoesNotThrowUnspecifiedException() - { - } - - [Test, ExpectedException( UserMessage="custom message" )] - public void TestDoesNotThrowUnspecifiedExceptionWithUserMessage() - { - } - } - - [TestFixture] - public class TestThrowsExceptionWithRightMessage - { - [Test] - [ExpectedException(typeof(Exception), ExpectedMessage="the message")] - public void TestThrow() - { - throw new Exception("the message"); - } - } - - [TestFixture] - public class TestThrowsArgumentOutOfRangeException - { - [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException)) ] - public void TestThrow() - { -#if NETCF || SILVERLIGHT - throw new ArgumentOutOfRangeException("param", "the message"); -#else - throw new ArgumentOutOfRangeException("param", "actual value", "the message"); -#endif - } - } - - [TestFixture] - public class TestThrowsExceptionWithWrongMessage - { - [Test] - [ExpectedException(typeof(Exception), ExpectedMessage="not the message")] - public void TestThrow() - { - throw new Exception("the message"); - } - - [Test] - [ExpectedException( typeof(Exception), ExpectedMessage="not the message", UserMessage="custom message" )] - public void TestThrowWithUserMessage() - { - throw new Exception("the message"); - } - } - - [TestFixture] - public class TestAssertsBeforeThrowingException - { - [Test] - [ExpectedException(typeof(Exception))] - public void TestAssertFail() - { - Assert.Fail( "private message" ); - } - } - - public class ExceptionHandlerCalledClass : IExpectException - { - public bool HandlerCalled = false; - public bool AlternateHandlerCalled = false; - - [Test, ExpectedException(typeof(ArgumentException))] - public void ThrowsArgumentException() - { - throw new ArgumentException(); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public void ThrowsCustomException() - { - throw new CustomException(); - } - - class CustomException : Exception { } - - [Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")] - public void ThrowsArgumentException_AlternateHandler() - { - throw new ArgumentException(); - } - - [Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")] - public void ThrowsCustomException_AlternateHandler() - { - throw new CustomException(); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public void ThrowsSystemException() - { - throw new Exception(); - } - - [Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")] - public void ThrowsSystemException_AlternateHandler() - { - throw new Exception(); - } - - [Test, ExpectedException(typeof(ArgumentException), Handler = "DeliberatelyMissingHandler")] - public void MethodWithBadHandler() - { - throw new ArgumentException(); - } - - public void HandleException(Exception ex) - { - HandlerCalled = true; - } - - public void AlternateExceptionHandler(Exception ex) - { - AlternateHandlerCalled = true; - } - } - -#if CLR_2_0 || CLR_4_0 - public static class StaticClassWithExpectedExceptions - { - [Test, ExpectedException(typeof(ArgumentException))] - public static void TestSucceedsInStaticClass() - { - throw new ArgumentException("argument exception"); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public static void TestFailsInStaticClass_NoExceptionThrown() - { - } - - [Test, ExpectedException(typeof(ArgumentException))] - public static void TestFailsInStaticClass_WrongExceptionThrown() - { - throw new InvalidOperationException("wrong exception"); - } - } -#endif -} diff --git a/test/NUnitLite/src/testdata/FixtureSetUpTearDownData.cs b/test/NUnitLite/src/testdata/FixtureSetUpTearDownData.cs deleted file mode 100644 index 2b0828e9f..000000000 --- a/test/NUnitLite/src/testdata/FixtureSetUpTearDownData.cs +++ /dev/null @@ -1,360 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.FixtureSetUpTearDownData -{ - [TestFixture] - public class SetUpAndTearDownFixture - { - public int setUpCount = 0; - public int tearDownCount = 0; - - [TestFixtureSetUp] - public virtual void Init() - { - setUpCount++; - } - - [TestFixtureTearDown] - public virtual void Destroy() - { - tearDownCount++; - } - - [Test] - public void Success(){} - - [Test] - public void EvenMoreSuccess(){} - } - - [TestFixture, Explicit] - public class ExplicitSetUpAndTearDownFixture - { - public int setUpCount = 0; - public int tearDownCount = 0; - - [TestFixtureSetUp] - public virtual void Init() - { - setUpCount++; - } - - [TestFixtureTearDown] - public virtual void Destroy() - { - tearDownCount++; - } - - [Test] - public void Success() { } - - [Test] - public void EvenMoreSuccess() { } - } - - [TestFixture] - public class InheritSetUpAndTearDown : SetUpAndTearDownFixture - { - [Test] - public void AnotherTest(){} - - [Test] - public void YetAnotherTest(){} - } - - [TestFixture] - public class DefineInheritSetUpAndTearDown : SetUpAndTearDownFixture - { - public int derivedSetUpCount; - public int derivedTearDownCount; - - [TestFixtureSetUp] - public override void Init() - { - derivedSetUpCount++; - } - - [TestFixtureTearDown] - public override void Destroy() - { - derivedTearDownCount++; - } - - [Test] - public void AnotherTest() { } - - [Test] - public void YetAnotherTest() { } - } - - [TestFixture] - public class DerivedSetUpAndTearDownFixture : SetUpAndTearDownFixture - { - public int derivedSetUpCount; - public int derivedTearDownCount; - - public bool baseSetUpCalledFirst; - public bool baseTearDownCalledLast; - - [TestFixtureSetUp] - public void Init2() - { - derivedSetUpCount++; - baseSetUpCalledFirst = this.setUpCount > 0; - } - - [TestFixtureTearDown] - public void Destroy2() - { - derivedTearDownCount++; - baseTearDownCalledLast = this.tearDownCount == 0; - } - - [Test] - public void AnotherTest() { } - - [Test] - public void YetAnotherTest() { } - } - - [TestFixture] - public class StaticSetUpAndTearDownFixture - { - public static int setUpCount = 0; - public static int tearDownCount = 0; - - [TestFixtureSetUp] - public static void Init() - { - setUpCount++; - } - - [TestFixtureTearDown] - public static void Destroy() - { - tearDownCount++; - } - } - - [TestFixture] - public class DerivedStaticSetUpAndTearDownFixture : StaticSetUpAndTearDownFixture - { - public static int derivedSetUpCount; - public static int derivedTearDownCount; - - public static bool baseSetUpCalledFirst; - public static bool baseTearDownCalledLast; - - - [TestFixtureSetUp] - public static void Init2() - { - derivedSetUpCount++; - baseSetUpCalledFirst = setUpCount > 0; - } - - [TestFixtureTearDown] - public static void Destroy2() - { - derivedTearDownCount++; - baseTearDownCalledLast = tearDownCount == 0; - } - } - -#if CLR_2_0 || CLR_4_0 - [TestFixture] - public static class StaticClassSetUpAndTearDownFixture - { - public static int setUpCount = 0; - public static int tearDownCount = 0; - - [TestFixtureSetUp] - public static void Init() - { - setUpCount++; - } - - [TestFixtureTearDown] - public static void Destroy() - { - tearDownCount++; - } - } -#endif - - [TestFixture] - public class MisbehavingFixture - { - public bool blowUpInSetUp = false; - public bool blowUpInTearDown = false; - - public int setUpCount = 0; - public int tearDownCount = 0; - - public void Reinitialize() - { - setUpCount = 0; - tearDownCount = 0; - - blowUpInSetUp = false; - blowUpInTearDown = false; - } - - [TestFixtureSetUp] - public void BlowUpInSetUp() - { - setUpCount++; - if (blowUpInSetUp) - throw new Exception("This was thrown from fixture setup"); - } - - [TestFixtureTearDown] - public void BlowUpInTearDown() - { - tearDownCount++; - if ( blowUpInTearDown ) - throw new Exception("This was thrown from fixture teardown"); - } - - [Test] - public void nothingToTest() - { - } - } - - [TestFixture] - public class ExceptionInConstructor - { - public ExceptionInConstructor() - { - throw new Exception( "This was thrown in constructor" ); - } - - [Test] - public void nothingToTest() - { - } - } - - [TestFixture] - public class IgnoreInFixtureSetUp - { - [TestFixtureSetUp] - public void SetUpCallsIgnore() - { - Assert.Ignore( "TestFixtureSetUp called Ignore" ); - } - - [Test] - public void nothingToTest() - { - } - } - - [TestFixture] - public class SetUpAndTearDownWithTestInName - { - public int setUpCount = 0; - public int tearDownCount = 0; - - [TestFixtureSetUp] - public virtual void TestFixtureSetUp() - { - setUpCount++; - } - - [TestFixtureTearDown] - public virtual void TestFixtureTearDown() - { - tearDownCount++; - } - - [Test] - public void Success(){} - - [Test] - public void EvenMoreSuccess(){} - } - - [TestFixture, Ignore( "Do Not Run This" )] - public class IgnoredFixture - { - public bool setupCalled = false; - public bool teardownCalled = false; - - [TestFixtureSetUp] - public virtual void ShouldNotRun() - { - setupCalled = true; - } - - [TestFixtureTearDown] - public virtual void NeitherShouldThis() - { - teardownCalled = true; - } - - [Test] - public void Success(){} - - [Test] - public void EvenMoreSuccess(){} - } - - [TestFixture] - public class FixtureWithNoTests - { - public bool setupCalled = false; - public bool teardownCalled = false; - - [TestFixtureSetUp] - public virtual void Init() - { - setupCalled = true; - } - - [TestFixtureTearDown] - public virtual void Destroy() - { - teardownCalled = true; - } - } - - [TestFixture] - public class DisposableFixture : IDisposable - { - public bool disposeCalled = false; - - [Test] - public void OneTest() { } - - public void Dispose() - { - disposeCalled = true; - } - } -} diff --git a/test/NUnitLite/src/testdata/MaxTimeFixture.cs b/test/NUnitLite/src/testdata/MaxTimeFixture.cs deleted file mode 100644 index 4c019144f..000000000 --- a/test/NUnitLite/src/testdata/MaxTimeFixture.cs +++ /dev/null @@ -1,65 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData -{ - [TestFixture] - public class MaxTimeFixture - { - [Test, MaxTime(1)] - public void MaxTimeExceeded() - { -#if NETCF - long endTime = DateTime.Now.Ticks + TimeSpan.TicksPerMillisecond * 20; - while (endTime > DateTime.Now.Ticks) ; -#else - System.Threading.Thread.Sleep(20); -#endif - } - } - - [TestFixture] - public class MaxTimeFixtureWithFailure - { - [Test, MaxTime(1)] - public void MaxTimeExceeded() - { - System.Threading.Thread.Sleep(20); - Assert.Fail("Intentional Failure"); - } - } - - [TestFixture] - public class MaxTimeFixtureWithError - { - [Test, MaxTime(1)] - public void MaxTimeExceeded() - { - System.Threading.Thread.Sleep(20); - throw new Exception("Exception message"); - } - } -} diff --git a/test/NUnitLite/src/testdata/ParameterizedTestFixture.cs b/test/NUnitLite/src/testdata/ParameterizedTestFixture.cs deleted file mode 100644 index 62b54a190..000000000 --- a/test/NUnitLite/src/testdata/ParameterizedTestFixture.cs +++ /dev/null @@ -1,53 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData -{ - [TestFixture(1)] - [TestFixture(2)] - public class ParameterizedTestFixture - { - [Test] - public void MethodWithoutParams() - { - } - - [TestCase(10,20)] - public void MethodWithParams(int x, int y) - { - } - } - - [TestFixture(Category = "XYZ")] - public class TestFixtureWithSingleCategory - { - } - - [TestFixture(Category = "X,Y,Z")] - public class TestFixtureWithMultipleCategories - { - } -} diff --git a/test/NUnitLite/src/testdata/PropertyAttributeTests.cs b/test/NUnitLite/src/testdata/PropertyAttributeTests.cs deleted file mode 100644 index 84c10aa12..000000000 --- a/test/NUnitLite/src/testdata/PropertyAttributeTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.PropertyAttributeTests -{ - [TestFixture, Property("ClassUnderTest","SomeClass" )] - public class FixtureWithProperties - { - [Test, Property("user","Charlie")] - public void Test1() { } - - [Test, Property("X",10.0), Property("Y",17.0)] - public void Test2() { } - - [Test, Priority(5)] - public void Test3() { } - } - - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] - public class PriorityAttribute : PropertyAttribute - { - public PriorityAttribute( int level ) : base( level ) { } - } -} diff --git a/test/NUnitLite/src/testdata/RepeatedTestFixture.cs b/test/NUnitLite/src/testdata/RepeatedTestFixture.cs deleted file mode 100644 index 0e421a14e..000000000 --- a/test/NUnitLite/src/testdata/RepeatedTestFixture.cs +++ /dev/null @@ -1,135 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -#if false -using System; -using NUnit.Framework; - -namespace NUnit.TestData.RepeatedTestFixture -{ - [TestFixture] - public class RepeatingTestsBase - { - private int fixtureSetupCount; - private int fixtureTeardownCount; - private int setupCount; - private int teardownCount; - protected int count; - - [TestFixtureSetUp] - public void FixtureSetUp() - { - fixtureSetupCount++; - } - - [TestFixtureTearDown] - public void FixtureTearDown() - { - fixtureTeardownCount++; - } - - [SetUp] - public void SetUp() - { - setupCount++; - } - - [TearDown] - public void TearDown() - { - teardownCount++; - } - - public int FixtureSetupCount - { - get { return fixtureSetupCount; } - } - public int FixtureTeardownCount - { - get { return fixtureTeardownCount; } - } - public int SetupCount - { - get { return setupCount; } - } - public int TeardownCount - { - get { return teardownCount; } - } - public int Count - { - get { return count; } - } - } - - public class RepeatSuccessFixture : RepeatingTestsBase - { - [Test, Repeat(3)] - public void RepeatSuccess() - { - count++; - Assert.IsTrue (true); - } - } - - public class RepeatFailOnFirstFixture : RepeatingTestsBase - { - [Test, Repeat(3)] - public void RepeatFailOnFirst() - { - count++; - Assert.IsFalse (true); - } - } - - public class RepeatFailOnThirdFixture : RepeatingTestsBase - { - [Test, Repeat(3)] - public void RepeatFailOnThird() - { - count++; - - if (count == 3) - Assert.IsTrue (false); - } - } - - public class RepeatedTestWithIgnore : RepeatingTestsBase - { - [Test, Repeat(3), Ignore("Ignore this test")] - public void RepeatShouldIgnore() - { - Assert.Fail("Ignored test executed"); - } - } - - public class RepeatedTestWithCategory : RepeatingTestsBase - { - [Test, Repeat(3), Category("SAMPLE")] - public void TestWithCategory() - { - count++; - Assert.IsTrue(true); - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/SetUpData.cs b/test/NUnitLite/src/testdata/SetUpData.cs deleted file mode 100644 index 7376cea8f..000000000 --- a/test/NUnitLite/src/testdata/SetUpData.cs +++ /dev/null @@ -1,192 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.SetUpData -{ - [TestFixture] - public class SetUpAndTearDownFixture - { - public bool wasSetUpCalled; - public bool wasTearDownCalled; - - [SetUp] - public virtual void Init() - { - wasSetUpCalled = true; - } - - [TearDown] - public virtual void Destroy() - { - wasTearDownCalled = true; - } - - [Test] - public void Success() { } - } - - - [TestFixture] - public class SetUpAndTearDownCounterFixture - { - public int setUpCounter; - public int tearDownCounter; - - [SetUp] - public virtual void Init() - { - setUpCounter++; - } - - [TearDown] - public virtual void Destroy() - { - tearDownCounter++; - } - - [Test] - public void TestOne(){} - - [Test] - public void TestTwo(){} - - [Test] - public void TestThree(){} - } - - [TestFixture] - public class InheritSetUpAndTearDown : SetUpAndTearDownFixture - { - [Test] - public void AnotherTest(){} - } - - [TestFixture] - public class DefineInheritSetUpAndTearDown : SetUpAndTearDownFixture - { - public bool derivedSetUpCalled; - public bool derivedTearDownCalled; - - [SetUp] - public override void Init() - { - derivedSetUpCalled = true; - } - - [TearDown] - public override void Destroy() - { - derivedTearDownCalled = true; - } - - [Test] - public void AnotherTest(){} - } - - public class MultipleSetUpTearDownFixture - { - public bool wasSetUp1Called; - public bool wasSetUp2Called; - public bool wasSetUp3Called; - public bool wasTearDown1Called; - public bool wasTearDown2Called; - - [SetUp] - public virtual void Init1() - { - wasSetUp1Called = true; - } - [SetUp] - public virtual void Init2() - { - wasSetUp2Called = true; - } - [SetUp] - public virtual void Init3() - { - wasSetUp3Called = true; - } - - [TearDown] - public virtual void TearDown1() - { - wasTearDown1Called = true; - } - [TearDown] - public virtual void TearDown2() - { - wasTearDown2Called = true; - } - - [Test] - public void Success() { } - } - - [TestFixture] - public class DerivedClassWithSeparateSetUp : SetUpAndTearDownFixture - { - public bool wasDerivedSetUpCalled; - public bool wasDerivedTearDownCalled; - public bool wasBaseSetUpCalledFirst; - public bool wasBaseTearDownCalledLast; - - [SetUp] - public void DerivedInit() - { - wasDerivedSetUpCalled = true; - wasBaseSetUpCalledFirst = wasSetUpCalled; - } - - [TearDown] - public void DerivedTearDown() - { - wasDerivedTearDownCalled = true; - wasBaseTearDownCalledLast = !wasTearDownCalled; - } - } - - [TestFixture] - public class SetupAndTearDownExceptionFixture - { - public Exception setupException; - public Exception tearDownException; - - [SetUp] - public void SetUp() - { - if (setupException != null) throw setupException; - } - - [TearDown] - public void TearDown() - { - if (tearDownException!=null) throw tearDownException; - } - - [Test] - public void TestOne() {} - } -} diff --git a/test/NUnitLite/src/testdata/TestCaseAttributeFixture.cs b/test/NUnitLite/src/testdata/TestCaseAttributeFixture.cs deleted file mode 100644 index cd19df668..000000000 --- a/test/NUnitLite/src/testdata/TestCaseAttributeFixture.cs +++ /dev/null @@ -1,102 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.TestCaseAttributeFixture -{ - [TestFixture] - public class TestCaseAttributeFixture - { - [TestCase("12-Octobar-1942")] - public void MethodHasInvalidDateFormat(DateTime dt) - {} - - [TestCase(2,3,4,Description="My Description")] - public void MethodHasDescriptionSpecified(int x, int y, int z) - {} - - [TestCase(2,3,4,TestName="XYZ")] - public void MethodHasTestNameSpecified(int x, int y, int z) - {} - - [TestCase(2, 3, 4, Category = "XYZ")] - public void MethodHasSingleCategory(int x, int y, int z) - { } - - [TestCase(2, 3, 4, Category = "X,Y,Z")] - public void MethodHasMultipleCategories(int x, int y, int z) - { } - - [TestCase(2, 2000000, ExpectedResult=4)] - public int MethodCausesConversionOverflow(short x, short y) - { - return x + y; - } - - [TestCase(2, 3, 4, ExpectedException = typeof(ArgumentNullException))] - public void MethodThrowsExpectedException(int x, int y, int z) - { - throw new ArgumentNullException(); - } - - [TestCase(2, 3, 4, ExpectedException = typeof(ArgumentNullException))] - public void MethodThrowsWrongException(int x, int y, int z) - { - throw new ArgumentException(); - } - - [TestCase(2, 3, 4, ExpectedException = typeof(ArgumentNullException))] - public void MethodThrowsNoException(int x, int y, int z) - { - } - - [TestCase(2, 3, 4, ExpectedException = typeof(Exception), - ExpectedMessage="Test Exception")] - public void MethodThrowsExpectedExceptionWithWrongMessage(int x, int y, int z) - { - throw new Exception("Wrong Test Exception"); - } - - [TestCase(2, 3, 4, ExpectedException = typeof(ArgumentNullException))] - public void MethodCallsIgnore(int x, int y, int z) - { - Assert.Ignore("Ignore this"); - } - - [TestCase(1)] - [TestCase(2, Ignore = true)] - [TestCase(3, IgnoreReason = "Don't Run Me!")] - public void MethodWithIgnoredTestCases(int num) - { - } - - [TestCase(1)] - [TestCase(2, Explicit = true)] - [TestCase(3, Explicit = true, Reason = "Connection failing")] - public void MethodWithExplicitTestCases(int num) - { - } - } -} diff --git a/test/NUnitLite/src/testdata/TestCaseSourceAttributeFixture.cs b/test/NUnitLite/src/testdata/TestCaseSourceAttributeFixture.cs deleted file mode 100644 index 25b30a4cb..000000000 --- a/test/NUnitLite/src/testdata/TestCaseSourceAttributeFixture.cs +++ /dev/null @@ -1,111 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework; - -namespace NUnit.TestData.TestCaseSourceAttributeFixture -{ - [TestFixture] - public class TestCaseSourceAttributeFixture - { - [TestCaseSource("source")] - public void MethodThrowsExpectedException(int x, int y, int z) - { - throw new ArgumentNullException(); - } - - [TestCaseSource("source")] - public void MethodThrowsWrongException(int x, int y, int z) - { - throw new ArgumentException(); - } - - [TestCaseSource("source")] - public void MethodThrowsNoException(int x, int y, int z) - { - } - - [TestCaseSource("source")] - public void MethodCallsIgnore(int x, int y, int z) - { - Assert.Ignore("Ignore this"); - } - - internal static object[] source = new object[] { - new TestCaseData( 2, 3, 4 ).Throws(typeof(ArgumentNullException)) }; - - [TestCaseSource("ignored_source")] - public void MethodWithIgnoredTestCases(int num) - { - } - - [TestCaseSource("explicit_source")] - public void MethodWithExplicitTestCases(int num) - { - } - - internal static IEnumerable ignored_source - { - get - { - return new object[] { - new TestCaseData(1), - new TestCaseData(2).Ignore(), - new TestCaseData(3).Ignore("Don't Run Me!") - }; - } - } - - internal static IEnumerable explicit_source - { - get - { - return new object[] { - new TestCaseData(1), - new TestCaseData(2).Explicit(), - new TestCaseData(3).Explicit("Connection failing") - }; - } - } - -#if CLR_2_0 || CLR_4_0 - [TestCaseSource("exception_source")] - public void MethodWithSourceThrowingException(string lhs, string rhs) - { - } - - internal static IEnumerable exception_source - { - get - { - yield return new TestCaseData("a", "a"); - yield return new TestCaseData("b", "b"); - - throw new System.Exception("my message"); - } - } -#endif - } -} diff --git a/test/NUnitLite/src/testdata/TestContextData.cs b/test/NUnitLite/src/testdata/TestContextData.cs deleted file mode 100644 index b627cd506..000000000 --- a/test/NUnitLite/src/testdata/TestContextData.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using NUnit.Framework; - -namespace NUnit.TestData.TestContextData -{ - [TestFixture] - public class TestStateRecordingFixture - { - public string stateList; - - public bool testFailure; - public bool testInconclusive; - public bool setUpFailure; - public bool setUpIgnore; - - [SetUp] - public void SetUp() - { - stateList = TestContext.CurrentContext.Result.Outcome + "=>"; - - if (setUpFailure) - Assert.Fail("Failure in SetUp"); - if (setUpIgnore) - Assert.Ignore("Ignored in SetUp"); - } - - [Test] - public void TheTest() - { - stateList += TestContext.CurrentContext.Result.Outcome; - - if (testFailure) - Assert.Fail("Deliberate failure"); - if (testInconclusive) - Assert.Inconclusive("Inconclusive test"); - } - - [TearDown] - public void TearDown() - { - stateList += "=>" + TestContext.CurrentContext.Result.Outcome; - } - } -} diff --git a/test/NUnitLite/src/testdata/TestFixtureData.cs b/test/NUnitLite/src/testdata/TestFixtureData.cs deleted file mode 100644 index 16aa54a9f..000000000 --- a/test/NUnitLite/src/testdata/TestFixtureData.cs +++ /dev/null @@ -1,447 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; -#if !NETCF -using System.Security.Principal; -#endif - -namespace NUnit.TestData.TestFixtureData -{ - /// - /// Classes used for testing NUnit - /// - - [TestFixture] - public class NoDefaultCtorFixture - { - public NoDefaultCtorFixture(int index) { } - - [Test] - public void OneTest() { } - } - - [TestFixture(7,3)] - public class FixtureWithArgsSupplied - { - public FixtureWithArgsSupplied(int x, int y) { } - - [Test] - public void OneTest() { } - } - - [TestFixture] - public class BadCtorFixture - { - BadCtorFixture() - { - throw new Exception(); - } - - [Test] public void OneTest() - {} - } - - [TestFixture] - public class FixtureWithTestFixtureAttribute - { - [Test] - public void SomeTest() { } - } - - public class FixtureWithoutTestFixtureAttributeContainingTest - { - [Test] - public void SomeTest() { } - } - - public class FixtureWithoutTestFixtureAttributeContainingTestCase - { - [TestCase(42)] - public void SomeTest(int x) { } - } - - public class FixtureWithoutTestFixtureAttributeContainingTestCaseSource - { - [TestCaseSource("data")] - public void SomeTest(int x) { } - } - -#if !NUNITLITE - public class FixtureWithoutTestFixtureAttributeContainingTheory - { - [Theory] - public void SomeTest(int x) { } - } -#endif - -#if CLR_2_0 || CLR_4_0 - public static class StaticFixtureWithoutTestFixtureAttribute - { - [Test] - public static void StaticTest() { } - } -#endif - - [TestFixture] - public class MultipleSetUpAttributes - { - [SetUp] - public void Init1() - {} - - [SetUp] - public void Init2() - {} - - [Test] public void OneTest() - {} - } - - [TestFixture] - public class MultipleTearDownAttributes - { - [TearDown] - public void Destroy1() - {} - - [TearDown] - public void Destroy2() - {} - - [Test] public void OneTest() - {} - } - - [TestFixture] - [Ignore("testing ignore a fixture")] - public class IgnoredFixture - { - [Test] - public void Success() - {} - } - - [TestFixture] - public class OuterClass - { - [TestFixture] - public class NestedTestFixture - { - [TestFixture] - public class DoublyNestedTestFixture - { - [Test] - public void Test() - { - } - } - } - } - - [TestFixture] - public abstract class AbstractTestFixture - { - [TearDown] - public void Destroy1() - {} - - [Test] - public void SomeTest() - { - } - } - - public class DerivedFromAbstractTestFixture : AbstractTestFixture - { - } - - [TestFixture] - public class BaseClassTestFixture - { - [Test] - public void Success() { } - } - - public abstract class AbstractDerivedTestFixture : BaseClassTestFixture - { - [Test] - public void Test() - { - } - } - - public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture - { - } - - [TestFixture] - public abstract class AbstractBaseFixtureWithAttribute - { - } - - [TestFixture] - public abstract class AbstractDerivedFixtureWithSecondAttribute - : AbstractBaseFixtureWithAttribute - { - } - - public class DoubleDerivedClassWithTwoInheritedAttributes - : AbstractDerivedFixtureWithSecondAttribute - { - } - - [TestFixture] - public class MultipleFixtureSetUpAttributes - { - [TestFixtureSetUp] - public void Init1() - {} - - [TestFixtureSetUp] - public void Init2() - {} - - [Test] public void OneTest() - {} - } - - [TestFixture] - public class MultipleFixtureTearDownAttributes - { - [TestFixtureTearDown] - public void Destroy1() - {} - - [TestFixtureTearDown] - public void Destroy2() - {} - - [Test] public void OneTest() - {} - } - - // Base class used to ensure following classes - // all have at least one test - public class OneTestBase - { - [Test] public void OneTest() { } - } - - [TestFixture] - public class PrivateSetUp : OneTestBase - { - [SetUp] - private void Setup() {} - } - - [TestFixture] - public class ProtectedSetUp : OneTestBase - { - [SetUp] - protected void Setup() {} - } - - [TestFixture] - public class StaticSetUp : OneTestBase - { - [SetUp] - public static void Setup() {} - } - - [TestFixture] - public class SetUpWithReturnValue : OneTestBase - { - [SetUp] - public int Setup() { return 0; } - } - - [TestFixture] - public class SetUpWithParameters : OneTestBase - { - [SetUp] - public void Setup(int j) { } - } - - [TestFixture] - public class PrivateTearDown : OneTestBase - { - [TearDown] - private void Teardown() {} - } - - [TestFixture] - public class ProtectedTearDown : OneTestBase - { - [TearDown] - protected void Teardown() {} - } - - [TestFixture] - public class StaticTearDown : OneTestBase - { - [SetUp] - public static void TearDown() {} - } - - [TestFixture] - public class TearDownWithReturnValue : OneTestBase - { - [TearDown] - public int Teardown() { return 0; } - } - - [TestFixture] - public class TearDownWithParameters : OneTestBase - { - [TearDown] - public void Teardown(int j) { } - } - - [TestFixture] - public class PrivateFixtureSetUp : OneTestBase - { - [TestFixtureSetUp] - private void Setup() {} - } - - [TestFixture] - public class ProtectedFixtureSetUp : OneTestBase - { - [TestFixtureSetUp] - protected void Setup() {} - } - - [TestFixture] - public class StaticFixtureSetUp : OneTestBase - { - [TestFixtureSetUp] - public static void Setup() {} - } - - [TestFixture] - public class FixtureSetUpWithReturnValue : OneTestBase - { - [TestFixtureSetUp] - public int Setup() { return 0; } - } - - [TestFixture] - public class FixtureSetUpWithParameters : OneTestBase - { - [SetUp] - public void Setup(int j) { } - } - - [TestFixture] - public class PrivateFixtureTearDown : OneTestBase - { - [TestFixtureTearDown] - private void Teardown() {} - } - - [TestFixture] - public class ProtectedFixtureTearDown : OneTestBase - { - [TestFixtureTearDown] - protected void Teardown() {} - } - - [TestFixture] - public class StaticFixtureTearDown : OneTestBase - { - [TestFixtureTearDown] - public static void Teardown() {} - } - - [TestFixture] - public class FixtureTearDownWithReturnValue : OneTestBase - { - [TestFixtureTearDown] - public int Teardown() { return 0; } - } - - [TestFixture] - public class FixtureTearDownWithParameters : OneTestBase - { - [TestFixtureTearDown] - public void Teardown(int j) { } - } - -#if !NETCF && !SILVERLIGHT - [TestFixture] - public class FixtureThatChangesTheCurrentPrincipal - { - [Test] - public void ChangeCurrentPrincipal() - { - WindowsIdentity identity = WindowsIdentity.GetCurrent(); - GenericPrincipal principal = new GenericPrincipal( identity, new string[] { } ); - System.Threading.Thread.CurrentPrincipal = principal; - } - } -#endif - -#if CLR_2_0 || CLR_4_0 -#if !NETCF - [TestFixture(typeof(int))] - [TestFixture(typeof(string))] - public class GenericFixtureWithProperArgsProvided - { - [Test] - public void SomeTest() { } - } - - public class GenericFixtureWithNoTestFixtureAttribute - { - [Test] - public void SomeTest() { } - } - - [TestFixture] - public class GenericFixtureWithNoArgsProvided - { - [Test] - public void SomeTest() { } - } - - [TestFixture] - public abstract class AbstractFixtureBase - { - [Test] - public void SomeTest() { } - } - - public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided : AbstractFixtureBase - { - } - - [TestFixture(typeof(int))] - [TestFixture(typeof(string))] - public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided : AbstractFixtureBase - { - } -#endif -#endif -} diff --git a/test/NUnitLite/src/testdata/TestMethodSignatureFixture.cs b/test/NUnitLite/src/testdata/TestMethodSignatureFixture.cs deleted file mode 100644 index 2c97bd5b9..000000000 --- a/test/NUnitLite/src/testdata/TestMethodSignatureFixture.cs +++ /dev/null @@ -1,124 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.TestMethodSignatureFixture -{ - [TestFixture] - public class TestMethodSignatureFixture - { - public static int Tests = 19; - public static int Runnable = 11; - public static int NotRunnable = 8; - public static int Errors = 3; - public static int Failures = 0; - - [Test] - public void InstanceTestMethod() { } - - [Test] - public static void StaticTestMethod() { } - - [Test] - public void TestMethodWithArgumentsNotProvided(int x, int y, string label) { } - - [Test] - public static void StaticTestMethodWithArgumentsNotProvided(int x, int y, string label) { } - - [TestCase(5, 2, "ABC")] - public void TestMethodWithoutParametersWithArgumentsProvided() { } - - [TestCase(5, 2, "ABC")] - public void TestMethodWithArgumentsProvided(int x, int y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - - [TestCase(5, 2, "ABC")] - public static void StaticTestMethodWithArgumentsProvided(int x, int y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - - [TestCase(2, 2)] - public void TestMethodWithWrongNumberOfArgumentsProvided(int x, int y, string label) - { - } - - [TestCase(2, 2, 3.5)] - public void TestMethodWithWrongArgumentTypesProvided(int x, int y, string label) - { - } - - [TestCase(2, 2)] - public static void StaticTestMethodWithWrongNumberOfArgumentsProvided(int x, int y, string label) - { - } - - [TestCase(2, 2, 3.5)] - public static void StaticTestMethodWithWrongArgumentTypesProvided(int x, int y, string label) - { - } - - [TestCase(3.7, 2, 5.7)] - public void TestMethodWithConvertibleArguments(double x, double y, double sum) - { - Assert.AreEqual(sum, x + y, 0.0001); - } - - [TestCase(3.7, 2, 5.7)] - public void TestMethodWithNonConvertibleArguments(int x, int y, int sum) - { - Assert.AreEqual(sum, x + y, 0.0001); - } - - [TestCase(12, 3, 4)] - [TestCase( 12, 2, 6 )] - [TestCase( 12, 4, 3 )] - public void TestMethodWithMultipleTestCases( int n, int d, int q ) - { - Assert.AreEqual( q, n / d ); - } - -// [Test] -// public abstract void AbstractTestMethod() { } - - [Test] - protected void ProtectedTestMethod() { } - - [Test] - private void PrivateTestMethod() { } - - [Test] - public bool TestMethodWithReturnType() - { - return true; - } - } -} diff --git a/test/NUnitLite/src/testdata/TheoryFixture.cs b/test/NUnitLite/src/testdata/TheoryFixture.cs deleted file mode 100644 index 8d4dc896d..000000000 --- a/test/NUnitLite/src/testdata/TheoryFixture.cs +++ /dev/null @@ -1,84 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; - -namespace NUnit.TestData.TheoryFixture -{ - [TestFixture] - public class TheoryFixture - { - [Datapoint] - internal int i0 = 0; - [Datapoint] - internal static int i1 = 1; - [Datapoint] - public int i100 = 100; - - private void Dummy() - { - int x = i0; // Suppress Compiler Warnings - int y = i1; // - } - - [Theory] - public void TheoryWithNoArguments() - { - } - - [Theory] - public void TheoryWithArgumentsButNoDatapoints(decimal x, decimal y) - { - } - - [Theory] - public void TheoryWithArgumentsAndDatapoints(int x, int y) - { - } - - [TestCase(5, 10)] - [TestCase(3, 12)] - public void TestWithArguments(int x, int y) - { - } - - [Theory] - public void TestWithBooleanArguments(bool a, bool b) - { - } - - [Theory] - public void TestWithEnumAsArgument(System.AttributeTargets targets) - { - } - - [Theory] - public void TestWithAllBadValues( - [Values(-12.0, -4.0, -9.0)] double d) - { - Assume.That(d > 0); - Assert.Pass(); - } - } -} diff --git a/test/NUnitLite/src/testdata/TimeoutFixture.cs b/test/NUnitLite/src/testdata/TimeoutFixture.cs deleted file mode 100644 index 766d53936..000000000 --- a/test/NUnitLite/src/testdata/TimeoutFixture.cs +++ /dev/null @@ -1,65 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if (CLR_2_0 || CLR_4_0) -using System; -using NUnit.Framework; - -namespace NUnit.TestData -{ - [TestFixture] - public class TimeoutFixture - { - public bool TearDownWasRun; - - [SetUp] - public void SetUp() - { - TearDownWasRun = false; - } - - [TearDown] - public void TearDown() - { - TearDownWasRun = true; - } - - [Test, Timeout(50)] - public void InfiniteLoopWith50msTimeout() - { - while (true) { } - } - } - - [TestFixture, Timeout(50)] - public class ThreadingFixtureWithTimeout - { - [Test] - public void Test1() { } - [Test] - public void Test2WithInfiniteLoop() { while (true) { } } - [Test] - public void Test3() { } - } -} -#endif diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-2.0.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-2.0.csproj deleted file mode 100644 index b16f8f8f2..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-2.0.csproj +++ /dev/null @@ -1,124 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {442DAB16-3063-4FE3-90B6-C29C3D85360D} - Library - Properties - NUnit.TestData - nunitlite.testdata - v2.0 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-2.0\ - - - true - full - false - TRACE;DEBUG;NET_2_0,CLR_2_0,NUNITLITE - prompt - 4 - ..\..\bin\Debug\net-2.0\ - - - pdbonly - true - TRACE;NET_2_0,CLR_2_0,NUNITLITE - prompt - 4 - ..\..\bin\Release\net-2.0\ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - {C24A3FC4-2541-4E9C-BADD-564777610B75} - nunitlite-2.0 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-3.5.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-3.5.csproj deleted file mode 100644 index 70945c20b..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-3.5.csproj +++ /dev/null @@ -1,124 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {652AFEEB-B19C-4C67-A014-2248EA72F229} - Library - Properties - NUnit.TestData - nunitlite.testdata - v3.5 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-3.5\ - - - true - full - false - ..\..\bin\Debug\net-3.5\ - TRACE;DEBUG;NET_3_5, CLR_2_0,NUNITLITE - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\net-3.5\ - TRACE;NET_3_5, CLR_2_0,NUNITLITE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - {43B24DC5-16D6-45EF-93F1-B021B785A892} - nunitlite-3.5 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-4.0.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-4.0.csproj deleted file mode 100644 index 45c28fbd4..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-4.0.csproj +++ /dev/null @@ -1,124 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {5C77A144-3CD1-42FC-B622-410E1945CA1E} - Library - Properties - NUnit.TestData - nunitlite.testdata - v4.0 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-4.0\ - - - true - full - false - ..\..\bin\Debug\net-4.0\ - TRACE;DEBUG;NET_4_0, CLR_4_0,NUNITLITE - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\net-4.0\ - TRACE;NET_4_0, CLR_4_0,NUNITLITE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - {1567BCCE-7BE9-4815-84D7-7F794DB39081} - nunitlite-4.0 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-4.5.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-4.5.csproj deleted file mode 100644 index f8f82a4a4..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-4.5.csproj +++ /dev/null @@ -1,130 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {6358FBCA-9CA2-4A70-AF87-18B916400CEE} - Library - Properties - NUnit.TestData - nunitlite.testdata - v4.5 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - obj\$(Configuration)\net-4.5\ - - - true - full - false - ..\..\bin\Debug\net-4.5\ - TRACE;DEBUG;NET_4_5,CLR_4_0,NUNITLITE - prompt - 4 - false - - - pdbonly - true - ..\..\bin\Release\net-4.5\ - TRACE;NET_4_5,CLR_4_0,NUNITLITE - prompt - 4 - false - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - {d12f0f7b-8de3-43ec-ba49-41052d065a9b} - nunitlite-4.5 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-netcf-2.0.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-netcf-2.0.csproj deleted file mode 100644 index 0aebdf292..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-netcf-2.0.csproj +++ /dev/null @@ -1,101 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {F67E80E8-DF9F-4C66-9142-5002FA638EB7} - Library - Properties - NUnit.TestData - nunitlite.testdata - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - NUnitLite - v2.0 - Windows CE - - - obj\$(Configuration)\netcf-2.0\ - - - true - full - false - ..\..\bin\Debug\netcf-2.0\ - TRACE;DEBUG;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\..\bin\Release\netcf-2.0 - TRACE;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {BED999D7-F594-4CE4-A037-E40E2B9C1288} - nunitlite-netcf-2.0 - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-netcf-3.5.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-netcf-3.5.csproj deleted file mode 100644 index 7c679b2e7..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-netcf-3.5.csproj +++ /dev/null @@ -1,102 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {0B7C0B55-6A49-4F32-993E-C9ED6DA0B73C} - Library - Properties - NUnit.TestData - nunitlite.testdata - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - nunitlite.testdata_netcf_3._5 - v3.5 - Windows CE - - - obj\$(Configuration)\netcf-3.5\ - - - true - full - false - ..\..\bin\Debug\netcf-3.5\ - TRACE;DEBUG;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\..\bin\Release\netcf-3.5\ - TRACE;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {5F6CB3DC-5CE5-4C6A-AB23-936DB3B35DCC} - nunitlite-netcf-3.5 - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-sl-3.0.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-sl-3.0.csproj deleted file mode 100644 index bd4d24cac..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-sl-3.0.csproj +++ /dev/null @@ -1,103 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnit.TestData - nunitlite.testdata - Silverlight - v3.0 - $(TargetFrameworkVersion) - false - true - true - false - - obj\$(Configuration)\sl-3.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-3.0\ - TRACE;DEBUG;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-3.0\ - TRACE;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {02B02379-2596-4E45-8B10-835D62EA2D9E} - nunitlite-sl-3.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-sl-4.0.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-sl-4.0.csproj deleted file mode 100644 index 73cc533a0..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-sl-4.0.csproj +++ /dev/null @@ -1,108 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {E97412B5-8C91-4236-8E9A-24C8E20BC675} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnit.TestData - nunitlite.testdata - Silverlight - v4.0 - $(TargetFrameworkVersion) - false - true - true - obj\$(Configuration)\sl-4.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-4.0\ - TRACE;DEBUG;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-4.0\ - TRACE;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {41326141-EB24-4984-9D9B-5CFAA55946BA} - nunitlite-sl-4.0 - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata-sl-5.0.csproj b/test/NUnitLite/src/testdata/nunitlite.testdata-sl-5.0.csproj deleted file mode 100644 index f1a2b776e..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata-sl-5.0.csproj +++ /dev/null @@ -1,102 +0,0 @@ - - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnit.TestData - nunitlite.testdata - Silverlight - v5.0 - $(TargetFrameworkVersion) - false - true - true - - obj\$(Configuration)\sl-5.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-5.0\ - TRACE;DEBUG;SILVERLIGHT;SL_5_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-5.0\ - TRACE;SILVERLIGHT;SL_5_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3} - nunitlite-sl-5.0 - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/testdata/nunitlite.testdata.build b/test/NUnitLite/src/testdata/nunitlite.testdata.build deleted file mode 100644 index 5ab089e99..000000000 --- a/test/NUnitLite/src/testdata/nunitlite.testdata.build +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/NUnitLite/src/tests/Api/ResultStateTests.cs b/test/NUnitLite/src/tests/Api/ResultStateTests.cs deleted file mode 100644 index 8c813d33e..000000000 --- a/test/NUnitLite/src/tests/Api/ResultStateTests.cs +++ /dev/null @@ -1,176 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class ResultStateTests - { - [TestCase(TestStatus.Failed)] - [TestCase(TestStatus.Skipped)] - [TestCase(TestStatus.Inconclusive)] - [TestCase(TestStatus.Passed)] - public void Status_ConstructorWithOneArguments_ReturnsConstructorArgumentStatus(TestStatus status) - { - // Arrange N/A - - ResultState resultState = new ResultState(status); - - Assert.AreEqual(status, resultState.Status); - } - - [Test] - public void Label_ConstructorWithOneArguments_ReturnsStringEmpty() - { - // Arrange N/A - - ResultState resultState = new ResultState(TestStatus.Failed); - - Assert.AreEqual(string.Empty, resultState.Label); - } - - [TestCase(TestStatus.Failed)] - [TestCase(TestStatus.Skipped)] - [TestCase(TestStatus.Inconclusive)] - [TestCase(TestStatus.Passed)] - public void Status_ConstructorWithTwoArguments_ReturnsConstructorArgumentStatus(TestStatus status) - { - // Arrange N/A - - ResultState resultState = new ResultState(status, string.Empty); - - Assert.AreEqual(status, resultState.Status); - } - - [TestCase("")] - [TestCase("label")] - public void Label_ConstructorWithTwoArguments_ReturnsConstructorArgumentLabel(string label) - { - // Arrange N/A - - ResultState resultState = new ResultState(TestStatus.Failed, label); - - Assert.AreEqual(label, resultState.Label); - } - - [Test] - public void Label_ConstructorWithTwoArgumentsLabelArgumentIsNull_ReturnsEmptyString() - { - // Arrange N/A - - ResultState resultState = new ResultState(TestStatus.Failed, null); - - Assert.AreEqual(string.Empty, resultState.Label); - } - - [TestCase(TestStatus.Skipped, SpecialValue.Null, "Skipped")] - [TestCase(TestStatus.Passed, "", "Passed")] - [TestCase(TestStatus.Passed, "testLabel", "Passed:testLabel")] - public void ToString_Constructor_ReturnsExepectedString(TestStatus status, string label, string expected) - { - // Arrange N/A - - ResultState resultState = new ResultState(status, label); - - Assert.AreEqual(expected, resultState.ToString()); - } - - #region Test Fields - - [Test] - public void Inconclusive_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Inconclusive; - - Assert.AreEqual(TestStatus.Inconclusive, resultState.Status, "Status not correct."); - Assert.AreEqual(string.Empty, resultState.Label, "Label not correct."); - } - - [Test] - public void NotRunnable_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.NotRunnable; - - Assert.AreEqual(TestStatus.Skipped, resultState.Status, "Status not correct."); - Assert.AreEqual("Invalid", resultState.Label, "Label not correct."); - } - - [Test] - public void Skipped_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Skipped; - - Assert.AreEqual(TestStatus.Skipped, resultState.Status, "Status not correct."); - Assert.AreEqual(string.Empty, resultState.Label, "Label not correct."); - } - - [Test] - public void Ignored_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Ignored; - - Assert.AreEqual(TestStatus.Skipped, resultState.Status, "Status not correct."); - Assert.AreEqual("Ignored", resultState.Label, "Label not correct."); - } - - [Test] - public void Success_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Success; - - Assert.AreEqual(TestStatus.Passed, resultState.Status, "Status not correct."); - Assert.AreEqual(string.Empty, resultState.Label, "Label not correct."); - } - - [Test] - public void Failure_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Failure; - - Assert.AreEqual(TestStatus.Failed, resultState.Status, "Status not correct."); - Assert.AreEqual(string.Empty, resultState.Label, "Label not correct."); - } - - [Test] - public void Error_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Error; - - Assert.AreEqual(TestStatus.Failed, resultState.Status, "Status not correct."); - Assert.AreEqual("Error", resultState.Label, "Label not correct."); - } - - [Test] - public void Cancelled_NA_ReturnsResultStateWithPropertiesCorrectlySet() - { - ResultState resultState = ResultState.Cancelled; - - Assert.AreEqual(TestStatus.Failed, resultState.Status, "Status not correct."); - Assert.AreEqual("Cancelled", resultState.Label, "Label not correct."); - } - - #endregion - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/App.g.cs b/test/NUnitLite/src/tests/App.g.cs deleted file mode 100644 index 7fb3902dd..000000000 --- a/test/NUnitLite/src/tests/App.g.cs +++ /dev/null @@ -1,53 +0,0 @@ -#pragma checksum "D:\Dev\NUnit\nunitlite\silverlight\src\tests\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "7F705B1DDE1B06450160A1EECA2F6007" -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.17626 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System; -using System.Windows; -using System.Windows.Automation; -using System.Windows.Automation.Peers; -using System.Windows.Automation.Provider; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Ink; -using System.Windows.Input; -using System.Windows.Interop; -using System.Windows.Markup; -using System.Windows.Media; -using System.Windows.Media.Animation; -using System.Windows.Media.Imaging; -using System.Windows.Resources; -using System.Windows.Shapes; -using System.Windows.Threading; - - -namespace NUnitLite.Tests { - - - public partial class App : System.Windows.Application { - - private bool _contentLoaded; - - /// - /// InitializeComponent - /// - [System.Diagnostics.DebuggerNonUserCodeAttribute()] - public void InitializeComponent() { - if (_contentLoaded) { - return; - } - _contentLoaded = true; - System.Windows.Application.LoadComponent(this, new System.Uri("/nunitlite.tests;component/App.xaml", System.UriKind.Relative)); - } - } -} - diff --git a/test/NUnitLite/src/tests/App.xaml.cs b/test/NUnitLite/src/tests/App.xaml.cs deleted file mode 100644 index f7401fe24..000000000 --- a/test/NUnitLite/src/tests/App.xaml.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Windows; - -namespace NUnitLite.Tests -{ - public partial class App : Application - { - - public App() - { - this.Startup += this.Application_Startup; - this.Exit += this.Application_Exit; - this.UnhandledException += this.Application_UnhandledException; - - InitializeComponent(); - } - - private void Application_Startup(object sender, StartupEventArgs e) - { - RootVisual = new NUnitLite.Runner.Silverlight.TestPage(); - } - - private void Application_Exit(object sender, EventArgs e) - { - - } - private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) - { - // If the app is running outside of the debugger then report the exception using - // the browser's exception mechanism. On IE this will display it a yellow alert - // icon in the status bar and Firefox will display a script error. - if (!System.Diagnostics.Debugger.IsAttached) - { - - // NOTE: This will allow the application to continue running after an exception has been thrown - // but not handled. - // For production applications this error handling should be replaced with something that will - // report the error to the website and stop the application. - e.Handled = true; - Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); }); - } - } - private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e) - { - try - { - string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; - errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n"); - - System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");"); - } - catch (Exception) - { - } - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/AssemblyInfo.cs b/test/NUnitLite/src/tests/AssemblyInfo.cs deleted file mode 100644 index 93c175d48..000000000 --- a/test/NUnitLite/src/tests/AssemblyInfo.cs +++ /dev/null @@ -1,47 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("NUnitLiteTests")] -[assembly: AssemblyDescription("Tests of the NUnitLite testing framework")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NUnitLite")] -[assembly: AssemblyCopyright("Copyright © 2007, Charlie Poole")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e7a2d0a1-69b5-40a6-bbfa-4c2e77335d8d")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] -#if !PocketPC && !WindowsCE && !NETCF -[assembly: AssemblyFileVersion("1.0.0.0")] -#endif - -// Under Silverlight, it's only possible to reflect -// over members that would be accessible normally. -#if SILVERLIGHT -[assembly: InternalsVisibleTo("nunitlite")] -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Assertions/ArrayEqualsFailureMessageFixture.cs b/test/NUnitLite/src/tests/Assertions/ArrayEqualsFailureMessageFixture.cs deleted file mode 100644 index 2cbd4213c..000000000 --- a/test/NUnitLite/src/tests/Assertions/ArrayEqualsFailureMessageFixture.cs +++ /dev/null @@ -1,257 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Assertions -{ - /// - /// Summary description for ArrayEqualsFailureMessageFixture. - /// - [TestFixture] - public class ArrayEqualsFailureMessageFixture : MessageChecker - { - [Test, ExpectedException(typeof(AssertionException))] - public void ArraysHaveDifferentRanks() - { - int[] expected = new int[] { 1, 2, 3, 4 }; - int[,] actual = new int[,] { { 1, 2 }, { 3, 4 } }; - - expectedMessage = - " Expected is , actual is " + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ExpectedArrayIsLonger() - { - int[] expected = new int[] { 1, 2, 3, 4, 5 }; - int[] actual = new int[] { 1, 2, 3 }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at index [3]" + NL + - " Missing: < 4, 5 >"; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ActualArrayIsLonger() - { - int[] expected = new int[] { 1, 2, 3 }; - int[] actual = new int[] { 1, 2, 3, 4, 5, 6, 7 }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at index [3]" + NL + - " Extra: < 4, 5, 6... >"; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailureOnSingleDimensionedArrays() - { - int[] expected = new int[] { 1, 2, 3 }; - int[] actual = new int[] { 1, 5, 3 }; - - expectedMessage = - " Expected and actual are both " + NL + - " Values differ at index [1]" + NL + - TextMessageWriter.Pfx_Expected + "2" + NL + - TextMessageWriter.Pfx_Actual + "5" + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void DoubleDimensionedArrays() - { - int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; - int[,] actual = new int[,] { { 1, 3, 2 }, { 4, 0, 6 } }; - - expectedMessage = - " Expected and actual are both " + NL + - " Values differ at index [0,1]" + NL + - TextMessageWriter.Pfx_Expected + "2" + NL + - TextMessageWriter.Pfx_Actual + "3" + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void TripleDimensionedArrays() - { - int[, ,] expected = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; - int[, ,] actual = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 0, 6 }, { 7, 8 } } }; - - expectedMessage = - " Expected and actual are both " + NL + - " Values differ at index [1,0,0]" + NL + - TextMessageWriter.Pfx_Expected + "5" + NL + - TextMessageWriter.Pfx_Actual + "0" + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FiveDimensionedArrays() - { - int[, , , ,] expected = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; - int[, , , ,] actual = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 4, 3 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; - - expectedMessage = - " Expected and actual are both " + NL + - " Values differ at index [0,0,0,1,0]" + NL + - TextMessageWriter.Pfx_Expected + "3" + NL + - TextMessageWriter.Pfx_Actual + "4" + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void JaggedArrays() - { - int[][] expected = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; - int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 0, 7 }, new int[] { 8, 9 } }; - - expectedMessage = - " Expected and actual are both " + NL + - " Values differ at index [1]" + NL + - " Expected and actual are both " + NL + - " Values differ at index [2]" + NL + - TextMessageWriter.Pfx_Expected + "6" + NL + - TextMessageWriter.Pfx_Actual + "0" + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void JaggedArrayComparedToSimpleArray() - { - int[] expected = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 0, 7 }, new int[] { 8, 9 } }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at index [0]" + NL + - TextMessageWriter.Pfx_Expected + "1" + NL + - TextMessageWriter.Pfx_Actual + "< 1, 2, 3 >" + NL; - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ArraysWithDifferentRanksAsCollection() - { - int[] expected = new int[] { 1, 2, 3, 4 }; - int[,] actual = new int[,] { { 1, 0 }, { 3, 4 } }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at expected index [1], actual index [0,1]" + NL + - TextMessageWriter.Pfx_Expected + "2" + NL + - TextMessageWriter.Pfx_Actual + "0" + NL; - Assert.That(actual, Is.EqualTo(expected).AsCollection); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ArraysWithDifferentDimensionsAsCollection() - { - int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; - int[,] actual = new int[,] { { 1, 2 }, { 3, 0 }, { 5, 6 } }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at expected index [1,0], actual index [1,1]" + NL + - TextMessageWriter.Pfx_Expected + "4" + NL + - TextMessageWriter.Pfx_Actual + "0" + NL; - Assert.That(actual, Is.EqualTo(expected).AsCollection); - } - - // [Test,ExpectedException(typeof(AssertionException))] - // public void ExpectedArrayIsLonger() - // { - // string[] array1 = { "one", "two", "three" }; - // string[] array2 = { "one", "two", "three", "four", "five" }; - // - // expectedMessage = - // " Expected is , actual is " + NL + - // " Values differ at index [3]" + NL + - // " Missing: < \"four\", \"five\" >"; - // Assert.That(array1, Is.EqualTo(array2)); - // } - - [Test, ExpectedException(typeof(AssertionException))] - public void SameLengthDifferentContent() - { - string[] array1 = { "one", "two", "three" }; - string[] array2 = { "one", "two", "ten" }; - - expectedMessage = - " Expected and actual are both " + NL + - " Values differ at index [2]" + NL + - " Expected string length 3 but was 5. Strings differ at index 1." + NL + - " Expected: \"ten\"" + NL + - " But was: \"three\"" + NL + - " ------------^" + NL; - Assert.That(array1, Is.EqualTo(array2)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ArraysDeclaredAsDifferentTypes() - { - string[] array1 = { "one", "two", "three" }; - object[] array2 = { "one", "three", "two" }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at index [1]" + NL + - " Expected string length 5 but was 3. Strings differ at index 1." + NL + - " Expected: \"three\"" + NL + - " But was: \"two\"" + NL + - " ------------^" + NL; - Assert.That(array1, Is.EqualTo(array2)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ArrayAndCollection_Failure() - { - int[] a = new int[] { 1, 2, 3 }; - ICollection b = new SimpleObjectCollection(1, 3); - Assert.AreEqual(a, b); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void DifferentArrayTypesEqualFails() - { - string[] array1 = { "one", "two", "three" }; - object[] array2 = { "one", "three", "two" }; - - expectedMessage = - " Expected is , actual is " + NL + - " Values differ at index [1]" + NL + - " Expected string length 3 but was 5. Strings differ at index 1." + NL + - " Expected: \"two\"" + NL + - " But was: \"three\"" + NL + - " ------------^" + NL; - Assert.AreEqual(array1, array2); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/ArrayEqualsFixture.cs b/test/NUnitLite/src/tests/Assertions/ArrayEqualsFixture.cs deleted file mode 100644 index 16b36bdc2..000000000 --- a/test/NUnitLite/src/tests/Assertions/ArrayEqualsFixture.cs +++ /dev/null @@ -1,220 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTIONA -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Assertions -{ - /// - /// Summary description for ArrayEqualTests. - /// - [TestFixture] - public class ArrayEqualsFixture : AssertionHelper - { - [Test] - public void ArrayIsEqualToItself() - { - string[] array = { "one", "two", "three" }; - Assert.That( array, Is.SameAs(array) ); - Assert.AreEqual( array, array ); - Expect(array, EqualTo(array)); - } - - [Test] - public void ArraysOfString() - { - string[] array1 = { "one", "two", "three" }; - string[] array2 = { "one", "two", "three" }; - Assert.IsFalse( array1 == array2 ); - Assert.AreEqual(array1, array2); - Expect(array1, EqualTo(array2)); - Assert.AreEqual(array2, array1); - Expect(array2, EqualTo(array1)); - } - - [Test] - public void ArraysOfInt() - { - int[] a = new int[] { 1, 2, 3 }; - int[] b = new int[] { 1, 2, 3 }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void ArraysOfDouble() - { - double[] a = new double[] { 1.0, 2.0, 3.0 }; - double[] b = new double[] { 1.0, 2.0, 3.0 }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void ArraysOfDecimal() - { - decimal[] a = new decimal[] { 1.0m, 2.0m, 3.0m }; - decimal[] b = new decimal[] { 1.0m, 2.0m, 3.0m }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void ArrayOfIntAndArrayOfDouble() - { - int[] a = new int[] { 1, 2, 3 }; - double[] b = new double[] { 1.0, 2.0, 3.0 }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void ArraysDeclaredAsDifferentTypes() - { - string[] array1 = { "one", "two", "three" }; - object[] array2 = { "one", "two", "three" }; - Assert.AreEqual( array1, array2, "String[] not equal to Object[]" ); - Assert.AreEqual( array2, array1, "Object[] not equal to String[]" ); - Expect(array1, EqualTo(array2), "String[] not equal to Object[]"); - Expect(array2, EqualTo(array1), "Object[] not equal to String[]"); - } - - [Test] - public void ArraysOfMixedTypes() - { - DateTime now = DateTime.Now; - object[] array1 = new object[] { 1, 2.0f, 3.5d, 7.000m, "Hello", now }; - object[] array2 = new object[] { 1.0d, 2, 3.5, 7, "Hello", now }; - Assert.AreEqual( array1, array2 ); - Assert.AreEqual(array2, array1); - Expect(array1, EqualTo(array2)); - Expect(array2, EqualTo(array1)); - } - - [Test] - public void DoubleDimensionedArrays() - { - int[,] a = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; - int[,] b = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void TripleDimensionedArrays() - { - int[, ,] expected = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; - int[,,] actual = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; - - Assert.AreEqual(expected, actual); - Expect(actual, EqualTo(expected)); - } - - [Test] - public void FiveDimensionedArrays() - { - int[, , , ,] expected = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; - int[, , , ,] actual = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; - - Assert.AreEqual(expected, actual); - Expect(actual, EqualTo(expected)); - } - - [Test] - public void ArraysOfArrays() - { - int[][] a = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } }; - int[][] b = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void JaggedArrays() - { - int[][] expected = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; - int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; - - Assert.AreEqual(expected, actual); - Expect(actual, EqualTo(expected)); - } - - [Test] - public void ArraysPassedAsObjects() - { - object a = new int[] { 1, 2, 3 }; - object b = new double[] { 1.0, 2.0, 3.0 }; - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void ArrayAndCollection() - { - int[] a = new int[] { 1, 2, 3 }; - ICollection b = new SimpleObjectCollection( a ); - Assert.AreEqual(a, b); - Assert.AreEqual(b, a); - Expect(a, EqualTo(b)); - Expect(b, EqualTo(a)); - } - - [Test] - public void ArraysWithDifferentRanksComparedAsCollection() - { - int[] expected = new int[] { 1, 2, 3, 4 }; - int[,] actual = new int[,] { { 1, 2 }, { 3, 4 } }; - - Assert.AreNotEqual(expected, actual); - Expect(actual, Not.EqualTo(expected)); - Expect(actual, EqualTo(expected).AsCollection); - } - - [Test] - public void ArraysWithDifferentDimensionsMatchedAsCollection() - { - int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; - int[,] actual = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; - - Assert.AreNotEqual(expected, actual); - Expect(actual, Not.EqualTo(expected)); - Expect(actual, EqualTo(expected).AsCollection); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/ArrayNotEqualFixture.cs b/test/NUnitLite/src/tests/Assertions/ArrayNotEqualFixture.cs deleted file mode 100644 index cad638c17..000000000 --- a/test/NUnitLite/src/tests/Assertions/ArrayNotEqualFixture.cs +++ /dev/null @@ -1,68 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Assertions -{ - /// - /// Summary description for ArrayNotEqualFixture. - /// - [TestFixture] - public class ArrayNotEqualFixture : AssertionHelper - { - [Test] - public void DifferentLengthArrays() - { - string[] array1 = { "one", "two", "three" }; - string[] array2 = { "one", "two", "three", "four", "five" }; - - Assert.AreNotEqual(array1, array2); - Assert.AreNotEqual(array2, array1); - Expect(array1, Not.EqualTo(array2)); - Expect(array2, Not.EqualTo(array1)); - } - - [Test] - public void SameLengthDifferentContent() - { - string[] array1 = { "one", "two", "three" }; - string[] array2 = { "one", "two", "ten" }; - Assert.AreNotEqual(array1, array2); - Assert.AreNotEqual(array2, array1); - Expect(array1, Not.EqualTo(array2)); - Expect(array2, Not.EqualTo(array1)); - } - - [Test] - public void ArraysDeclaredAsDifferentTypes() - { - string[] array1 = { "one", "two", "three" }; - object[] array2 = { "one", "three", "two" }; - Assert.AreNotEqual(array1, array2); - Expect(array1, Not.EqualTo(array2)); - Expect(array2, Not.EqualTo(array1)); - } - - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssertFailTests.cs b/test/NUnitLite/src/tests/Assertions/AssertFailTests.cs deleted file mode 100644 index 3bb5112ac..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssertFailTests.cs +++ /dev/null @@ -1,83 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Api; -using NUnit.TestData.AssertFailFixture; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AssertFailTests - { - [Test, ExpectedException(typeof(AssertionException))] - public void ThrowsAssertionException() - { - Assert.Fail(); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "MESSAGE")] - public void ThrowsAssertionExceptionWithMessage() - { - Assert.Fail("MESSAGE"); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "MESSAGE: 2+2=4")] - public void ThrowsAssertionExceptionWithMessageAndArgs() - { - Assert.Fail("MESSAGE: {0}+{1}={2}", 2, 2, 4); - } - - [Test] - public void AssertFailWorks() - { - ITestResult result = TestBuilder.RunTestCase( - typeof(AssertFailFixture), - "CallAssertFail"); - - Assert.AreEqual(ResultState.Failure, result.ResultState); - } - - [Test] - public void AssertFailWorksWithMessage() - { - ITestResult result = TestBuilder.RunTestCase( - typeof(AssertFailFixture), - "CallAssertFailWithMessage"); - - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.AreEqual("MESSAGE", result.Message); - } - - [Test] - public void AssertFailWorksWithMessageAndArgs() - { - ITestResult result = TestBuilder.RunTestCase( - typeof(AssertFailFixture), - "CallAssertFailWithMessageAndArgs"); - - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.AreEqual("MESSAGE: 2+2=4", result.Message); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssertIgnoreTests.cs b/test/NUnitLite/src/tests/Assertions/AssertIgnoreTests.cs deleted file mode 100644 index 581498f63..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssertIgnoreTests.cs +++ /dev/null @@ -1,151 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData.AssertIgnoreData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Assertions -{ - /// - /// Tests of IgnoreException and Assert.Ignore - /// - [TestFixture] - public class AssertIgnoreTests - { - [Test, ExpectedException(typeof(IgnoreException))] - public void ThrowsIgnoreException() - { - Assert.Ignore(); - } - - [Test, ExpectedException(typeof(IgnoreException), ExpectedMessage = "MESSAGE")] - public void ThrowsIgnoreExceptionWithMessage() - { - Assert.Ignore("MESSAGE"); - } - - [Test, ExpectedException(typeof(IgnoreException), ExpectedMessage = "MESSAGE: 2+2=4")] - public void ThrowsIgnoreExceptionWithMessageAndArgs() - { - Assert.Ignore("MESSAGE: {0}+{1}={2}", 2, 2, 4); - } - - [Test] - public void IgnoreWorksForTestCase() - { - Type fixtureType = typeof(IgnoredTestCaseFixture); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "CallsIgnore"); - Assert.AreEqual(ResultState.Ignored, result.ResultState); - Assert.AreEqual("Ignore me", result.Message); - } - - [Test] - public void IgnoreTakesPrecedenceOverExpectedException() - { - Type fixtureType = typeof(IgnoredTestCaseFixture); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "CallsIgnoreWithExpectedException"); - Assert.AreEqual(ResultState.Ignored, result.ResultState); - Assert.AreEqual("Ignore me", result.Message); - } - - [Test] - public void IgnoreWorksForTestSuite() - { - TestSuite suite = new TestSuite("IgnoredTestFixture"); - suite.Add(TestBuilder.MakeFixture(typeof(IgnoredTestSuiteFixture))); - ITestResult fixtureResult = (ITestResult)TestBuilder.RunTest(suite, null).Children[0]; - - Assert.AreEqual(ResultState.Ignored, fixtureResult.ResultState); - - foreach (ITestResult testResult in fixtureResult.Children) - Assert.AreEqual(ResultState.Ignored, testResult.ResultState); - } - - [Test] - public void IgnoreWorksFromSetUp() - { - ITestResult fixtureResult = TestBuilder.RunTestFixture(typeof(IgnoreInSetUpFixture)); - - // TODO: Decide how Ignored tests impact the containing suite result - //Assert.AreEqual(ResultState.Ignored, fixtureResult.ResultState); - - foreach (TestResult testResult in fixtureResult.Children) - Assert.AreEqual(ResultState.Ignored, testResult.ResultState); - } - - [Test] - public void IgnoreWithUserMessage() - { - try - { - Assert.Ignore("my message"); - } - catch (IgnoreException ex) - { - Assert.AreEqual("my message", ex.Message); - } - } - - [Test] - public void IgnoreWithUserMessage_OneArg() - { - try - { - Assert.Ignore("The number is {0}", 5); - } - catch (IgnoreException ex) - { - Assert.AreEqual("The number is 5", ex.Message); - } - } - - [Test] - public void IgnoreWithUserMessage_ThreeArgs() - { - try - { - Assert.Ignore("The numbers are {0}, {1} and {2}", 1, 2, 3); - } - catch (IgnoreException ex) - { - Assert.AreEqual("The numbers are 1, 2 and 3", ex.Message); - } - } - - [Test] - public void IgnoreWithUserMessage_ArrayOfArgs() - { - try - { - Assert.Ignore("The numbers are {0}, {1} and {2}", new object[] { 1, 2, 3 }); - } - catch (IgnoreException ex) - { - Assert.AreEqual("The numbers are 1, 2 and 3", ex.Message); - } - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssertInconclusiveTests.cs b/test/NUnitLite/src/tests/Assertions/AssertInconclusiveTests.cs deleted file mode 100644 index 155d79946..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssertInconclusiveTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AssertInconclusiveTests - { - [Test, ExpectedException(typeof(InconclusiveException))] - public void ThrowsInconclusiveException() - { - Assert.Inconclusive(); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage = "MESSAGE")] - public void ThrowsInconclusiveExceptionWithMessage() - { - Assert.Inconclusive("MESSAGE"); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage = "MESSAGE: 2+2=4")] - public void ThrowsInconclusiveExceptionWithMessageAndArgs() - { - Assert.Inconclusive("MESSAGE: {0}+{1}={2}", 2, 2, 4); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssertPassTests.cs b/test/NUnitLite/src/tests/Assertions/AssertPassTests.cs deleted file mode 100644 index 2736940a5..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssertPassTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AssertPassTests - { - [Test, ExpectedException(typeof(SuccessException))] - public void ThrowsSuccessException() - { - Assert.Pass(); - } - - [Test, ExpectedException(typeof(SuccessException), ExpectedMessage = "MESSAGE")] - public void ThrowsSuccessExceptionWithMessage() - { - Assert.Pass("MESSAGE"); - } - - [Test, ExpectedException(typeof(SuccessException), ExpectedMessage = "MESSAGE: 2+2=4")] - public void ThrowsSuccessExceptionWithMessageAndArgs() - { - Assert.Pass("MESSAGE: {0}+{1}={2}", 2, 2, 4); - } - - [Test] - public void AssertPassReturnsSuccess() - { - Assert.Pass("This test is OK!"); - } - - [Test] - public void SubsequentFailureIsIrrelevant() - { - Assert.Pass("This test is OK!"); - Assert.Fail("No it's NOT!"); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssertThatTests.cs b/test/NUnitLite/src/tests/Assertions/AssertThatTests.cs deleted file mode 100644 index 517308e45..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssertThatTests.cs +++ /dev/null @@ -1,279 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Constraints; -using NUnit.Framework.Internal; -using NUnit.TestData; -using NUnit.TestUtilities; -#if NET_4_5 -using System.Threading.Tasks; -#endif - -#if CLR_2_0 || CLR_4_0 -using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate; -#else -using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate; -#endif - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AssertThatTests - { - [Test] - public void AssertionPasses_Boolean() - { - Assert.That(2 + 2 == 4); - } - - [Test] - public void AssertionPasses_BooleanWithMessage() - { - Assert.That(2 + 2 == 4, "Not Equal"); - } - - [Test] - public void AssertionPasses_BooleanWithMessageAndArgs() - { - Assert.That(2 + 2 == 4, "Not Equal to {0}", 4); - } - - [Test] - public void AssertionPasses_ActualAndConstraint() - { - Assert.That(2 + 2, Is.EqualTo(4)); - } - - [Test] - public void AssertionPasses_ActualAndConstraintWithMessage() - { - Assert.That(2 + 2, Is.EqualTo(4), "Should be 4"); - } - - [Test] - public void AssertionPasses_ActualAndConstraintWithMessageAndArgs() - { - Assert.That(2 + 2, Is.EqualTo(4), "Should be {0}", 4); - } - - [Test] - public void AssertionPasses_ReferenceAndConstraint() - { - bool value = true; - Assert.That(ref value, Is.True); - } - - [Test] - public void AssertionPasses_ReferenceAndConstraintWithMessage() - { - bool value = true; - Assert.That(ref value, Is.True, "Message"); - } - - [Test] - public void AssertionPasses_ReferenceAndConstraintWithMessageAndArgs() - { - bool value = true; - Assert.That(ref value, Is.True, "Message", 42); - } - - [Test] - public void AssertionPasses_DelegateAndConstraint() - { - Assert.That(new ActualValueDelegate(ReturnsFour), Is.EqualTo(4)); - } - - [Test] - public void AssertionPasses_DelegateAndConstraintWithMessage() - { - Assert.That(new ActualValueDelegate(ReturnsFour), Is.EqualTo(4), "Message"); - } - - [Test] - public void AssertionPasses_DelegateAndConstraintWithMessageAndArgs() - { - Assert.That(new ActualValueDelegate(ReturnsFour), Is.EqualTo(4), "Should be {0}", 4); - } - - private object ReturnsFour() - { - return 4; - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailureThrowsAssertionException_Boolean() - { - Assert.That(2 + 2 == 5); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "message", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_BooleanWithMessage() - { - Assert.That(2 + 2 == 5, "message"); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "got 5", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_BooleanWithMessageAndArgs() - { - Assert.That(2 + 2 == 5, "got {0}", 5); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailureThrowsAssertionException_ActualAndConstraint() - { - Assert.That(2 + 2, Is.EqualTo(5)); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "Error", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_ActualAndConstraintWithMessage() - { - Assert.That(2 + 2, Is.EqualTo(5), "Error"); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "Should be 5", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_ActualAndConstraintWithMessageAndArgs() - { - Assert.That(2 + 2, Is.EqualTo(5), "Should be {0}", 5); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailureThrowsAssertionException_ReferenceAndConstraint() - { - bool value = false; - Assert.That(ref value, Is.True); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "message", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_ReferenceAndConstraintWithMessage() - { - bool value = false; - Assert.That(ref value, Is.True, "message"); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "message is 42", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_ReferenceAndConstraintWithMessageAndArgs() - { - bool value = false; - Assert.That(ref value, Is.True, "message is {0}", 42); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailureThrowsAssertionException_DelegateAndConstraint() - { - Assert.That(new ActualValueDelegate(ReturnsFive), Is.EqualTo(4)); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "Error", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_DelegateAndConstraintWithMessage() - { - Assert.That(new ActualValueDelegate(ReturnsFive), Is.EqualTo(4), "Error"); - } - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "Should be 4", MatchType = MessageMatch.Contains)] - public void FailureThrowsAssertionException_DelegateAndConstraintWithMessageAndArgs() - { - Assert.That(new ActualValueDelegate(ReturnsFive), Is.EqualTo(4), "Should be {0}", 4); - } - - [Test] - public void AssertionsAreCountedCorrectly() - { - TestResult result = TestBuilder.RunTestFixture(typeof(AssertCountFixture)); - - int totalCount = 0; - foreach (TestResult childResult in result.Children) - { - int expectedCount = childResult.Name == "ThreeAsserts" ? 3 : 1; - Assert.That(childResult.AssertCount, Is.EqualTo(expectedCount), "Bad count for {0}", childResult.Name); - totalCount += expectedCount; - } - - Assert.That(result.AssertCount, Is.EqualTo(totalCount), "Fixture count is not correct"); - } - - private object ReturnsFive() - { - return 5; - } - -#if NET_4_5 - [Test] - public void AssertThatSuccess() - { - Assert.That(async () => await One(), Is.EqualTo(1)); - } - - [Test] - public void AssertThatFailure() - { - var exception = Assert.Throws(() => - Assert.That(async () => await One(), Is.EqualTo(2))); - } - - [Test] - public void AssertThatErrorTask() - { - var exception = Assert.Throws(() => - Assert.That(async () => await ThrowExceptionTask(), Is.EqualTo(1))); - - Assert.That(exception.StackTrace, Contains.Substring("ThrowExceptionTask")); - } - - [Test] - public void AssertThatErrorGenericTask() - { - var exception = Assert.Throws(() => - Assert.That(async () => await ThrowExceptionGenericTask(), Is.EqualTo(1))); - - Assert.That(exception.StackTrace, Contains.Substring("ThrowExceptionGenericTask")); - } - - [Test] - public void AssertThatErrorVoid() - { - var exception = Assert.Throws(() => - Assert.That(async () => { await ThrowExceptionGenericTask(); }, Is.EqualTo(1))); - - Assert.That(exception.StackTrace, Contains.Substring("ThrowExceptionGenericTask")); - } - - private static Task One() - { - return Task.Run(() => 1); - } - - private static async Task ThrowExceptionGenericTask() - { - await One(); - throw new InvalidOperationException(); - } - - private static async Task ThrowExceptionTask() - { - await One(); - throw new InvalidOperationException(); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssertThrowsTests.cs b/test/NUnitLite/src/tests/Assertions/AssertThrowsTests.cs deleted file mode 100644 index 222deedbc..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssertThrowsTests.cs +++ /dev/null @@ -1,164 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AssertThrowsTests - { - [Test] - public void CorrectExceptionThrown() - { - Assert.Throws(typeof(ArgumentException), new TestDelegate(TestDelegates.ThrowsArgumentException)); - -#if CLR_2_0 || CLR_4_0 - Assert.Throws(typeof(ArgumentException), TestDelegates.ThrowsArgumentException); - - Assert.Throws(typeof(ArgumentException), - delegate { throw new ArgumentException(); }); - - Assert.Throws( - delegate { throw new ArgumentException(); }); - Assert.Throws(TestDelegates.ThrowsArgumentException); - - // Without cast, delegate is ambiguous before C# 3.0. - Assert.That((TestDelegate)delegate { throw new ArgumentException(); }, - Throws.Exception.TypeOf() ); - //Assert.Throws( Is.TypeOf(typeof(ArgumentException)), - // delegate { throw new ArgumentException(); } ); -#endif - } - - [Test] - public void CorrectExceptionIsReturnedToMethod() - { - ArgumentException ex = Assert.Throws(typeof(ArgumentException), - new TestDelegate(TestDelegates.ThrowsArgumentException)) as ArgumentException; - - Assert.IsNotNull(ex, "No ArgumentException thrown"); - Assert.That(ex.Message, Is.StringStarting("myMessage")); -#if !NETCF && !SILVERLIGHT - Assert.That(ex.ParamName, Is.EqualTo("myParam")); -#endif - -#if CLR_2_0 || CLR_4_0 - ex = Assert.Throws( - delegate { throw new ArgumentException("myMessage", "myParam"); }) as ArgumentException; - - Assert.IsNotNull(ex, "No ArgumentException thrown"); - Assert.That(ex.Message, Is.StringStarting("myMessage")); -#if !NETCF && !SILVERLIGHT - Assert.That(ex.ParamName, Is.EqualTo("myParam")); -#endif - - ex = Assert.Throws(typeof(ArgumentException), - delegate { throw new ArgumentException("myMessage", "myParam"); } ) as ArgumentException; - - Assert.IsNotNull(ex, "No ArgumentException thrown"); - Assert.That(ex.Message, Is.StringStarting("myMessage")); -#if !NETCF && !SILVERLIGHT - Assert.That(ex.ParamName, Is.EqualTo("myParam")); -#endif - - ex = Assert.Throws(TestDelegates.ThrowsArgumentException) as ArgumentException; - - Assert.IsNotNull(ex, "No ArgumentException thrown"); - Assert.That(ex.Message, Is.StringStarting("myMessage")); -#if !NETCF && !SILVERLIGHT - Assert.That(ex.ParamName, Is.EqualTo("myParam")); -#endif -#endif - } - - [Test, ExpectedException(typeof(AssertionException))] - public void NoExceptionThrown() - { -#if CLR_2_0 || CLR_4_0 - ArgumentException ex = Assert.Throws(TestDelegates.ThrowsNothing); -#else - Exception ex = Assert.Throws(typeof(ArgumentException), new TestDelegate(TestDelegates.ThrowsNothing)); -#endif - Assert.That(ex.Message, Is.EqualTo( - " Expected: " + Env.NewLine + - " But was: null" + Env.NewLine)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void UnrelatedExceptionThrown() - { -#if CLR_2_0 || CLR_4_0 - ArgumentException ex = Assert.Throws(TestDelegates.ThrowsCustomException); -#else - ArgumentException ex = (ArgumentException)Assert.Throws(typeof(ArgumentException), new TestDelegate(TestDelegates.ThrowsCustomException)); -#endif - Assert.That(ex.Message, Is.StringStarting( - " Expected: " + Env.NewLine + - " But was: (my message)" + Env.NewLine)); - Assert.That(ex.Message, Contains.Substring(" at ")); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void BaseExceptionThrown() - { -#if CLR_2_0 || CLR_4_0 - ArgumentException ex = Assert.Throws(TestDelegates.ThrowsSystemException); -#else - Exception ex = Assert.Throws(typeof(ArgumentException), new TestDelegate(TestDelegates.ThrowsSystemException)); -#endif - Assert.That(ex.Message, Is.StringStarting( - " Expected: " + Env.NewLine + - " But was: (my message)" + Env.NewLine)); - Assert.That(ex.Message, Contains.Substring(" at ")); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void DerivedExceptionThrown() - { -#if CLR_2_0 || CLR_4_0 - Exception ex = Assert.Throws(TestDelegates.ThrowsArgumentException); -#else - Exception ex = Assert.Throws(typeof(Exception), new TestDelegate(TestDelegates.ThrowsArgumentException)); -#endif - Assert.That(ex.Message, Is.StringStarting( - " Expected: " + Env.NewLine + - " But was: (myMessage" + Env.NewLine + - "Parameter name: myParam)" + Env.NewLine)); - Assert.That(ex.Message, Contains.Substring(" at ")); - } - - [Test] - public void DoesNotThrowSuceeds() - { - Assert.DoesNotThrow(new TestDelegate(TestDelegates.ThrowsNothing)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void DoesNotThrowFails() - { - Assert.DoesNotThrow(new TestDelegate(TestDelegates.ThrowsArgumentException)); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AssumeThatTests.cs b/test/NUnitLite/src/tests/Assertions/AssumeThatTests.cs deleted file mode 100644 index 8b9efdd5f..000000000 --- a/test/NUnitLite/src/tests/Assertions/AssumeThatTests.cs +++ /dev/null @@ -1,236 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Constraints; -#if NET_4_5 -using System.Threading.Tasks; -#endif - -#if CLR_2_0 || CLR_4_0 -using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate; -#else -using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate; -#endif - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AssumeThatTests - { - [Test] - public void AssumptionPasses_Boolean() - { - Assume.That(2 + 2 == 4); - } - - [Test] - public void AssumptionPasses_BooleanWithMessage() - { - Assume.That(2 + 2 == 4, "Not Equal"); - } - - [Test] - public void AssumptionPasses_BooleanWithMessageAndArgs() - { - Assume.That(2 + 2 == 4, "Not Equal to {0}", 4); - } - - [Test] - public void AssumptionPasses_ActualAndConstraint() - { - Assume.That(2 + 2, Is.EqualTo(4)); - } - - [Test] - public void AssumptionPasses_ActualAndConstraintWithMessage() - { - Assume.That(2 + 2, Is.EqualTo(4), "Should be 4"); - } - - [Test] - public void AssumptionPasses_ActualAndConstraintWithMessageAndArgs() - { - Assume.That(2 + 2, Is.EqualTo(4), "Should be {0}", 4); - } - - [Test] - public void AssumptionPasses_ReferenceAndConstraint() - { - bool value = true; - Assume.That(ref value, Is.True); - } - - [Test] - public void AssumptionPasses_ReferenceAndConstraintWithMessage() - { - bool value = true; - Assume.That(ref value, Is.True, "Message"); - } - - [Test] - public void AssumptionPasses_ReferenceAndConstraintWithMessageAndArgs() - { - bool value = true; - Assume.That(ref value, Is.True, "Message", 42); - } - - [Test] - public void AssumptionPasses_DelegateAndConstraint() - { - Assume.That(new ActualValueDelegate(ReturnsFour), Is.EqualTo(4)); - } - - [Test] - public void AssumptionPasses_DelegateAndConstraintWithMessage() - { - Assume.That(new ActualValueDelegate(ReturnsFour), Is.EqualTo(4), "Message"); - } - - [Test] - public void AssumptionPasses_DelegateAndConstraintWithMessageAndArgs() - { - Assume.That(new ActualValueDelegate(ReturnsFour), Is.EqualTo(4), "Should be {0}", 4); - } - - private object ReturnsFour() - { - return 4; - } - - [Test, ExpectedException(typeof(InconclusiveException))] - public void FailureThrowsInconclusiveException_Boolean() - { - Assume.That(2 + 2 == 5); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage="message", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_BooleanWithMessage() - { - Assume.That(2 + 2 == 5, "message"); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage= "got 5", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_BooleanWithMessageAndArgs() - { - Assume.That(2 + 2 == 5, "got {0}", 5); - } - - [Test, ExpectedException(typeof(InconclusiveException))] - public void FailureThrowsInconclusiveException_ActualAndConstraint() - { - Assume.That(2 + 2, Is.EqualTo(5)); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage="Error", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_ActualAndConstraintWithMessage() - { - Assume.That(2 + 2, Is.EqualTo(5), "Error"); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage="Should be 5", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_ActualAndConstraintWithMessageAndArgs() - { - Assume.That(2 + 2, Is.EqualTo(5), "Should be {0}", 5); - } - - [Test, ExpectedException(typeof(InconclusiveException))] - public void FailureThrowsInconclusiveException_ReferenceAndConstraint() - { - bool value = false; - Assume.That(ref value, Is.True); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage="message", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_ReferenceAndConstraintWithMessage() - { - bool value = false; - Assume.That(ref value, Is.True, "message"); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage="message is 42", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_ReferenceAndConstraintWithMessageAndArgs() - { - bool value = false; - Assume.That(ref value, Is.True, "message is {0}", 42); - } - - [Test, ExpectedException(typeof(InconclusiveException))] - public void FailureThrowsInconclusiveException_DelegateAndConstraint() - { - Assume.That(new ActualValueDelegate(ReturnsFive), Is.EqualTo(4)); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage = "Error", MatchType = MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_DelegateAndConstraintWithMessage() - { - Assume.That(new ActualValueDelegate(ReturnsFive), Is.EqualTo(4), "Error"); - } - - [Test, ExpectedException(typeof(InconclusiveException), ExpectedMessage="Should be 4", MatchType=MessageMatch.Contains)] - public void FailureThrowsInconclusiveException_DelegateAndConstraintWithMessageAndArgs() - { - Assume.That(new ActualValueDelegate(ReturnsFive), Is.EqualTo(4), "Should be {0}", 4); - } - - private object ReturnsFive() - { - return 5; - } - -#if NET_4_5 - [Test] - public void AssumeThatSuccess() - { - Assume.That(async () => await One(), Is.EqualTo(1)); - } - - [Test] - public void AssumeThatFailure() - { - var exception = Assert.Throws(() => - Assume.That(async () => await One(), Is.EqualTo(2))); - } - - [Test] - public void AssumeThatError() - { - var exception = Assert.Throws(() => - Assume.That(async () => await ThrowExceptionGenericTask(), Is.EqualTo(1))); - - Assert.That(exception.StackTrace, Contains.Substring("ThrowExceptionGenericTask")); - } - - private static Task One() - { - return Task.Run(() => 1); - } - - private static async Task ThrowExceptionGenericTask() - { - await One(); - throw new InvalidOperationException(); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Assertions/AsyncThrowsTests.cs b/test/NUnitLite/src/tests/Assertions/AsyncThrowsTests.cs deleted file mode 100644 index c194df8bd..000000000 --- a/test/NUnitLite/src/tests/Assertions/AsyncThrowsTests.cs +++ /dev/null @@ -1,185 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if NET_4_5 -using System; -using System.Threading.Tasks; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class AsyncThrowsTests - { - private readonly TestDelegate _noThrowsVoid = new TestDelegate(async () => await Task.Yield()); - private readonly ActualValueDelegate _noThrowsAsyncTask = async () => await Task.Yield(); - private readonly ActualValueDelegate> _noThrowsAsyncGenericTask = async () => await ReturnOne(); - private readonly TestDelegate _throwsAsyncVoid = new TestDelegate(async () => await ThrowAsyncTask()); - private readonly TestDelegate _throwsSyncVoid = new TestDelegate(async () => { throw new InvalidOperationException(); }); - private readonly ActualValueDelegate _throwsAsyncTask = async () => await ThrowAsyncTask(); - private readonly ActualValueDelegate> _throwsAsyncGenericTask = async () => await ThrowAsyncGenericTask(); - - private static ThrowsConstraint ThrowsInvalidOperationExceptionConstraint - { - get { return new ThrowsConstraint(new ExactTypeConstraint(typeof(InvalidOperationException))); } - } - - [Test] - public void ThrowsConstraintVoid() - { - Assert.IsTrue(ThrowsInvalidOperationExceptionConstraint.Matches(_throwsAsyncVoid)); - } - - [Test] - public void ThrowsConstraintVoidRunSynchronously() - { - Assert.IsTrue(ThrowsInvalidOperationExceptionConstraint.Matches(_throwsSyncVoid)); - } - - [Test] - public void ThrowsConstraintAsyncTask() - { - Assert.IsTrue(ThrowsInvalidOperationExceptionConstraint.Matches(_throwsAsyncTask)); - } - - [Test] - public void ThrowsConstraintAsyncGenericTask() - { - Assert.IsTrue(ThrowsInvalidOperationExceptionConstraint.Matches(_throwsAsyncGenericTask)); - } - - [Test] - public void ThrowsNothingConstraintVoidSuccess() - { - Assert.IsTrue(new ThrowsNothingConstraint().Matches(_noThrowsVoid)); - } - - [Test] - public void ThrowsNothingConstraintVoidFailure() - { - Assert.IsFalse(new ThrowsNothingConstraint().Matches(_throwsAsyncVoid)); - } - - [Test] - public void ThrowsNothingConstraintTaskVoidSuccess() - { - Assert.IsTrue(new ThrowsNothingConstraint().Matches(_noThrowsAsyncTask)); - } - - [Test] - public void ThrowsNothingConstraintTaskFailure() - { - Assert.IsFalse(new ThrowsNothingConstraint().Matches(_throwsAsyncTask)); - } - - [Test] - public void AssertThrowsVoid() - { - Assert.Throws(typeof(InvalidOperationException), _throwsAsyncVoid); - } - - [Test] - public void AssertThatThrowsVoid() - { - Assert.That(_throwsAsyncVoid, Throws.TypeOf()); - } - - [Test] - public void AssertThatThrowsTask() - { - Assert.That(_throwsAsyncTask, Throws.TypeOf()); - } - - [Test] - public void AssertThatThrowsGenericTask() - { - Assert.That(_throwsAsyncGenericTask, Throws.TypeOf()); - } - - [Test] - public void AssertThatThrowsNothingVoidSuccess() - { - Assert.That(_noThrowsVoid, Throws.Nothing); - } - - [Test] - public void AssertThatThrowsNothingTaskSuccess() - { - Assert.That(_noThrowsAsyncTask, Throws.Nothing); - } - - [Test] - public void AssertThatThrowsNothingGenericTaskSuccess() - { - Assert.That(_noThrowsAsyncGenericTask, Throws.Nothing); - } - - [Test] - public void AssertThatThrowsNothingVoidFailure() - { - Assert.Throws(() => Assert.That(_throwsAsyncVoid, Throws.Nothing)); - } - - [Test] - public void AssertThatThrowsNothingTaskFailure() - { - Assert.Throws(() => Assert.That(_throwsAsyncTask, Throws.Nothing)); - } - - [Test] - public void AssertThatThrowsNothingGenericTaskFailure() - { - Assert.Throws(() => Assert.That(_throwsAsyncGenericTask, Throws.Nothing)); - } - - [Test] - public void AssertThrowsAsync() - { - Assert.Throws(_throwsAsyncVoid); - } - - [Test] - public void AssertThrowsSync() - { - Assert.Throws(_throwsSyncVoid); - } - - private static async Task ThrowAsyncTask() - { - await ReturnOne(); - throw new InvalidOperationException(); - } - - private static async Task ThrowAsyncGenericTask() - { - await ThrowAsyncTask(); - return await ReturnOne(); - } - - private static Task ReturnOne() - { - return Task.Run(() => 1); - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Assertions/CollectionTests.cs b/test/NUnitLite/src/tests/Assertions/CollectionTests.cs deleted file mode 100644 index d8a6ad2da..000000000 --- a/test/NUnitLite/src/tests/Assertions/CollectionTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using System.Collections; -using NUnit.Framework; -using NUnit.Framework.Internal; -using Env = NUnit.Env; -using NUnit.TestUtilities; - -namespace NUnitLite.Tests -{ - [TestFixture] - class CollectionTests : IExpectException - { - [Test] - public void CanMatchTwoCollections() - { - ICollection expected = new SimpleObjectCollection(1, 2, 3); - ICollection actual = new SimpleObjectCollection(1, 2, 3); - - Assert.That(actual, Is.EqualTo(expected)); - } - - [Test] - public void CanMatchAnArrayWithACollection() - { - ICollection collection = new SimpleObjectCollection(1, 2, 3); - int[] array = new int[] { 1, 2, 3 }; - - Assert.That(collection, Is.EqualTo(array)); - Assert.That(array, Is.EqualTo(collection)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailureMatchingArrayAndCollection() - { - int[] expected = new int[] { 1, 2, 3 }; - ICollection actual = new SimpleObjectCollection(1, 5, 3); - - Assert.That(actual, Is.EqualTo(expected)); - } - - public void HandleException(Exception ex) - { - Assert.That(ex.Message, Is.EqualTo( - " Expected is , actual is with 3 elements" + Env.NewLine + - " Values differ at index [1]" + Env.NewLine + - TextMessageWriter.Pfx_Expected + "2" + Env.NewLine + - TextMessageWriter.Pfx_Actual + "5" + Env.NewLine)); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/ConditionAssertTests.cs b/test/NUnitLite/src/tests/Assertions/ConditionAssertTests.cs deleted file mode 100644 index 876746ea5..000000000 --- a/test/NUnitLite/src/tests/Assertions/ConditionAssertTests.cs +++ /dev/null @@ -1,224 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using System.Threading; -using System.Globalization; -using NUnit.Framework; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class ConditionAssertTests : MessageChecker - { - [Test] - public void IsTrue() - { - Assert.IsTrue(true); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void IsTrueFails() - { - expectedMessage = - " Expected: True" + Env.NewLine + - " But was: False" + Env.NewLine; - Assert.IsTrue(false); - } - - [Test] - public void IsFalse() - { - Assert.IsFalse(false); - } - - [Test] - [ExpectedException(typeof(AssertionException))] - public void IsFalseFails() - { - expectedMessage = - " Expected: False" + Env.NewLine + - " But was: True" + Env.NewLine; - Assert.IsFalse(true); - } - - [Test] - public void IsNull() - { - Assert.IsNull(null); - } - - [Test] - [ExpectedException(typeof(AssertionException))] - public void IsNullFails() - { - String s1 = "S1"; - expectedMessage = - " Expected: null" + Env.NewLine + - " But was: \"S1\"" + Env.NewLine; - Assert.IsNull(s1); - } - - [Test] - public void IsNotNull() - { - String s1 = "S1"; - Assert.IsNotNull(s1); - } - - [Test] - [ExpectedException(typeof(AssertionException))] - public void IsNotNullFails() - { - expectedMessage = - " Expected: not null" + Env.NewLine + - " But was: null" + Env.NewLine; - Assert.IsNotNull(null); - } - -#if !NUNITLITE - [Test] - public void IsNaN() - { - Assert.IsNaN(double.NaN); - } - - [Test] - [ExpectedException(typeof(AssertionException))] - public void IsNaNFails() - { - expectedMessage = - " Expected: NaN" + Env.NewLine + - " But was: 10.0d" + Env.NewLine; - Assert.IsNaN(10.0); - } - - [Test] - public void IsEmpty() - { - Assert.IsEmpty( "", "Failed on empty String" ); - Assert.IsEmpty( new int[0], "Failed on empty Array" ); - Assert.IsEmpty( new ArrayList(), "Failed on empty ArrayList" ); - Assert.IsEmpty( new Hashtable(), "Failed on empty Hashtable" ); - Assert.IsEmpty( (IEnumerable)new int[0], "Failed on empty IEnumerable" ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsEmptyFailsOnString() - { - expectedMessage = - " Expected: " + Env.NewLine + - " But was: \"Hi!\"" + Env.NewLine; - Assert.IsEmpty( "Hi!" ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsEmptyFailsOnNullString() - { - expectedMessage = - " Expected: " + Env.NewLine + - " But was: null" + Env.NewLine; - Assert.IsEmpty( (string)null ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsEmptyFailsOnNonEmptyArray() - { - expectedMessage = - " Expected: " + Env.NewLine + - " But was: < 1, 2, 3 >" + Env.NewLine; - Assert.IsEmpty( new int[] { 1, 2, 3 } ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsEmptyFailsOnNonEmptyIEnumerable() - { - expectedMessage = - " Expected: " + Environment.NewLine + - " But was: < 1, 2, 3 >" + Environment.NewLine; - Assert.IsEmpty((IEnumerable)new int[] { 1, 2, 3 }); - } - - [Test] - public void IsNotEmpty() - { - int[] array = new int[] { 1, 2, 3 }; - ArrayList list = new ArrayList( array ); - Hashtable hash = new Hashtable(); - hash.Add( "array", array ); - - Assert.IsNotEmpty( "Hi!", "Failed on String" ); - Assert.IsNotEmpty( array, "Failed on Array" ); - Assert.IsNotEmpty( list, "Failed on ArrayList" ); - Assert.IsNotEmpty( hash, "Failed on Hashtable" ); - Assert.IsNotEmpty( (IEnumerable)array, "Failed on IEnumerable" ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsNotEmptyFailsOnEmptyString() - { - expectedMessage = - " Expected: not " + Env.NewLine + - " But was: " + Env.NewLine; - Assert.IsNotEmpty( "" ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsNotEmptyFailsOnEmptyArray() - { - expectedMessage = - " Expected: not " + Env.NewLine + - " But was: " + Env.NewLine; - Assert.IsNotEmpty( new int[0] ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsNotEmptyFailsOnEmptyArrayList() - { - expectedMessage = - " Expected: not " + Env.NewLine + - " But was: " + Env.NewLine; - Assert.IsNotEmpty( new ArrayList() ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsNotEmptyFailsOnEmptyHashTable() - { - expectedMessage = - " Expected: not " + Env.NewLine + - " But was: " + Env.NewLine; - Assert.IsNotEmpty( new Hashtable() ); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsNotEmptyFailsOnEmptyIEnumerable() - { - expectedMessage = - " Expected: not " + Environment.NewLine + - " But was: " + Environment.NewLine; - Assert.IsNotEmpty((IEnumerable)new int[0]); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Assertions/EqualsFixture.cs b/test/NUnitLite/src/tests/Assertions/EqualsFixture.cs deleted file mode 100644 index 6681126ad..000000000 --- a/test/NUnitLite/src/tests/Assertions/EqualsFixture.cs +++ /dev/null @@ -1,568 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2004 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Globalization; -using System.Threading; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class EqualsFixture : MessageChecker - { - [Test] - public void Equals() - { - string nunitString = "Hello NUnit"; - string expected = nunitString; - string actual = nunitString; - - Assert.IsTrue(expected == actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void EqualsNull() - { - Assert.AreEqual(null, null); - } - - [Test] - public void Bug575936Int32Int64Comparison() - { - long l64 = 0; - int i32 = 0; - Assert.AreEqual(i32, l64); - } - - [Test] - public void IntegerLongComparison() - { - Assert.AreEqual(1, 1L); - Assert.AreEqual(1L, 1); - } - - [Test] - public void IntegerEquals() - { - int val = 42; - Assert.AreEqual(val, 42); - } - - - [Test,ExpectedException(typeof(AssertionException))] - public void EqualsFail() - { - string junitString = "Goodbye JUnit"; - string expected = "Hello NUnit"; - - expectedMessage = - " Expected string length 11 but was 13. Strings differ at index 0." + Env.NewLine + - " Expected: \"Hello NUnit\"" + Env.NewLine + - " But was: \"Goodbye JUnit\"" + Env.NewLine + - " -----------^" + Env.NewLine; - Assert.AreEqual(expected, junitString); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void EqualsNaNFails() - { - expectedMessage = - " Expected: 1.234d +/- 0.0d" + Env.NewLine + - " But was: NaN" + Env.NewLine; - Assert.AreEqual(1.234, Double.NaN, 0.0); - } - - - [Test] - [ExpectedException(typeof(AssertionException))] - public void NanEqualsFails() - { - expectedMessage = - " Expected: NaN" + Env.NewLine + - " But was: 1.234d" + Env.NewLine; - Assert.AreEqual(Double.NaN, 1.234, 0.0); - } - - [Test] - public void NanEqualsNaNSucceeds() - { - Assert.AreEqual(Double.NaN, Double.NaN, 0.0); - } - - [Test] - public void NegInfinityEqualsInfinity() - { - Assert.AreEqual(Double.NegativeInfinity, Double.NegativeInfinity, 0.0); - } - - [Test] - public void PosInfinityEqualsInfinity() - { - Assert.AreEqual(Double.PositiveInfinity, Double.PositiveInfinity, 0.0); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void PosInfinityNotEquals() - { - expectedMessage = - " Expected: Infinity" + Env.NewLine + - " But was: 1.23d" + Env.NewLine; - Assert.AreEqual(Double.PositiveInfinity, 1.23, 0.0); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void PosInfinityNotEqualsNegInfinity() - { - expectedMessage = - " Expected: Infinity" + Env.NewLine + - " But was: -Infinity" + Env.NewLine; - Assert.AreEqual(Double.PositiveInfinity, Double.NegativeInfinity, 0.0); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void SinglePosInfinityNotEqualsNegInfinity() - { - expectedMessage = - " Expected: Infinity" + Env.NewLine + - " But was: -Infinity" + Env.NewLine; - Assert.AreEqual(float.PositiveInfinity, float.NegativeInfinity, (float)0.0); - } - -#if !NETCF - [Test,ExpectedException(typeof(InvalidOperationException))] - public void EqualsThrowsException() - { - object o = new object(); - Assert.Equals(o, o); - } - - [Test,ExpectedException(typeof(InvalidOperationException))] - public void ReferenceEqualsThrowsException() - { - object o = new object(); - Assert.ReferenceEquals(o, o); - } -#endif - - [Test] - public void Float() - { - float val = (float)1.0; - float expected = val; - float actual = val; - - Assert.IsTrue(expected == actual); - Assert.AreEqual(expected, actual, (float)0.0); - } - - [Test] - public void Byte() - { - byte val = 1; - byte expected = val; - byte actual = val; - - Assert.IsTrue(expected == actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void String() - { - string s1 = "test"; - string s2 = new System.Text.StringBuilder(s1).ToString(); - - Assert.IsTrue(s1.Equals(s2)); - Assert.AreEqual(s1,s2); - } - - [Test] - public void Short() - { - short val = 1; - short expected = val; - short actual = val; - - Assert.IsTrue(expected == actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void Int() - { - int val = 1; - int expected = val; - int actual = val; - - Assert.IsTrue(expected == actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void UInt() - { - uint val = 1; - uint expected = val; - uint actual = val; - - Assert.IsTrue(expected == actual); - Assert.AreEqual(expected, actual); - } - - [Test] - public void Decimal() - { - decimal expected = 100m; - decimal actual = 100.0m; - int integer = 100; - - Assert.IsTrue( expected == actual ); - Assert.AreEqual(expected, actual); - Assert.IsTrue(expected == integer); - Assert.AreEqual(expected, integer); - Assert.IsTrue(actual == integer); - Assert.AreEqual(actual, integer); - } - - - - /// - /// Checks to see that a value comparison works with all types. - /// Current version has problems when value is the same but the - /// types are different...C# is not like Java, and doesn't automatically - /// perform value type conversion to simplify this type of comparison. - /// - /// Related to Bug575936Int32Int64Comparison, but covers all numeric - /// types. - /// - [Test] - public void EqualsSameTypes() - { - byte b1 = 35; - sbyte sb2 = 35; - decimal d4 = 35; - double d5 = 35; - float f6 = 35; - int i7 = 35; - uint u8 = 35; - long l9 = 35; - short s10 = 35; - ushort us11 = 35; - - System.Byte b12 = 35; - System.SByte sb13 = 35; - System.Decimal d14 = 35; - System.Double d15 = 35; - System.Single s16 = 35; - System.Int32 i17 = 35; - System.UInt32 ui18 = 35; - System.Int64 i19 = 35; - System.UInt64 ui20 = 35; - System.Int16 i21 = 35; - System.UInt16 i22 = 35; - - Assert.AreEqual(35, b1); - Assert.AreEqual(35, sb2); - Assert.AreEqual(35, d4); - Assert.AreEqual(35, d5); - Assert.AreEqual(35, f6); - Assert.AreEqual(35, i7); - Assert.AreEqual(35, u8); - Assert.AreEqual(35, l9); - Assert.AreEqual(35, s10); - Assert.AreEqual(35, us11); - - Assert.AreEqual( 35, b12 ); - Assert.AreEqual( 35, sb13 ); - Assert.AreEqual( 35, d14 ); - Assert.AreEqual( 35, d15 ); - Assert.AreEqual( 35, s16 ); - Assert.AreEqual( 35, i17 ); - Assert.AreEqual( 35, ui18 ); - Assert.AreEqual( 35, i19 ); - Assert.AreEqual( 35, ui20 ); - Assert.AreEqual( 35, i21 ); - Assert.AreEqual( 35, i22 ); - -#if CLR_2_0 || CLR_4_0 - byte? b23 = 35; - sbyte? sb24 = 35; - decimal? d25 = 35; - double? d26 = 35; - float? f27 = 35; - int? i28 = 35; - uint? u29 = 35; - long? l30 = 35; - short? s31 = 35; - ushort? us32 = 35; - - Assert.AreEqual(35, b23); - Assert.AreEqual(35, sb24); - Assert.AreEqual(35, d25); - Assert.AreEqual(35, d26); - Assert.AreEqual(35, f27); - Assert.AreEqual(35, i28); - Assert.AreEqual(35, u29); - Assert.AreEqual(35, l30); - Assert.AreEqual(35, s31); - Assert.AreEqual(35, us32); -#endif - } - - [Test] - public void EnumsEqual() - { - MyEnum actual = MyEnum.a; - Assert.AreEqual( MyEnum.a, actual ); - } - - [Test, ExpectedException( typeof(AssertionException) )] - public void EnumsNotEqual() - { - MyEnum actual = MyEnum.a; - expectedMessage = - " Expected: c" + Env.NewLine + - " But was: a" + Env.NewLine; - Assert.AreEqual( MyEnum.c, actual ); - } - - [Test] - public void DateTimeEqual() - { - DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 ); - DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ) + TimeSpan.FromHours( 7.0 ); - Assert.AreEqual( dt1, dt2 ); - } - - [Test, ExpectedException( typeof (AssertionException) )] - public void DateTimeNotEqual() - { - DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 ); - DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ); - expectedMessage = - " Expected: 2005-06-01 07:00:00.000" + Env.NewLine + - " But was: 2005-06-01 00:00:00.000" + Env.NewLine; - Assert.AreEqual(dt1, dt2); - } - - private enum MyEnum - { - a, b, c - } - - [Test] - public void DoubleNotEqualMessageDisplaysAllDigits() - { - string message = ""; - - try - { - double d1 = 36.1; - double d2 = 36.099999999999994; - Assert.AreEqual( d1, d2 ); - } - catch(AssertionException ex) - { - message = ex.Message; - } - - if ( message == "" ) - Assert.Fail( "Should have thrown an AssertionException" ); - - int i = message.IndexOf('3'); - int j = message.IndexOf( 'd', i ); - string expected = message.Substring( i, j - i + 1 ); - i = message.IndexOf( '3', j ); - j = message.IndexOf( 'd', i ); - string actual = message.Substring( i , j - i + 1 ); - Assert.AreNotEqual( expected, actual ); - } - - [Test] - public void FloatNotEqualMessageDisplaysAllDigits() - { - string message = ""; - - try - { - float f1 = 36.125F; - float f2 = 36.125004F; - Assert.AreEqual( f1, f2 ); - } - catch(AssertionException ex) - { - message = ex.Message; - } - - if ( message == "" ) - Assert.Fail( "Should have thrown an AssertionException" ); - - int i = message.IndexOf( '3' ); - int j = message.IndexOf( 'f', i ); - string expected = message.Substring( i, j - i + 1 ); - i = message.IndexOf( '3', j ); - j = message.IndexOf( 'f', i ); - string actual = message.Substring( i, j - i + 1 ); - Assert.AreNotEqual( expected, actual ); - } - - [Test] - public void DoubleNotEqualMessageDisplaysTolerance() - { - string message = ""; - - try - { - double d1 = 0.15; - double d2 = 0.12; - double tol = 0.005; - Assert.AreEqual(d1, d2, tol); - } - catch (AssertionException ex) - { - message = ex.Message; - } - - if (message == "") - Assert.Fail("Should have thrown an AssertionException"); - - Assert.That(message, Contains.Substring("+/- 0.005")); - } - - [Test] - public void FloatNotEqualMessageDisplaysTolerance() - { - string message = ""; - - try - { - float f1 = 0.15F; - float f2 = 0.12F; - float tol = 0.001F; - Assert.AreEqual( f1, f2, tol ); - } - catch( AssertionException ex ) - { - message = ex.Message; - } - - if ( message == "" ) - Assert.Fail( "Should have thrown an AssertionException" ); - - Assert.That(message, Contains.Substring( "+/- 0.001")); - } - - [Test] - public void DoubleNotEqualMessageDisplaysDefaultTolerance() - { - string message = ""; - GlobalSettings.DefaultFloatingPointTolerance = 0.005d; - - try - { - double d1 = 0.15; - double d2 = 0.12; - Assert.AreEqual(d1, d2); - } - catch (AssertionException ex) - { - message = ex.Message; - } - finally - { - GlobalSettings.DefaultFloatingPointTolerance = 0.0d; - } - - if (message == "") - Assert.Fail("Should have thrown an AssertionException"); - - Assert.That(message, Contains.Substring("+/- 0.005")); - } - - [Test] - public void DoubleNotEqualWithNanDoesNotDisplayDefaultTolerance() - { - string message = ""; - GlobalSettings.DefaultFloatingPointTolerance = 0.005d; - - try - { - double d1 = double.NaN; - double d2 = 0.12; - Assert.AreEqual(d1, d2); - } - catch (AssertionException ex) - { - message = ex.Message; - } - finally - { - GlobalSettings.DefaultFloatingPointTolerance = 0.0d; - } - - if (message == "") - Assert.Fail("Should have thrown an AssertionException"); - - Assert.That(message.IndexOf("+/-") == -1); - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF - [Test] - public void IEquatableSuccess_OldSyntax() - { - IntEquatable a = new IntEquatable(1); - - Assert.AreEqual(1, a); - Assert.AreEqual(a, 1); - } - - [Test] - public void IEquatableSuccess_ConstraintSyntax() - { - IntEquatable a = new IntEquatable(1); - - Assert.That(a, Is.EqualTo(1)); - Assert.That(1, Is.EqualTo(a)); - } -#endif - } - -#if CLR_2_0 || CLR_4_0 - public class IntEquatable : IEquatable - { - private int i; - - public IntEquatable(int i) - { - this.i = i; - } - - public bool Equals(int other) - { - return i.Equals(other); - } - } -#endif -} - diff --git a/test/NUnitLite/src/tests/Assertions/MessageChecker.cs b/test/NUnitLite/src/tests/Assertions/MessageChecker.cs deleted file mode 100644 index dc8cf05d6..000000000 --- a/test/NUnitLite/src/tests/Assertions/MessageChecker.cs +++ /dev/null @@ -1,70 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Assertions -{ - /// - /// MessageCheckingTest is an abstract base for tests - /// that check for an expected message in the exception - /// handler. - /// - public abstract class MessageChecker : IExpectException - { - protected string expectedMessage; - protected MessageMatch matchType = MessageMatch.Exact; - protected readonly string NL = NUnit.Env.NewLine; - - [SetUp] - public void SetUp() - { - expectedMessage = null; - } - - public void HandleException( Exception ex ) - { - if ( expectedMessage != null ) - { - switch(matchType) - { - default: - case MessageMatch.Exact: - Assert.AreEqual( expectedMessage, ex.Message ); - break; - case MessageMatch.Contains: - Assert.That(ex.Message, Is.StringContaining(expectedMessage)); - break; - case MessageMatch.StartsWith: - Assert.That(ex.Message, Is.StringStarting(expectedMessage)); - break; -#if !NETCF - case MessageMatch.Regex: - Assert.That(ex.Message, Is.StringMatching(expectedMessage)); - break; -#endif - } - } - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/NotEqualFixture.cs b/test/NUnitLite/src/tests/Assertions/NotEqualFixture.cs deleted file mode 100644 index 72c67c8bf..000000000 --- a/test/NUnitLite/src/tests/Assertions/NotEqualFixture.cs +++ /dev/null @@ -1,134 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class NotEqualFixture : MessageChecker - { - [Test] - public void NotEqual() - { - Assert.AreNotEqual( 5, 3 ); - } - - [Test, ExpectedException( typeof( AssertionException ) )] - public void NotEqualFails() - { - expectedMessage = - " Expected: not 5" + Env.NewLine + - " But was: 5" + Env.NewLine; - Assert.AreNotEqual( 5, 5 ); - } - - [Test] - public void NullNotEqualToNonNull() - { - Assert.AreNotEqual( null, 3 ); - } - - [Test, ExpectedException( typeof( AssertionException ) )] - public void NullEqualsNull() - { - expectedMessage = - " Expected: not null" + Env.NewLine + - " But was: null" + Env.NewLine; - Assert.AreNotEqual( null, null ); - } - - [Test] - public void ArraysNotEqual() - { - Assert.AreNotEqual( new object[] { 1, 2, 3 }, new object[] { 1, 3, 2 } ); - } - - [Test, ExpectedException( typeof( AssertionException ) )] - public void ArraysNotEqualFails() - { - expectedMessage = - " Expected: not < 1, 2, 3 >" + Env.NewLine + - " But was: < 1, 2, 3 >" + Env.NewLine; - Assert.AreNotEqual( new object[] { 1, 2, 3 }, new object[] { 1, 2, 3 } ); - } - - [Test] - public void UInt() - { - uint u1 = 5; - uint u2 = 8; - Assert.AreNotEqual( u1, u2 ); - } - - [Test] - public void NotEqualSameTypes() - { - byte b1 = 35; - sbyte sb2 = 35; - decimal d4 = 35; - double d5 = 35; - float f6 = 35; - int i7 = 35; - uint u8 = 35; - long l9 = 35; - short s10 = 35; - ushort us11 = 35; - - System.Byte b12 = 35; - System.SByte sb13 = 35; - System.Decimal d14 = 35; - System.Double d15 = 35; - System.Single s16 = 35; - System.Int32 i17 = 35; - System.UInt32 ui18 = 35; - System.Int64 i19 = 35; - System.UInt64 ui20 = 35; - System.Int16 i21 = 35; - System.UInt16 i22 = 35; - - Assert.AreNotEqual(23, b1); - Assert.AreNotEqual(23, sb2); - Assert.AreNotEqual(23, d4); - Assert.AreNotEqual(23, d5); - Assert.AreNotEqual(23, f6); - Assert.AreNotEqual(23, i7); - Assert.AreNotEqual(23, u8); - Assert.AreNotEqual(23, l9); - Assert.AreNotEqual(23, s10); - Assert.AreNotEqual(23, us11); - - Assert.AreNotEqual(23, b12); - Assert.AreNotEqual(23, sb13); - Assert.AreNotEqual(23, d14); - Assert.AreNotEqual(23, d15); - Assert.AreNotEqual(23, s16); - Assert.AreNotEqual(23, i17); - Assert.AreNotEqual(23, ui18); - Assert.AreNotEqual(23, i19); - Assert.AreNotEqual(23, ui20); - Assert.AreNotEqual(23, i21); - Assert.AreNotEqual(23, i22); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Assertions/NotSameFixture.cs b/test/NUnitLite/src/tests/Assertions/NotSameFixture.cs deleted file mode 100644 index dcc8ed936..000000000 --- a/test/NUnitLite/src/tests/Assertions/NotSameFixture.cs +++ /dev/null @@ -1,49 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class NotSameFixture : MessageChecker - { - private readonly string s1 = "S1"; - private readonly string s2 = "S2"; - - [Test] - public void NotSame() - { - Assert.AreNotSame(s1, s2); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void NotSameFails() - { - expectedMessage = - " Expected: not same as \"S1\"" + Env.NewLine + - " But was: \"S1\"" + Env.NewLine; - Assert.AreNotSame( s1, s1 ); - } - } -} diff --git a/test/NUnitLite/src/tests/Assertions/NullableTypesTests.cs b/test/NUnitLite/src/tests/Assertions/NullableTypesTests.cs deleted file mode 100644 index 76193c9bf..000000000 --- a/test/NUnitLite/src/tests/Assertions/NullableTypesTests.cs +++ /dev/null @@ -1,252 +0,0 @@ -// **************************************************************** -// Copyright 2008, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org. -// **************************************************************** -using System; - -namespace NUnit.Framework.Tests -{ -#if CLR_2_0 || CLR_4_0 -#if !MONO - [TestFixture, Category("Generics")] - public class NullableTypesTests - { - [Test] - public void CanTestForNull() - { - int? nullInt = null; - int? five = 5; - - Assert.IsNull(nullInt); - Assert.IsNotNull(five); - Assert.That(nullInt, Is.Null); - Assert.That(five, Is.Not.Null); - } - -#if false - [Test] - public void CanCompareNullableInts() - { - int? five = 5; - int? answer = 2 + 3; - - Assert.AreEqual(five, answer); - Assert.AreEqual(five, 5); - Assert.AreEqual(5, five); - - Assert.That(five, Is.EqualTo(answer)); - Assert.That(five, Is.EqualTo(5)); - Assert.That(5, Is.EqualTo(five)); - - Assert.Greater(five, 3); - Assert.GreaterOrEqual(five, 5); - Assert.Less(3, five); - Assert.LessOrEqual(5, five); - - Assert.That(five, Is.GreaterThan(3)); - Assert.That(five, Is.GreaterThanOrEqualTo(5)); - //Assert.That(3, Is.LessThan(five)); - //Assert.That(5, Is.LessThanOrEqualTo(five)); - } - - [Test] - public void CanCompareNullableDoubles() - { - double? five = 5.0; - double? answer = 2.0 + 3.0; - - Assert.AreEqual(five, answer); - Assert.AreEqual(five, 5.0); - Assert.AreEqual(5.0, five); - - Assert.That(five, Is.EqualTo(answer)); - Assert.That(five, Is.EqualTo(5.0)); - Assert.That(5.0, Is.EqualTo(five)); - - Assert.Greater(five, 3.0); - Assert.GreaterOrEqual(five, 5.0); - Assert.Less(3.0, five); - Assert.LessOrEqual(5.0, five); - - Assert.That(five, Is.GreaterThan(3.0)); - Assert.That(five, Is.GreaterThanOrEqualTo(5.0)); - //Assert.That(3.0, Is.LessThan(five)); - //Assert.That(5.0, Is.LessThanOrEqualTo(five)); - } -#endif - - [Test] - public void CanTestForNaN() - { - double? anNaN = Double.NaN; - Assert.That(anNaN, Is.NaN); - } - -#if false - [Test] - public void CanCompareNullableDecimals() - { - decimal? five = 5m; - decimal? answer = 2m + 3m; - - Assert.AreEqual(five, answer); - Assert.AreEqual(five, 5m); - Assert.AreEqual(5m, five); - - Assert.That(five, Is.EqualTo(answer)); - Assert.That(five, Is.EqualTo(5m)); - Assert.That(5m, Is.EqualTo(five)); - - Assert.Greater(five, 3m); - Assert.GreaterOrEqual(five, 5m); - Assert.Less(3m, five); - Assert.LessOrEqual(5m, five); - - Assert.That(five, Is.GreaterThan(3m)); - Assert.That(five, Is.GreaterThanOrEqualTo(5m)); - //Assert.That(3m, Is.LessThan(five)); - //Assert.That(5m, Is.LessThanOrEqualTo(five)); - } -#endif - - [Test] - public void CanCompareWithTolerance() - { - double? five = 5.0; - - Assert.AreEqual(5.0000001, five, .0001); - Assert.That( five, Is.EqualTo(5.0000001).Within(.0001)); - - float? three = 3.0f; - - Assert.AreEqual(3.00001f, three, .001); - Assert.That( three, Is.EqualTo(3.00001f).Within(.001)); - } - - private enum Colors - { - Red, - Blue, - Green - } - - [Test] - public void CanCompareNullableEnums() - { - Colors? color = Colors.Red; - Colors? other = Colors.Red; - - Assert.AreEqual(color, other); - Assert.AreEqual(color, Colors.Red); - Assert.AreEqual(Colors.Red, color); - } - - [Test] - public void CanCompareNullableMixedNumerics() - { - int? int5 = 5; - double? double5 = 5.0; - decimal? decimal5 = 5.00m; - - Assert.AreEqual(int5, double5); - Assert.AreEqual(int5, decimal5); - Assert.AreEqual(double5, int5); - Assert.AreEqual(double5, decimal5); - Assert.AreEqual(decimal5, int5); - Assert.AreEqual(decimal5, double5); - - Assert.That(int5, Is.EqualTo(double5)); - Assert.That(int5, Is.EqualTo(decimal5)); - Assert.That(double5, Is.EqualTo(int5)); - Assert.That(double5, Is.EqualTo(decimal5)); - Assert.That(decimal5, Is.EqualTo(int5)); - Assert.That(decimal5, Is.EqualTo(double5)); - - Assert.AreEqual(5, double5); - Assert.AreEqual(5, decimal5); - Assert.AreEqual(5.0, int5); - Assert.AreEqual(5.0, decimal5); - Assert.AreEqual(5m, int5); - Assert.AreEqual(5m, double5); - - Assert.That(5, Is.EqualTo(double5)); - Assert.That(5, Is.EqualTo(decimal5)); - Assert.That(5.0, Is.EqualTo(int5)); - Assert.That(5.0, Is.EqualTo(decimal5)); - Assert.That(5m, Is.EqualTo(int5)); - Assert.That(5m, Is.EqualTo(double5)); - - Assert.AreEqual(double5, 5); - Assert.AreEqual(decimal5, 5); - Assert.AreEqual(int5, 5.0); - Assert.AreEqual(decimal5, 5.0); - Assert.AreEqual(int5, 5m); - Assert.AreEqual(double5, 5m); - - Assert.That(double5, Is.EqualTo(5)); - Assert.That(decimal5, Is.EqualTo(5)); - Assert.That(int5, Is.EqualTo(5.0)); - Assert.That(decimal5, Is.EqualTo(5.0)); - Assert.That(int5, Is.EqualTo(5m)); - Assert.That(double5, Is.EqualTo(5m)); - -#if false - Assert.Greater(int5, 3.0); - Assert.Greater(int5, 3m); - Assert.Greater(double5, 3); - Assert.Greater(double5, 3m); - Assert.Greater(decimal5, 3); - Assert.Greater(decimal5, 3.0); - - Assert.That(int5, Is.GreaterThan(3.0)); - Assert.That(int5, Is.GreaterThan(3m)); - Assert.That(double5, Is.GreaterThan(3)); - Assert.That(double5, Is.GreaterThan(3m)); - Assert.That(decimal5, Is.GreaterThan(3)); - Assert.That(decimal5, Is.GreaterThan(3.0)); - - Assert.Less(3.0, int5); - Assert.Less(3m, int5); - Assert.Less(3, double5); - Assert.Less(3m, double5); - Assert.Less(3, decimal5); - Assert.Less(3.0, decimal5); -#endif - //Assert.That(3.0, Is.LessThan(int5)); - //Assert.That(3m, Is.LessThan(int5)); - //Assert.That(3, Is.LessThan(double5)); - //Assert.That(3m, Is.LessThan(double5)); - //Assert.That(3, Is.LessThan(decimal5)); - //Assert.That(3.0, Is.LessThan(decimal5)); - } - - private struct MyStruct - { - int i; - string s; - - public MyStruct(int i, string s) - { - this.i = i; - this.s = s; - } - } - - [Test] - public void CanCompareNullableStructs() - { - MyStruct struct1 = new MyStruct(5, "Hello"); - MyStruct struct2 = new MyStruct(5, "Hello"); - Nullable one = new MyStruct(5, "Hello"); - Nullable two = new MyStruct(5, "Hello"); - - Assert.AreEqual(struct1, struct2); // Control - Assert.AreEqual(one, two); - Assert.AreEqual(one, struct1); - Assert.AreEqual(struct2, two); - } - } -#endif -#endif -} diff --git a/test/NUnitLite/src/tests/Assertions/SameFixture.cs b/test/NUnitLite/src/tests/Assertions/SameFixture.cs deleted file mode 100644 index 2ec97ca07..000000000 --- a/test/NUnitLite/src/tests/Assertions/SameFixture.cs +++ /dev/null @@ -1,61 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2004 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Text; -using NUnit.Framework; - -namespace NUnit.Framework.Assertions -{ - [TestFixture] - public class SameFixture : MessageChecker - { - [Test] - public void Same() - { - string s1 = "S1"; - Assert.AreSame(s1, s1); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void SameFails() - { - Exception ex1 = new Exception( "one" ); - Exception ex2 = new Exception( "two" ); - expectedMessage = - " Expected: same as " + Env.NewLine + - " But was: " + Env.NewLine; - Assert.AreSame(ex1, ex2); - } - - [Test,ExpectedException(typeof(AssertionException))] - public void SameValueTypes() - { - int index = 2; - expectedMessage = - " Expected: same as 2" + Env.NewLine + - " But was: 2" + Env.NewLine; - Assert.AreSame(index, index); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/ApplyToTestTests.cs b/test/NUnitLite/src/tests/Attributes/ApplyToTestTests.cs deleted file mode 100644 index 075f97d10..000000000 --- a/test/NUnitLite/src/tests/Attributes/ApplyToTestTests.cs +++ /dev/null @@ -1,331 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class ApplyToTestTests - { - Test test; - - [SetUp] - public void SetUp() - { - test = new TestDummy(); - test.RunState = RunState.Runnable; - } - - #region CategoryAttribute - - [Test] - public void CategoryAttributeSetsCategory() - { - new CategoryAttribute("database").ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); - } - - [Test] - public void CategoryAttributeSetsMultipleCategories() - { - new CategoryAttribute("group1").ApplyToTest(test); - new CategoryAttribute("group2").ApplyToTest(test); - Assert.That(test.Properties[PropertyNames.Category], - Is.EquivalentTo(new string[] { "group1", "group2" })); - } - - #endregion - - #region DescriptionAttribute - - [Test] - public void DescriptionAttributeSetsDescription() - { - new DescriptionAttribute("Cool test!").ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); - } - - #endregion - - #region IgnoreAttribute - - [Test] - public void IgnoreAttributeIgnoresTest() - { - new IgnoreAttribute().ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); - } - - [Test] - public void IgnoreAttributeSetsIgnoreReason() - { - new IgnoreAttribute("BECAUSE").ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); - Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); - } - - #endregion - - #region ExplicitAttribute - - [Test] - public void ExplicitAttributeMakesTestExplicit() - { - new ExplicitAttribute().ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); - } - - [Test] - public void ExplicitAttributeSetsIgnoreReason() - { - new ExplicitAttribute("BECAUSE").ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); - Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); - } - - #endregion - - #region CombinatorialAttribute - - [Test] - public void CombinatorialAttributeSetsJoinType() - { - new CombinatorialAttribute().ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); - } - - #endregion - - #region CultureAttribute - - [Test] - public void CultureAttributeIncludingCurrentCultureRunsTest() - { - string name = System.Globalization.CultureInfo.CurrentCulture.Name; - new CultureAttribute(name).ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); - } - - [Test] - public void CultureAttributeExcludingCurrentCultureSkipsTest() - { - string name = System.Globalization.CultureInfo.CurrentCulture.Name; - CultureAttribute attr = new CultureAttribute(name); - attr.Exclude = name; - attr.ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); - Assert.That(test.Properties.Get(PropertyNames.SkipReason), - Is.EqualTo("Not supported under culture " + name)); - } - - [Test] - public void CultureAttributeIncludingOtherCultureSkipsTest() - { - string name = "fr-FR"; - if (System.Globalization.CultureInfo.CurrentCulture.Name == name) - name = "en-US"; - - new CultureAttribute(name).ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); - Assert.That(test.Properties.Get(PropertyNames.SkipReason), - Is.EqualTo("Only supported under culture " + name)); - } - - [Test] - public void CultureAttributeExcludingOtherCultureRunsTest() - { - string other = "fr-FR"; - if (System.Globalization.CultureInfo.CurrentCulture.Name == other) - other = "en-US"; - - CultureAttribute attr = new CultureAttribute(); - attr.Exclude = other; - attr.ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); - } - - [Test] - public void CultureAttributeWithMultipleCulturesIncluded() - { - string current = System.Globalization.CultureInfo.CurrentCulture.Name; - string other = current == "fr-FR" ? "en-US" : "fr-FR"; - string cultures = current + "," + "other"; - - new CultureAttribute(cultures).ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); - } - - #endregion - - #region MaxTimeAttribute - - [Test] - public void MaxTimeAttributeSetsMaxTime() - { - new MaxTimeAttribute(2000).ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); - } - - #endregion - - #region PairwiseAttribute - - [Test] - public void PairwiseAttributeSetsJoinType() - { - new PairwiseAttribute().ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); - } - - #endregion - - #region PlatformAttribute - - [Test] - public void PlatformAttributeRunsTest() - { - string myPlatform = System.IO.Path.DirectorySeparatorChar == '/' - ? "Linux" : "Win"; - new PlatformAttribute(myPlatform).ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); - } - - [Test] - public void PlatformAttributeSkipsTest() - { - string notMyPlatform = System.IO.Path.DirectorySeparatorChar == '/' - ? "Win" : "Linux"; - new PlatformAttribute(notMyPlatform).ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); - } - - #endregion - -#if !NUNITLITE - - #region RepeatAttribute - - public void RepeatAttributeSetsRepeatCount() - { - new RepeatAttribute(5).ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); - } - - #endregion - - #region RequiredAddinAttribute - - [Test, Ignore("NYI")] - public void RequiredAddinAttributeSkipsTest() - { - new RequiredAddinAttribute("JUNK").ApplyToTest(test); - Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); - } - - #endregion - - #region RequiresMTAAttribute - - [Test] - public void RequiresMTAAttributeSetsApartmentState() - { - new RequiresMTAAttribute().ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.ApartmentState), - Is.EqualTo(System.Threading.ApartmentState.MTA)); - } - - #endregion - - #region RequiresSTAAttribute - - [Test] - public void RequiresSTAAttributeSetsApartmentState() - { - new RequiresSTAAttribute().ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.ApartmentState), - Is.EqualTo(System.Threading.ApartmentState.STA)); - } - - #endregion - - #region RequiresThreadAttribute - - [Test] - public void RequiresThreadAttributeSetsRequiresThread() - { - new RequiresThreadAttribute().ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); - } - - [Test] - public void RequiresThreadAttributeMaySetApartmentState() - { - new RequiresThreadAttribute(System.Threading.ApartmentState.STA).ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); - Assert.That(test.Properties.Get(PropertyNames.ApartmentState), - Is.EqualTo(System.Threading.ApartmentState.STA)); - } - - #endregion - -#endif - - #region SequentialAttribute - - [Test] - public void SequentialAttributeSetsJoinType() - { - new SequentialAttribute().ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); - } - - #endregion - -#if !NETCF - - #region SetCultureAttribute - - public void SetCultureAttributeSetsSetCultureProperty() - { - new SetCultureAttribute("fr-FR").ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); - } - - #endregion - - #region SetUICultureAttribute - - public void SetUICultureAttributeSetsSetUICultureProperty() - { - new SetUICultureAttribute("fr-FR").ApplyToTest(test); - Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); - } - - #endregion - -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/AttributeInheritanceTests.cs b/test/NUnitLite/src/tests/Attributes/AttributeInheritanceTests.cs deleted file mode 100644 index a272fed85..000000000 --- a/test/NUnitLite/src/tests/Attributes/AttributeInheritanceTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; -using NUnit.TestData.AttributeInheritanceData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Tests -{ - [TestFixture] - public class AttributeInheritanceTests - { - [Test] - public void InheritedFixtureAttributeIsRecognized() - { - Assert.That( TestBuilder.MakeFixture( typeof (When_collecting_test_fixtures) ) != null ); - } - - [Test] - public void InheritedTestAttributeIsRecognized() - { - Test fixture = TestBuilder.MakeFixture( typeof( When_collecting_test_fixtures ) ); - Assert.AreEqual( 1, fixture.TestCaseCount ); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/CategoryAttributeTests.cs b/test/NUnitLite/src/tests/Attributes/CategoryAttributeTests.cs deleted file mode 100644 index 5d750f1fc..000000000 --- a/test/NUnitLite/src/tests/Attributes/CategoryAttributeTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData.CategoryAttributeData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - /// - /// Summary description for CategoryAttributeTests. - /// - [TestFixture] - public class CategoryAttributeTests - { - TestSuite fixture; - - [SetUp] - public void CreateFixture() - { - fixture = TestBuilder.MakeFixture( typeof( FixtureWithCategories ) ); - } - - [Test] - public void CategoryOnFixture() - { - Assert.That( fixture.Properties.Contains("Category", "DataBase")); - } - - [Test] - public void CategoryOnTestMethod() - { - Test test1 = (Test)fixture.Tests[0]; - Assert.That( test1.Properties.Contains("Category", "Long") ); - } - - [Test] - public void CanDeriveFromCategoryAttribute() - { - Test test2 = (Test)fixture.Tests[1]; - Assert.That(test2.Properties["Category"], Contains.Item("Critical") ); - } - - [Test] - public void DerivedCategoryMayBeInherited() - { - Assert.That(fixture.Properties.Contains("Category", "MyCategory")); - } - - [Test] - public void CanSpecifyOnMethodAndTestCase() - { - TestSuite test3 = (TestSuite)fixture.Tests[2]; - Assert.That(test3.Name, Is.EqualTo("Test3")); - Assert.That(test3.Properties["Category"], Contains.Item("Top")); - Test testCase = (Test)test3.Tests[0]; - Assert.That(testCase.Name, Is.EqualTo("Test3(5)")); - Assert.That(testCase.Properties["Category"], Contains.Item("Bottom")); - } - - [Test] - public void TestWithInvalidCategoryNameIsNotRunnable() - { - Test test4 = (Test)fixture.Tests[3]; - Assert.That(test4.RunState, Is.EqualTo(RunState.NotRunnable)); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/CombinatorialTests.cs b/test/NUnitLite/src/tests/Attributes/CombinatorialTests.cs deleted file mode 100644 index 3ad46b44e..000000000 --- a/test/NUnitLite/src/tests/Attributes/CombinatorialTests.cs +++ /dev/null @@ -1,100 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class CombinatorialTests - { - [Test] - public void SingleArgument( - [Values(1.3, 1.7, 1.5)] double x) - { - Assert.That(x > 1.0 && x < 2.0); - } - - [Test, Combinatorial] - public void TwoArguments_Combinatorial( - [Values(1, 2, 3)] int x, - [Values(10, 20)] int y) - { - Assert.That(x > 0 && x < 4 && y % 10 == 0); - } - - [Test, Sequential] - public void TwoArguments_Sequential( - [Values(1, 2, 3)] int x, - [Values(10, 20)] int y) - { - Assert.That(x > 0 && x < 4 && y % 10 == 0); - } - - [Test, Combinatorial] - public void ThreeArguments_Combinatorial( - [Values(1, 2, 3)] int x, - [Values(10, 20)] int y, - [Values("Charlie", "Joe", "Frank")] string name) - { - Assert.That(x > 0 && x < 4 && y % 10 == 0); - Assert.That(name.Length >= 2); - } - - [Test, Sequential] - public void ThreeArguments_Sequential( - [Values(1, 2, 3)] int x, - [Values(10, 20)] int y, - [Values("Charlie", "Joe", "Frank")] string name) - { - Assert.That(x > 0 && x < 4 && y % 10 == 0); - Assert.That(name.Length >= 2); - } - - [Test] - public void RangeTest( - [Range(0.2, 0.6, 0.2)] double a, - [Range(10, 20, 5)] int b) - { - } - - [Test, Sequential] - public void RandomTest( - [Random(32, 212, 5)] int x, - [Random(5)] double y, - [Random(5)] AttributeTargets z) - { - Assert.That(x,Is.InRange(32,212)); - Assert.That(y,Is.InRange(0.0,1.0)); - Assert.That(z, Is.TypeOf(typeof(AttributeTargets))); - } - - [Test, Sequential] - public void RandomArgsAreIndependent( - [Random(1)] double x, - [Random(1)] double y) - { - Assert.AreNotEqual(x, y); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/DatapointTests.cs b/test/NUnitLite/src/tests/Attributes/DatapointTests.cs deleted file mode 100644 index 742cf1f6e..000000000 --- a/test/NUnitLite/src/tests/Attributes/DatapointTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData.DatapointFixture; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - public class DatapointTests - { - private void RunTestOnFixture(Type fixtureType) - { - TestResult result = TestBuilder.RunTestFixture(fixtureType); - ResultSummary summary = new ResultSummary(result); - Assert.That(summary.Passed, Is.EqualTo(2)); - Assert.That(summary.Inconclusive, Is.EqualTo(3)); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Success)); - } - - [Test] - public void WorksOnField() - { - RunTestOnFixture(typeof(SquareRootTest_Field_Double)); - } - - [Test] - public void WorksOnArray() - { - RunTestOnFixture(typeof(SquareRootTest_Field_ArrayOfDouble)); - } - - [Test] - public void WorksOnPropertyReturningArray() - { - RunTestOnFixture(typeof(SquareRootTest_Property_ArrayOfDouble)); - } - - [Test] - public void WorksOnMethodReturningArray() - { - RunTestOnFixture(typeof(SquareRootTest_Method_ArrayOfDouble)); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void WorksOnIEnumerableOfT() - { - RunTestOnFixture(typeof(SquareRootTest_Field_IEnumerableOfDouble)); - } - - [Test] - public void WorksOnPropertyReturningIEnumerableOfT() - { - RunTestOnFixture(typeof(SquareRootTest_Property_IEnumerableOfDouble)); - } - - [Test] - public void WorksOnMethodReturningIEnumerableOfT() - { - RunTestOnFixture(typeof(SquareRootTest_Method_IEnumerableOfDouble)); - } - - [Test] - public void WorksOnEnumeratorReturningIEnumerableOfT() - { - RunTestOnFixture(typeof(SquareRootTest_Iterator_IEnumerableOfDouble)); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/DescriptionTests.cs b/test/NUnitLite/src/tests/Attributes/DescriptionTests.cs deleted file mode 100644 index eb1bbdeb0..000000000 --- a/test/NUnitLite/src/tests/Attributes/DescriptionTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.TestData.DescriptionFixture; -using NUnit.TestUtilities; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Attributes -{ - // TODO: Review to see if we need these tests - - [TestFixture] - public class DescriptionTests - { - static readonly Type FixtureType = typeof( DescriptionFixture ); - - [Test] - public void ReflectionTest() - { - Test testCase = TestBuilder.MakeTestCase( FixtureType, "Method" ); - Assert.AreEqual( RunState.Runnable, testCase.RunState ); - } - - [Test] - public void Description() - { - Test testCase = TestBuilder.MakeTestCase(FixtureType, "Method"); - Assert.AreEqual("Test Description", testCase.Properties.Get(PropertyNames.Description)); - } - - [Test] - public void NoDescription() - { - Test testCase = TestBuilder.MakeTestCase( FixtureType, "NoDescriptionMethod" ); - Assert.IsNull(testCase.Properties.Get(PropertyNames.Description)); - } - - [Test] - public void FixtureDescription() - { - TestSuite suite = new TestSuite("suite"); - suite.Add( TestBuilder.MakeFixture( typeof( DescriptionFixture ) ) ); - - TestSuite mockFixtureSuite = (TestSuite)suite.Tests[0]; - - Assert.AreEqual("Fixture Description", mockFixtureSuite.Properties.Get(PropertyNames.Description)); - } - - [Test] - public void SeparateDescriptionAttribute() - { - Test testCase = TestBuilder.MakeTestCase(FixtureType, "SeparateDescriptionMethod"); - Assert.AreEqual("Separate Description", testCase.Properties.Get(PropertyNames.Description)); - } - - [Test] - public void DescriptionOnTestCase() - { - TestSuite parameterizedMethodSuite = TestBuilder.MakeParameterizedMethodSuite(FixtureType, "TestCaseWithDescription"); - Assert.AreEqual("method description", parameterizedMethodSuite.Properties.Get(PropertyNames.Description)); - Test testCase = (Test)parameterizedMethodSuite.Tests[0]; - Assert.AreEqual("case description", testCase.Properties.Get(PropertyNames.Description)); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/ExpectedExceptionTests.cs b/test/NUnitLite/src/tests/Attributes/ExpectedExceptionTests.cs deleted file mode 100644 index 23bbcce4d..000000000 --- a/test/NUnitLite/src/tests/Attributes/ExpectedExceptionTests.cs +++ /dev/null @@ -1,470 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; -using NUnit.TestData.ExpectedExceptionData; -#if !NETCF -using System.Runtime.Serialization; -#endif - -namespace NUnit.Framework.Attributes -{ - /// - /// - /// - [TestFixture] - public class ExpectedExceptionTests - { - [Test, ExpectedException] - public void CanExpectUnspecifiedException() - { - throw new ArgumentException(); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void TestSucceedsWithSpecifiedExceptionType() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException(ExpectedException=typeof(ArgumentException))] - public void TestSucceedsWithSpecifiedExceptionTypeAsNamedParameter() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException("System.ArgumentException")] - public void TestSucceedsWithSpecifiedExceptionName() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException(ExpectedExceptionName="System.ArgumentException")] - public void TestSucceedsWithSpecifiedExceptionNameAsNamedParameter() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException),ExpectedMessage="argument exception")] - public void TestSucceedsWithSpecifiedExceptionTypeAndMessage() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage="argument exception", MatchType=MessageMatch.Exact)] - public void TestSucceedsWithSpecifiedExceptionTypeAndExactMatch() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException),ExpectedMessage="invalid", MatchType=MessageMatch.Contains)] - public void TestSucceedsWithSpecifiedExceptionTypeAndContainsMatch() - { - throw new ArgumentException("argument invalid exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException),ExpectedMessage="exception$", MatchType=MessageMatch.Regex)] - public void TestSucceedsWithSpecifiedExceptionTypeAndRegexMatch() - { - throw new ArgumentException("argument invalid exception"); - } - - [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "argument invalid", MatchType = MessageMatch.StartsWith)] - public void TestSucceedsWithSpecifiedExceptionTypeAndStartsWithMatch() - { - throw new ArgumentException("argument invalid exception"); - } - -// [Test] -// [ExpectedException("System.ArgumentException", "argument exception")] -// public void TestSucceedsWithSpecifiedExceptionNameAndMessage_OldFormat() -// { -// throw new ArgumentException("argument exception"); -// } - - [Test] - [ExpectedException("System.ArgumentException", ExpectedMessage = "argument exception")] - public void TestSucceedsWithSpecifiedExceptionNameAndMessage_NewFormat() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException("System.ArgumentException",ExpectedMessage="argument exception",MatchType=MessageMatch.Exact)] - public void TestSucceedsWithSpecifiedExceptionNameAndExactMatch() - { - throw new ArgumentException("argument exception"); - } - - [Test] - [ExpectedException("System.ArgumentException",ExpectedMessage="invalid", MatchType=MessageMatch.Contains)] - public void TestSucceedsWhenSpecifiedExceptionNameAndContainsMatch() - { - throw new ArgumentException("argument invalid exception"); - } - - [Test] - [ExpectedException("System.ArgumentException",ExpectedMessage="exception$", MatchType=MessageMatch.Regex)] - public void TestSucceedsWhenSpecifiedExceptionNameAndRegexMatch() - { - throw new ArgumentException("argument invalid exception"); - } - - [Test] - public void TestFailsWhenBaseExceptionIsThrown() - { - Type fixtureType = typeof(BaseException); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "BaseExceptionTest" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "BaseExceptionTest should have failed"); - Assert.That(result.Message, Is.StringStarting( - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.ArgumentException" + Env.NewLine + - " but was: System.Exception")); - } - - [Test] - public void TestFailsWhenDerivedExceptionIsThrown() - { - Type fixtureType = typeof(DerivedException); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "DerivedExceptionTest"); - Assert.IsTrue(result.ResultState == ResultState.Failure, "DerivedExceptionTest should have failed"); - Assert.That(result.Message, Is.StringStarting( - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.Exception" + Env.NewLine + - " but was: System.ArgumentException")); - } - - [Test] - public void TestMismatchedExceptionType() - { - Type fixtureType = typeof(MismatchedException); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionType"); - Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionType should have failed"); - Assert.That(result.Message, Is.StringStarting( - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.ArgumentException" + Env.NewLine + - " but was: System.ArgumentOutOfRangeException")); - } - - [Test] - public void TestMismatchedExceptionTypeAsNamedParameter() - { - Type fixtureType = typeof(MismatchedException); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionTypeAsNamedParameter"); - Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionType should have failed"); - Assert.That(result.Message, Is.StringStarting( - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.ArgumentException" + Env.NewLine + - " but was: System.ArgumentOutOfRangeException")); - } - - [Test] - public void TestMismatchedExceptionTypeWithUserMessage() - { - Type fixtureType = typeof(MismatchedException); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "MismatchedExceptionTypeWithUserMessage" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.That(result.Message, Is.StringStarting( - "custom message" + Env.NewLine + - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.ArgumentException" + Env.NewLine + - " but was: System.ArgumentOutOfRangeException")); - } - - [Test] - public void TestMismatchedExceptionName() - { - Type fixtureType = typeof(MismatchedException); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "MismatchedExceptionName" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionName should have failed"); - Assert.That(result.Message, Is.StringStarting( - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.ArgumentException" + Env.NewLine + - " but was: System.ArgumentOutOfRangeException")); - } - - [Test] - public void TestMismatchedExceptionNameWithUserMessage() - { - Type fixtureType = typeof(MismatchedException); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionNameWithUserMessage"); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.That(result.Message, Is.StringStarting( - "custom message" + Env.NewLine + - "An unexpected exception type was thrown" + Env.NewLine + - "Expected: System.ArgumentException" + Env.NewLine + - " but was: System.ArgumentOutOfRangeException")); - } - - [Test] - public void TestMismatchedExceptionMessage() - { - Type fixtureType = typeof(TestThrowsExceptionWithWrongMessage); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestThrow" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "TestThrow should have failed"); - Assert.AreEqual( - "The exception message text was incorrect" + Env.NewLine + - "Expected: not the message" + Env.NewLine + - " but was: the message", - result.Message); - } - - [Test] - public void TestMismatchedExceptionMessageWithUserMessage() - { - Type fixtureType = typeof(TestThrowsExceptionWithWrongMessage); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestThrowWithUserMessage" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "TestThrow should have failed"); - Assert.AreEqual( - "custom message" + Env.NewLine + - "The exception message text was incorrect" + Env.NewLine + - "Expected: not the message" + Env.NewLine + - " but was: the message", - result.Message); - } - - [Test] - public void TestUnspecifiedExceptionNotThrown() - { - Type fixtureType = typeof(TestDoesNotThrowExceptionFixture); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowUnspecifiedException" ); - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.AreEqual("An Exception was expected", result.Message); - } - - [Test] - public void TestUnspecifiedExceptionNotThrownWithUserMessage() - { - Type fixtureType = typeof(TestDoesNotThrowExceptionFixture); - ITestResult result = TestBuilder.RunTestCase(fixtureType, "TestDoesNotThrowUnspecifiedExceptionWithUserMessage"); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.AreEqual("custom message" + Env.NewLine + "An Exception was expected", result.Message); - } - - [Test] - public void TestExceptionTypeNotThrown() - { - Type fixtureType = typeof(TestDoesNotThrowExceptionFixture); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionType" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.AreEqual("System.ArgumentException was expected", result.Message); - } - - [Test] - public void TestExceptionTypeNotThrownWithUserMessage() - { - Type fixtureType = typeof(TestDoesNotThrowExceptionFixture); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionTypeWithUserMessage" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.AreEqual("custom message" + Env.NewLine + "System.ArgumentException was expected", result.Message); - } - - [Test] - public void TestExceptionNameNotThrown() - { - Type fixtureType = typeof(TestDoesNotThrowExceptionFixture); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionName" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.AreEqual("System.ArgumentException was expected", result.Message); - } - - [Test] - public void TestExceptionNameNotThrownWithUserMessage() - { - Type fixtureType = typeof(TestDoesNotThrowExceptionFixture); - ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionNameWithUserMessage" ); - Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed"); - Assert.AreEqual("custom message" + Env.NewLine + "System.ArgumentException was expected", result.Message); - } - - [Test] - public void MethodThrowsException() - { - TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionFixture ) ); - Assert.AreEqual(true, result.ResultState == ResultState.Failure); - } - - [Test] - public void MethodThrowsRightExceptionMessage() - { - TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionWithRightMessage ) ); - Assert.AreEqual(true, result.ResultState == ResultState.Success); - } - - [Test] - public void MethodThrowsArgumentOutOfRange() - { - TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsArgumentOutOfRangeException ) ); - Assert.AreEqual(true, result.ResultState == ResultState.Success); - } - - [Test] - public void MethodThrowsWrongExceptionMessage() - { - TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionWithWrongMessage ) ); - Assert.AreEqual(true, result.ResultState == ResultState.Failure); - } - - [Test] - public void SetUpThrowsSameException() - { - TestResult result = TestBuilder.RunTestFixture( typeof( SetUpExceptionTests ) ); - Assert.AreEqual(true, result.ResultState == ResultState.Failure); - } - - [Test] - public void TearDownThrowsSameException() - { - TestResult result = TestBuilder.RunTestFixture( typeof( TearDownExceptionTests ) ); - Assert.AreEqual(true, result.ResultState == ResultState.Failure); - } - - [Test] - public void AssertFailBeforeException() - { - TestResult suiteResult = TestBuilder.RunTestFixture( typeof (TestAssertsBeforeThrowingException) ); - Assert.AreEqual( ResultState.Failure, suiteResult.ResultState ); - TestResult result = (TestResult)suiteResult.Children[0]; - Assert.AreEqual( "private message", result.Message ); - } - - internal class MyAppException : System.Exception - { - public MyAppException (string message) : base(message) - {} - - public MyAppException(string message, Exception inner) : - base(message, inner) - {} - -#if !NETCF && !SILVERLIGHT - protected MyAppException(SerializationInfo info, - StreamingContext context) : base(info,context) - {} -#endif - } - - [Test] - [ExpectedException(typeof(MyAppException))] - public void ThrowingMyAppException() - { - throw new MyAppException("my app"); - } - - [Test] - [ExpectedException(typeof(MyAppException), ExpectedMessage="my app")] - public void ThrowingMyAppExceptionWithMessage() - { - throw new MyAppException("my app"); - } - - [Test] - [ExpectedException(typeof(NUnitException))] - public void ThrowNUnitException() - { - throw new NUnitException("Nunit exception"); - } - - [Test] - public void ExceptionHandlerIsCalledWhenExceptionMatches_AlternateHandler() - { - ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass(); - TestBuilder.RunTestCase( fixture, "ThrowsArgumentException_AlternateHandler" ); - Assert.IsFalse(fixture.HandlerCalled, "Base Handler should not be called" ); - Assert.IsTrue(fixture.AlternateHandlerCalled, "Alternate Handler should be called" ); - } - - [Test] - public void ExceptionHandlerIsCalledWhenExceptionMatches() - { - ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass(); - TestBuilder.RunTestCase( fixture, "ThrowsArgumentException" ); - Assert.IsTrue(fixture.HandlerCalled, "Base Handler should be called"); - Assert.IsFalse(fixture.AlternateHandlerCalled, "Alternate Handler should not be called"); - } - - [Test] - public void ExceptionHandlerIsNotCalledWhenExceptionDoesNotMatch() - { - ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass(); - TestBuilder.RunTestCase( fixture, "ThrowsCustomException" ); - Assert.IsFalse( fixture.HandlerCalled, "Base Handler should not be called" ); - Assert.IsFalse( fixture.AlternateHandlerCalled, "Alternate Handler should not be called" ); - } - - [Test] - public void ExceptionHandlerIsNotCalledWhenExceptionDoesNotMatch_AlternateHandler() - { - ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass(); - TestBuilder.RunTestCase(fixture, "ThrowsCustomException_AlternateHandler"); - Assert.IsFalse(fixture.HandlerCalled, "Base Handler should not be called"); - Assert.IsFalse(fixture.AlternateHandlerCalled, "Alternate Handler should not be called"); - } - - [Test] - public void TestIsNotRunnableWhenAlternateHandlerIsNotFound() - { - ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass(); - Test test = TestBuilder.MakeTestCase( fixture, "MethodWithBadHandler" ); - Assert.AreEqual( RunState.NotRunnable, test.RunState ); - Assert.AreEqual( - "The specified exception handler DeliberatelyMissingHandler was not found", - test.Properties.Get(PropertyNames.SkipReason) ); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void TestSucceedsInStaticClass() - { - ITestResult result = TestBuilder.RunTestCase(typeof(StaticClassWithExpectedExceptions), "TestSucceedsInStaticClass"); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Success)); - } - - [Test] - public void TestFailsInStaticClass_NoExceptionThrown() - { - ITestResult result = TestBuilder.RunTestCase(typeof(StaticClassWithExpectedExceptions), "TestFailsInStaticClass_NoExceptionThrown"); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); - } - - [Test] - public void TestFailsInStaticClass_WrongExceptionThrown() - { - ITestResult result = TestBuilder.RunTestCase(typeof(StaticClassWithExpectedExceptions), "TestFailsInStaticClass_WrongExceptionThrown"); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/FixtureSetUpTearDownTests.cs b/test/NUnitLite/src/tests/Attributes/FixtureSetUpTearDownTests.cs deleted file mode 100644 index eb8a55dfb..000000000 --- a/test/NUnitLite/src/tests/Attributes/FixtureSetUpTearDownTests.cs +++ /dev/null @@ -1,336 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if !NETCF -using System.Security.Principal; -#endif -using System.Threading; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.Framework.Builders; -using NUnit.TestData.FixtureSetUpTearDownData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class FixtureSetupTearDownTest - { - [Test] - public void MakeSureSetUpAndTearDownAreCalled() - { - SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(1, fixture.setUpCount, "SetUp"); - Assert.AreEqual(1, fixture.tearDownCount, "TearDown"); - } - - [Test] - public void MakeSureSetUpAndTearDownAreCalledOnExplicitFixture() - { - ExplicitSetUpAndTearDownFixture fixture = new ExplicitSetUpAndTearDownFixture(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(1, fixture.setUpCount, "SetUp"); - Assert.AreEqual(1, fixture.tearDownCount, "TearDown"); - } - - [Test] - public void CheckInheritedSetUpAndTearDownAreCalled() - { - InheritSetUpAndTearDown fixture = new InheritSetUpAndTearDown(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); - } - - [Test] - public static void StaticSetUpAndTearDownAreCalled() - { - StaticSetUpAndTearDownFixture.setUpCount = 0; - StaticSetUpAndTearDownFixture.tearDownCount = 0; - TestBuilder.RunTestFixture(typeof(StaticSetUpAndTearDownFixture)); - - Assert.AreEqual(1, StaticSetUpAndTearDownFixture.setUpCount); - Assert.AreEqual(1, StaticSetUpAndTearDownFixture.tearDownCount); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public static void StaticClassSetUpAndTearDownAreCalled() - { - StaticClassSetUpAndTearDownFixture.setUpCount = 0; - StaticClassSetUpAndTearDownFixture.tearDownCount = 0; - - TestBuilder.RunTestFixture(typeof(StaticClassSetUpAndTearDownFixture)); - - Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.setUpCount); - Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.tearDownCount); - } -#endif - - [Test] - public void OverriddenSetUpAndTearDownAreNotCalled() - { - DefineInheritSetUpAndTearDown fixture = new DefineInheritSetUpAndTearDown(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(0, fixture.setUpCount); - Assert.AreEqual(0, fixture.tearDownCount); - Assert.AreEqual(1, fixture.derivedSetUpCount); - Assert.AreEqual(1, fixture.derivedTearDownCount); - } - - [Test] - public void BaseSetUpCalledFirstAndTearDownCalledLast() - { - DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); - Assert.AreEqual(1, fixture.derivedSetUpCount); - Assert.AreEqual(1, fixture.derivedTearDownCount); - Assert.That(fixture.baseSetUpCalledFirst, "Base SetUp called first"); - Assert.That(fixture.baseTearDownCalledLast, "Base TearDown called last"); - } - - [Test] - public void StaticBaseSetUpCalledFirstAndTearDownCalledLast() - { - StaticSetUpAndTearDownFixture.setUpCount = 0; - StaticSetUpAndTearDownFixture.tearDownCount = 0; - DerivedStaticSetUpAndTearDownFixture.derivedSetUpCount = 0; - DerivedStaticSetUpAndTearDownFixture.derivedTearDownCount = 0; - - DerivedStaticSetUpAndTearDownFixture fixture = new DerivedStaticSetUpAndTearDownFixture(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.setUpCount); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.tearDownCount); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.derivedSetUpCount); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.derivedTearDownCount); - Assert.That(DerivedStaticSetUpAndTearDownFixture.baseSetUpCalledFirst, "Base SetUp called first"); - Assert.That(DerivedStaticSetUpAndTearDownFixture.baseTearDownCalledLast, "Base TearDown called last"); - } - - [Test] - public void HandleErrorInFixtureSetup() - { - MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInSetUp = true; - ITestResult result = TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCOunt" ); - - Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.AreEqual("System.Exception : This was thrown from fixture setup", result.Message, "TestSuite Message"); - Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null"); - - Assert.AreEqual(1, result.Children.Count, "Result should have one child"); - Assert.AreEqual(1, result.FailCount, "Failure count"); - } - - [Test] - public void RerunFixtureAfterSetUpFixed() - { - MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInSetUp = true; - ITestResult result = TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(ResultState.Error, result.ResultState); - - //fix the blow up in setup - fixture.Reinitialize(); - result = TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCOunt" ); - - Assert.AreEqual(ResultState.Success, result.ResultState); - } - - [Test] - public void HandleIgnoreInFixtureSetup() - { - IgnoreInFixtureSetUp fixture = new IgnoreInFixtureSetUp(); - ITestResult result = TestBuilder.RunTestFixture(fixture); - - // should have one suite and one fixture - Assert.AreEqual(ResultState.Ignored, result.ResultState, "Suite should be ignored"); - Assert.AreEqual("TestFixtureSetUp called Ignore", result.Message); - Assert.IsNotNull(result.StackTrace, "StackTrace should not be null"); - - Assert.AreEqual(1, result.Children.Count); - Assert.AreEqual(1, result.SkipCount); - } - - [Test] - public void HandleErrorInFixtureTearDown() - { - MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInTearDown = true; - ITestResult result = TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, result.Children.Count); - Assert.AreEqual(ResultState.Error, result.ResultState); - - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCOunt" ); - - Assert.AreEqual("TearDown : System.Exception : This was thrown from fixture teardown", result.Message); - Assert.IsNotNull(result.StackTrace, "StackTrace should not be null"); - } - - [Test] - public void HandleExceptionInFixtureConstructor() - { - ITestResult result = TestBuilder.RunTestFixture( typeof( ExceptionInConstructor ) ); - - Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.AreEqual("System.Exception : This was thrown in constructor", result.Message, "TestSuite Message"); - Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null"); - - Assert.AreEqual(1, result.Children.Count, "Result should have one child"); - Assert.AreEqual(1, result.FailCount, "Failure count"); - } - - [Test] - public void RerunFixtureAfterTearDownFixed() - { - MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInTearDown = true; - ITestResult result = TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, result.Children.Count); - - fixture.Reinitialize(); - result = TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCOunt" ); - } - - [Test] - public void HandleSetUpAndTearDownWithTestInName() - { - SetUpAndTearDownWithTestInName fixture = new SetUpAndTearDownWithTestInName(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); - } - - //[Test] - //public void RunningSingleMethodCallsSetUpAndTearDown() - //{ - // SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture(); - // TestSuite suite = TestBuilder.MakeFixture(fixture.GetType()); - // suite.Fixture = fixture; - // Test test = (Test)suite.Tests[0]; - - // suite.Run(TestListener.NULL, new NameFilter(test.TestName)); - - // Assert.AreEqual(1, fixture.setUpCount); - // Assert.AreEqual(1, fixture.tearDownCount); - //} - - [Test] - public void IgnoredFixtureShouldNotCallFixtureSetUpOrTearDown() - { - IgnoredFixture fixture = new IgnoredFixture(); - TestSuite suite = new TestSuite("IgnoredFixtureSuite"); - TestSuite fixtureSuite = TestBuilder.MakeFixture( fixture.GetType() ); - Test test = (Test)fixtureSuite.Tests[0]; - suite.Add( fixtureSuite ); - - TestBuilder.RunTest(fixtureSuite, fixture); - Assert.IsFalse( fixture.setupCalled, "TestFixtureSetUp called running fixture" ); - Assert.IsFalse( fixture.teardownCalled, "TestFixtureTearDown called running fixture" ); - - TestBuilder.RunTest(suite, fixture); - Assert.IsFalse( fixture.setupCalled, "TestFixtureSetUp called running enclosing suite" ); - Assert.IsFalse( fixture.teardownCalled, "TestFixtureTearDown called running enclosing suite" ); - - TestBuilder.RunTest(test, fixture); - Assert.IsFalse( fixture.setupCalled, "TestFixtureSetUp called running a test case" ); - Assert.IsFalse( fixture.teardownCalled, "TestFixtureTearDown called running a test case" ); - } - - [Test] - public void FixtureWithNoTestsShouldCallFixtureSetUpOrTearDown() - { - FixtureWithNoTests fixture = new FixtureWithNoTests(); - - TestBuilder.RunTestFixture(fixture); - - Assert.That( fixture.setupCalled, Is.True, "SetUp should be called for a fixture with no tests" ); - Assert.That( fixture.teardownCalled, Is.True, "TearDown should be called for a fixture with no tests" ); - } - - [Test] - public void DisposeCalledWhenFixtureImplementsIDisposable() - { - DisposableFixture fixture = new DisposableFixture(); - TestBuilder.RunTestFixture(fixture); - Assert.IsTrue(fixture.disposeCalled); - } - } - -#if !SILVERLIGHT && !NETCF - [TestFixture] - class ChangesMadeInFixtureSetUp - { - [TestFixtureSetUp] - public void TestFixtureSetUp() - { - GenericIdentity identity = new GenericIdentity("foo"); - Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); - - System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-GB"); - Thread.CurrentThread.CurrentCulture = culture; - Thread.CurrentThread.CurrentUICulture = culture; - } - - [Test] - public void TestThatChangesPersistUsingSameThread() - { - Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name); - Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentCulture.Name); - Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentUICulture.Name); - } - -#if !NUNITLITE - [Test, RequiresThread] - public void TestThatChangesPersistUsingSeparateThread() - { - Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name); - Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentCulture.Name); - Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentUICulture.Name); - } -#endif - } -#endif -} diff --git a/test/NUnitLite/src/tests/Attributes/MaxTimeTests.cs b/test/NUnitLite/src/tests/Attributes/MaxTimeTests.cs deleted file mode 100644 index 5af83bf37..000000000 --- a/test/NUnitLite/src/tests/Attributes/MaxTimeTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Tests -{ - /// - /// Tests for MaxTime decoration. - /// - [TestFixture] - public class MaxTimeTests - { - [Test,MaxTime(1000)] - public void MaxTimeNotExceeded() - { - } - - // TODO: We need a way to simulate the clock reliably - [Test] - public void MaxTimeExceeded() - { - ITestResult suiteResult = TestBuilder.RunTestFixture(typeof(MaxTimeFixture)); - Assert.AreEqual(ResultState.Failure, suiteResult.ResultState); - TestResult result = (TestResult)suiteResult.Children[0]; - Assert.That(result.Message, Contains.Substring("exceeds maximum of 1ms")); - } - - [Test, MaxTime(1000)] - [ExpectedException(typeof(AssertionException), ExpectedMessage = "Intentional Failure")] - public void FailureReport() - { - Assert.Fail("Intentional Failure"); - } - - [Test] - public void FailureReportHasPriorityOverMaxTime() - { - ITestResult result = TestBuilder.RunTestFixture(typeof(MaxTimeFixtureWithFailure)); - Assert.AreEqual(ResultState.Failure, result.ResultState); - result = (TestResult)result.Children[0]; - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.That(result.Message, Is.EqualTo("Intentional Failure")); - } - - [Test, MaxTime(1000), ExpectedException] - public void ErrorReport() - { - throw new Exception(); - } - - [Test] - public void ErrorReportHasPriorityOverMaxTime() - { - ITestResult result = TestBuilder.RunTestFixture(typeof(MaxTimeFixtureWithError)); - Assert.AreEqual(ResultState.Failure, result.ResultState); - result = (ITestResult)result.Children[0]; - Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.That(result.Message, Contains.Substring("Exception message")); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/PairwiseTests.cs b/test/NUnitLite/src/tests/Attributes/PairwiseTests.cs deleted file mode 100644 index b2bffafe6..000000000 --- a/test/NUnitLite/src/tests/Attributes/PairwiseTests.cs +++ /dev/null @@ -1,145 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework; -using NUnit.Framework.Builders; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class PairwiseTest - { - [TestFixture] - public class LiveTest - { - private PairCounter pairsTested = new PairCounter(); - - [TestFixtureSetUp] - public void TestFixtureSetUp() - { - pairsTested = new PairCounter(); - } - - [TestFixtureTearDown] - public void TestFixtureTearDown() - { - Assert.That(pairsTested.Count, Is.EqualTo(16)); - } - - [Test, Pairwise] - public void Test( - [Values("a", "b", "c")] string a, - [Values("+", "-")] string b, - [Values("x", "y")] string c) - { - Console.WriteLine("Pairwise: {0} {1} {2}", a, b, c); - - pairsTested[a + b] = null; - pairsTested[a + c] = null; - pairsTested[b + c] = null; - } - } - - // Test data is taken from various sources. See "Lessons Learned - // in Software Testing" pp 53-59, for example. For orthogonal cases, see - // http://www.freequality.org/sites/www_freequality_org/documents/tools/Tagarray_files/tamatrix.htm - static internal object[] cases = new object[] - { -#if ORIGINAL - new TestCaseData( new int[] { 2, 4 }, 8, 8 ).SetName("Test 2x4"), - new TestCaseData( new int[] { 2, 2, 2 }, 5, 4 ).SetName("Test 2x2x2"), - new TestCaseData( new int[] { 3, 2, 2 }, 6, 6 ).SetName("Test 3x2x2"), - new TestCaseData( new int[] { 3, 2, 2, 2 }, 7, 6 ).SetName("Test 3x2x2x2"), - new TestCaseData( new int[] { 3, 2, 2, 2, 2 }, 8, 6 ).SetName("Test 3x2x2x2x2"), - new TestCaseData( new int[] { 3, 2, 2, 2, 2, 2 }, 9, 8 ).SetName("Test 3x2x2x2x2x2"), - new TestCaseData( new int[] { 3, 3, 3 }, 12, 9 ).SetName("Test 3x3x3"), - new TestCaseData( new int[] { 4, 4, 4 }, 22, 16 ).SetName("Test 4x4x4"), - new TestCaseData( new int[] { 5, 5, 5 }, 34, 25 ).SetName("Test 5x5x5") -#else - new TestCaseData( new int[] { 2, 4 }, 8, 8 ).SetName("Test 2x4"), - new TestCaseData( new int[] { 2, 2, 2 }, 5, 4 ).SetName("Test 2x2x2"), - new TestCaseData( new int[] { 3, 2, 2 }, 7, 6 ).SetName("Test 3x2x2"), - new TestCaseData( new int[] { 3, 2, 2, 2 }, 8, 6 ).SetName("Test 3x2x2x2"), - new TestCaseData( new int[] { 3, 2, 2, 2, 2 }, 9, 6 ).SetName("Test 3x2x2x2x2"), - new TestCaseData( new int[] { 3, 2, 2, 2, 2, 2 }, 9, 8 ).SetName("Test 3x2x2x2x2x2"), - new TestCaseData( new int[] { 3, 3, 3 }, 9, 9 ).SetName("Test 3x3x3"), - new TestCaseData( new int[] { 4, 4, 4 }, 17, 16 ).SetName("Test 4x4x4"), - new TestCaseData( new int[] { 5, 5, 5 }, 27, 25 ).SetName("Test 5x5x5") -#endif - }; - - [Test, TestCaseSource("cases")] - public void Test(int[] dimensions, int bestSoFar, int targetCases) - { - int features = dimensions.Length; - - string[][] sources = new string[features][]; - - for (int i = 0; i < features; i++) - { - string featureName = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".Substring(i, 1); - - int n = dimensions[i]; - sources[i] = new string[n]; - for (int j = 0; j < n; j++) - sources[i][j] = featureName + j.ToString(); - } - - CombiningStrategy strategy = new PairwiseStrategy(sources); - - PairCounter pairs = new PairCounter(); - int cases = 0; - foreach (NUnit.Framework.Internal.ParameterSet parms in strategy.GetTestCases()) - { - for (int i = 1; i < features; i++) - for (int j = 0; j < i; j++) - { - string a = parms.Arguments[i] as string; - string b = parms.Arguments[j] as string; - pairs[a + b] = null; - } - - ++cases; - } - - int expectedPairs = 0; - for (int i = 1; i < features; i++) - for (int j = 0; j < i; j++) - expectedPairs += dimensions[i] * dimensions[j]; - - Assert.That(pairs.Count, Is.EqualTo(expectedPairs), "Number of pairs is incorrect"); - Assert.That(cases, Is.AtMost(bestSoFar), "Regression: Number of test cases exceeded target previously reached"); -#if DEBUG - //Assert.That(cases, Is.AtMost(targetCases), "Number of test cases exceeded target"); -#endif - } - -#if CLR_2_0 || CLR_4_0 - class PairCounter : System.Collections.Generic.Dictionary {} -#else - class PairCounter : Hashtable { } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/ParameterizedTestFixtureTests.cs b/test/NUnitLite/src/tests/Attributes/ParameterizedTestFixtureTests.cs deleted file mode 100644 index 2d12864ed..000000000 --- a/test/NUnitLite/src/tests/Attributes/ParameterizedTestFixtureTests.cs +++ /dev/null @@ -1,199 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - [TestFixture("hello", "hello", "goodbye")] - [TestFixture("zip", "zip")] - [TestFixture(42, 42, 99)] - public class ParameterizedTestFixture - { - private string eq1; - private string eq2; - private string neq; - - public ParameterizedTestFixture(string eq1, string eq2, string neq) - { - this.eq1 = eq1; - this.eq2 = eq2; - this.neq = neq; - } - - public ParameterizedTestFixture(string eq1, string eq2) - : this(eq1, eq2, null) { } - - public ParameterizedTestFixture(int eq1, int eq2, int neq) - { - this.eq1 = eq1.ToString(); - this.eq2 = eq2.ToString(); - this.neq = neq.ToString(); - } - - [Test] - public void TestEquality() - { - Assert.AreEqual(eq1, eq2); - if (eq1 != null && eq2 != null) - Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode()); - } - - [Test] - public void TestInequality() - { - Assert.AreNotEqual(eq1, neq); - if (eq1 != null && neq != null) - Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode()); - } - } - -#if DYNAMIC_DATA - [TestFixture(42)] - public class ParameterizedTestFixtureWithDataSources - { - private int answer; - - object[] myData = { new int[] { 6, 7 }, new int[] { 3, 14 } }; - - public ParameterizedTestFixtureWithDataSources(int val) - { - this.answer = val; - } - - [Test, TestCaseSource("myData")] - public void CanAccessTestCaseSource(int x, int y) - { - Assert.That(x * y, Is.EqualTo(answer)); - } - - IEnumerable GenerateData() - { - for(int i = 1; i <= answer; i++) - if ( answer%i == 0 ) - yield return new int[] { i, answer/i }; - } - - [Test, TestCaseSource("GenerateData")] - public void CanGenerateDataFromParameter(int x, int y) - { - Assert.That(x * y, Is.EqualTo(answer)); - } - - int[] intvals = new int[] { 1, 2, 3 }; - - [Test] - public void CanAccessValueSource( - [ValueSource("intvals")] int x) - { - Assert.That(answer % x == 0); - } - } -#endif - - public class ParameterizedTestFixtureNamingTests - { - TestSuite fixture; - - [SetUp] - public void MakeFixture() - { - fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.ParameterizedTestFixture)); - } - - [Test] - public void TopLevelSuiteIsNamedCorrectly() - { - Assert.That(fixture.Name, Is.EqualTo("ParameterizedTestFixture")); - Assert.That(fixture.FullName, Is.EqualTo("NUnit.TestData.ParameterizedTestFixture")); - } - - [Test] - public void SuiteHasCorrectNumberOfInstances() - { - Assert.That(fixture.Tests.Count, Is.EqualTo(2)); - } - - [Test] - public void FixtureInstancesAreNamedCorrectly() - { - string[] names = new string[fixture.Tests.Count]; - string[] fullnames = new string[fixture.Tests.Count]; - int index = 0; - foreach (Test test in fixture.Tests) - { - names[index] = test.Name; - fullnames[index] = test.FullName; - index++; - } - - Assert.That(names, Is.EquivalentTo(new string[] { - "ParameterizedTestFixture(1)", "ParameterizedTestFixture(2)" })); - Assert.That(fullnames, Is.EquivalentTo(new string[] { - "NUnit.TestData.ParameterizedTestFixture(1)", "NUnit.TestData.ParameterizedTestFixture(2)" })); - } - - [Test] - public void MethodWithoutParamsIsNamedCorrectly() - { - TestSuite instance = (TestSuite)fixture.Tests[0]; - Test method = TestFinder.Find("MethodWithoutParams", instance, false); - Assert.That(method, Is.Not.Null ); - Assert.That(method.FullName, Is.EqualTo(instance.FullName + ".MethodWithoutParams")); - } - - [Test] - public void MethodWithParamsIsNamedCorrectly() - { - TestSuite instance = (TestSuite)fixture.Tests[0]; - TestSuite method = (TestSuite)TestFinder.Find("MethodWithParams", instance, false); - Assert.That(method, Is.Not.Null); - - Test testcase = (Test)method.Tests[0]; - Assert.That(testcase.Name, Is.EqualTo("MethodWithParams(10,20)")); - Assert.That(testcase.FullName, Is.EqualTo(instance.FullName + ".MethodWithParams(10,20)")); - } - } - - public class ParameterizedTestFixtureTests - { - [Test] - public void CanSpecifyCategory() - { - Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithSingleCategory)); - Assert.AreEqual("XYZ", fixture.Properties.Get(PropertyNames.Category)); - } - - [Test] - public void CanSpecifyMultipleCategories() - { - Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithMultipleCategories)); - Assert.AreEqual(new string[] { "X", "Y", "Z" }, fixture.Properties[PropertyNames.Category]); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/PropertyAttributeTests.cs b/test/NUnitLite/src/tests/Attributes/PropertyAttributeTests.cs deleted file mode 100644 index e8025df07..000000000 --- a/test/NUnitLite/src/tests/Attributes/PropertyAttributeTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; -using NUnit.TestData.PropertyAttributeTests; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class PropertyAttributeTests - { - TestSuite fixture; - - [SetUp] - public void CreateFixture() - { - fixture = TestBuilder.MakeFixture( typeof( FixtureWithProperties ) ); - } - - [Test] - public void PropertyWithStringValue() - { - Test test1 = (Test)fixture.Tests[0]; - Assert.That( test1.Properties["user"].Contains("Charlie")); - } - - [Test] - public void PropertiesWithNumericValues() - { - Test test2 = (Test)fixture.Tests[1]; - Assert.AreEqual( 10.0, test2.Properties.Get("X") ); - Assert.AreEqual( 17.0, test2.Properties.Get("Y") ); - } - - [Test] - public void PropertyWorksOnFixtures() - { - Assert.AreEqual( "SomeClass", fixture.Properties.Get("ClassUnderTest") ); - } - - [Test] - public void CanDeriveFromPropertyAttribute() - { - Test test3 = (Test)fixture.Tests[2]; - Assert.AreEqual( 5, test3.Properties.Get("Priority") ); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/RepeatedTestTests.cs b/test/NUnitLite/src/tests/Attributes/RepeatedTestTests.cs deleted file mode 100644 index 34e4e9f5f..000000000 --- a/test/NUnitLite/src/tests/Attributes/RepeatedTestTests.cs +++ /dev/null @@ -1,115 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -#if false -using System; -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData.RepeatedTestFixture; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class RepeatedTestTests - { - private MethodInfo successMethod; - private MethodInfo failOnFirstMethod; - private MethodInfo failOnThirdMethod; - - [SetUp] - public void SetUp() - { - Type testType = typeof(RepeatSuccessFixture); - successMethod = testType.GetMethod ("RepeatSuccess"); - testType = typeof(RepeatFailOnFirstFixture); - failOnFirstMethod = testType.GetMethod("RepeatFailOnFirst"); - testType = typeof(RepeatFailOnThirdFixture); - failOnThirdMethod = testType.GetMethod("RepeatFailOnThird"); - } - - [Test] - public void RepeatSuccess() - { - Assert.IsNotNull (successMethod); - RepeatSuccessFixture fixture = new RepeatSuccessFixture(); - ITestResult result = TestBuilder.RunTestFixture(fixture); - - Assert.IsTrue(result.ResultState == ResultState.Success); - Assert.AreEqual(1, fixture.FixtureSetupCount); - Assert.AreEqual(1, fixture.FixtureTeardownCount); - Assert.AreEqual(3, fixture.SetupCount); - Assert.AreEqual(3, fixture.TeardownCount); - Assert.AreEqual(3, fixture.Count); - } - - [Test] - public void RepeatFailOnFirst() - { - Assert.IsNotNull (failOnFirstMethod); - RepeatFailOnFirstFixture fixture = new RepeatFailOnFirstFixture(); - ITestResult result = TestBuilder.RunTestFixture(fixture); - - Assert.IsFalse(result.ResultState == ResultState.Success); - Assert.AreEqual(1, fixture.SetupCount); - Assert.AreEqual(1, fixture.TeardownCount); - Assert.AreEqual(1, fixture.Count); - } - - [Test] - public void RepeatFailOnThird() - { - Assert.IsNotNull (failOnThirdMethod); - RepeatFailOnThirdFixture fixture = new RepeatFailOnThirdFixture(); - ITestResult result = TestBuilder.RunTestFixture(fixture); - - Assert.IsFalse(result.ResultState == ResultState.Success); - Assert.AreEqual(3, fixture.SetupCount); - Assert.AreEqual(3, fixture.TeardownCount); - Assert.AreEqual(3, fixture.Count); - } - - [Test] - public void IgnoreWorksWithRepeatedTest() - { - RepeatedTestWithIgnore fixture = new RepeatedTestWithIgnore(); - TestBuilder.RunTestFixture(fixture); - - Assert.AreEqual( 0, fixture.SetupCount ); - Assert.AreEqual( 0, fixture.TeardownCount ); - Assert.AreEqual( 0, fixture.Count ); - } - - [Test] - public void CategoryWorksWithRepeatedTest() - { - TestSuite suite = TestBuilder.MakeFixture(typeof(RepeatedTestWithCategory)); - Test test = suite.Tests[0] as Test; - System.Collections.IList categories = test.Properties["Category"]; - Assert.IsNotNull(categories); - Assert.AreEqual(1, categories.Count); - Assert.AreEqual("SAMPLE", categories[0]); - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Attributes/SetCultureAttributeTests.cs b/test/NUnitLite/src/tests/Attributes/SetCultureAttributeTests.cs deleted file mode 100644 index 84bd92cbb..000000000 --- a/test/NUnitLite/src/tests/Attributes/SetCultureAttributeTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Threading; -using System.Globalization; -using NUnit.Framework; -using NUnit.TestData.CultureAttributeData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class SetCultureAttributeTests - { - private CultureInfo originalCulture; - private CultureInfo originalUICulture; - - [SetUp] - public void Setup() - { - originalCulture = CultureInfo.CurrentCulture; - originalUICulture = CultureInfo.CurrentUICulture; - } - - [Test, SetUICulture("fr-FR")] - public void SetUICultureOnlyToFrench() - { - Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture should not change"); - Assert.AreEqual("fr-FR", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetUICulture("fr-CA")] - public void SetUICultureOnlyToFrenchCanadian() - { - Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture should not change"); - Assert.AreEqual("fr-CA", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetUICulture("ru-RU")] - public void SetUICultureOnlyToRussian() - { - Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture should not change"); - Assert.AreEqual("ru-RU", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetCulture("fr-FR"), SetUICulture("fr-FR")] - public void SetBothCulturesToFrench() - { - Assert.AreEqual("fr-FR", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("fr-FR", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetCulture("fr-CA"), SetUICulture("fr-CA")] - public void SetBothCulturesToFrenchCanadian() - { - Assert.AreEqual("fr-CA", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("fr-CA", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetCulture("ru-RU"), SetUICulture("ru-RU")] - public void SetBothCulturesToRussian() - { - Assert.AreEqual("ru-RU", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("ru-RU", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetCulture("fr-FR"), SetUICulture("fr-CA")] - public void SetMixedCulturesToFrenchAndUIFrenchCanadian() - { - Assert.AreEqual("fr-FR", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("fr-CA", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetCulture("ru-RU"), SetUICulture("en-US")] - public void SetMixedCulturesToRussianAndUIEnglishUS() - { - Assert.AreEqual("ru-RU", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("en-US", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [TestFixture, SetCulture("ru-RU"), SetUICulture("ru-RU")] - public class NestedBehavior - { - [Test] - public void InheritedRussian() - { - Assert.AreEqual("ru-RU", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("ru-RU", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - - [Test, SetUICulture("fr-FR")] - public void InheritedRussianWithUIFrench() - { - Assert.AreEqual("ru-RU", CultureInfo.CurrentCulture.Name, "Culture not set correctly"); - Assert.AreEqual("fr-FR", CultureInfo.CurrentUICulture.Name, "UICulture not set correctly"); - } - } - -#if CLR_2_0 || CLR_4_0 - [Test, SetCulture("de-DE")] - [TestCase(ExpectedResult="01.06.2010 00:00:00")] - public string UseWithParameterizedTest() - { - return new DateTime(2010, 6, 1).ToString(); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/TestCaseAttributeTests.cs b/test/NUnitLite/src/tests/Attributes/TestCaseAttributeTests.cs deleted file mode 100644 index 0aa5c8aed..000000000 --- a/test/NUnitLite/src/tests/Attributes/TestCaseAttributeTests.cs +++ /dev/null @@ -1,322 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData.TestCaseAttributeFixture; -using NUnit.TestUtilities; -using System.Collections; - -namespace NUnit.Framework.Tests -{ - [TestFixture] - public class TestCaseAttributeTests - { - [TestCase(12, 3, 4)] - [TestCase(12, 2, 6)] - [TestCase(12, 4, 3)] - [TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException))] - [TestCase(12, 0, 0, ExpectedExceptionName = "System.DivideByZeroException")] - public void IntegerDivisionWithResultPassedToTest(int n, int d, int q) - { - Assert.AreEqual(q, n / d); - } - - [TestCase(12, 3, ExpectedResult = 4)] - [TestCase(12, 2, ExpectedResult = 6)] - [TestCase(12, 4, ExpectedResult = 3)] - [TestCase(12, 0, ExpectedException = typeof(System.DivideByZeroException))] - [TestCase(12, 0, ExpectedExceptionName = "System.DivideByZeroException", - TestName = "DivisionByZeroThrowsException")] - public int IntegerDivisionWithResultCheckedByNUnit(int n, int d) - { - return n / d; - } - - [TestCase(2, 2, ExpectedResult=4)] - public double CanConvertIntToDouble(double x, double y) - { - return x + y; - } - - [TestCase("2.2", "3.3", ExpectedResult = 5.5)] - public decimal CanConvertStringToDecimal(decimal x, decimal y) - { - return x + y; - } - - [TestCase(2.2, 3.3, ExpectedResult = 5.5)] - public decimal CanConvertDoubleToDecimal(decimal x, decimal y) - { - return x + y; - } - - [TestCase(5, 2, ExpectedResult = 7)] - public decimal CanConvertIntToDecimal(decimal x, decimal y) - { - return x + y; - } - - [TestCase(5, 2, ExpectedResult = 7)] - public short CanConvertSmallIntsToShort(short x, short y) - { - return (short)(x + y); - } - - [TestCase(5, 2, ExpectedResult = 7)] - public byte CanConvertSmallIntsToByte(byte x, byte y) - { - return (byte)(x + y); - } - - [TestCase(5, 2, ExpectedResult = 7)] - public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y) - { - return (sbyte)(x + y); - } - - [Test] - public void ConversionOverflowMakesTestNotRunnable() - { - Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( - typeof(TestCaseAttributeFixture), "MethodCausesConversionOverflow").Tests[0]; - Assert.AreEqual(RunState.NotRunnable, test.RunState); - } - - [TestCase("12-October-1942")] - public void CanConvertStringToDateTime(DateTime dt) - { - Assert.AreEqual(1942, dt.Year); - } - - [TestCase(42, ExpectedException = typeof(System.Exception), - ExpectedMessage = "Test Exception")] - public void CanSpecifyExceptionMessage(int a) - { - throw new System.Exception("Test Exception"); - } - - [TestCase(42, ExpectedException = typeof(System.Exception), - ExpectedMessage = "Test Exception", - MatchType=MessageMatch.StartsWith)] - public void CanSpecifyExceptionMessageAndMatchType(int a) - { - throw new System.Exception("Test Exception thrown here"); - } - -#if CLR_2_0 || CLR_4_0 - [TestCase(null)] - public void CanPassNullAsFirstArgument(object a) - { - Assert.IsNull(a); - } -#endif - - [TestCase(new object[] { 1, "two", 3.0 })] - [TestCase(new object[] { "zip" })] - public void CanPassObjectArrayAsFirstArgument(object[] a) - { - } - - [TestCase(new object[] { "a", "b" })] - public void CanPassArrayAsArgument(object[] array) - { - Assert.AreEqual("a", array[0]); - Assert.AreEqual("b", array[1]); - } - - [TestCase("a", "b")] - public void ArgumentsAreCoalescedInObjectArray(object[] array) - { - Assert.AreEqual("a", array[0]); - Assert.AreEqual("b", array[1]); - } - - [TestCase(1, "b")] - public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array) - { - Assert.AreEqual(1, array[0]); - Assert.AreEqual("b", array[1]); - } - -#if CLR_2_0 || CLR_4_0 - [TestCase(ExpectedResult = null)] - public object ResultCanBeNull() - { - return null; - } -#endif - - [TestCase("a", "b")] - public void HandlesParamsArrayAsSoleArgument(params string[] array) - { - Assert.AreEqual("a", array[0]); - Assert.AreEqual("b", array[1]); - } - - [TestCase("a")] - public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array) - { - Assert.AreEqual("a", array[0]); - } - - [TestCase("a", "b", "c", "d")] - public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array) - { - Assert.AreEqual("a", s1); - Assert.AreEqual("b", s2); - Assert.AreEqual("c", array[0]); - Assert.AreEqual("d", array[1]); - } - - [TestCase("a", "b")] - public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array) - { - Assert.AreEqual("a", s1); - Assert.AreEqual("b", s2); - Assert.AreEqual(0, array.Length); - } - - [TestCase("a", "b", "c")] - public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array) - { - Assert.AreEqual("a", s1); - Assert.AreEqual("b", s2); - Assert.AreEqual("c", array[0]); - } - - [Test] - public void CanSpecifyDescription() - { - Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( - typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0]; - Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description)); - } - - [Test] - public void CanSpecifyTestName() - { - Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( - typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified").Tests[0]; - Assert.AreEqual("XYZ", test.Name); - Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName); - } - - [Test] - public void CanSpecifyCategory() - { - Test test = (Test)TestBuilder.MakeTestCase( - typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0]; - IList categories = test.Properties["Category"]; - Assert.AreEqual(new string[] { "XYZ" }, categories); - } - - [Test] - public void CanSpecifyMultipleCategories() - { - Test test = (Test)TestBuilder.MakeTestCase( - typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0]; - IList categories = test.Properties["Category"]; - Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories); - } - - [Test] - public void CanSpecifyExpectedException() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseAttributeFixture), "MethodThrowsExpectedException").Children[0]; - Assert.AreEqual(ResultState.Success, result.ResultState); - } - - [Test] - public void CanSpecifyExpectedException_WrongException() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseAttributeFixture), "MethodThrowsWrongException").Children[0]; - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.That(result.Message, Is.StringStarting("An unexpected exception type was thrown")); - } - - [Test] - public void CanSpecifyExpectedException_WrongMessage() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseAttributeFixture), "MethodThrowsExpectedExceptionWithWrongMessage").Children[0]; - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.That(result.Message, Is.StringStarting("The exception message text was incorrect")); - } - - [Test] - public void CanSpecifyExpectedException_NoneThrown() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseAttributeFixture), "MethodThrowsNoException").Children[0]; - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.AreEqual("System.ArgumentNullException was expected", result.Message); - } - - [Test] - public void IgnoreTakesPrecedenceOverExpectedException() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseAttributeFixture), "MethodCallsIgnore").Children[0]; - Assert.AreEqual(ResultState.Ignored, result.ResultState); - Assert.AreEqual("Ignore this", result.Message); - } - - [Test] - public void CanIgnoreIndividualTestCases() - { - TestSuite test = (TestSuite)TestBuilder.MakeTestCase( - typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases"); - - Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); - - testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); - - testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); - Assert.That(testCase.Properties.GetSetting(PropertyNames.SkipReason, ""), Is.EqualTo("Don't Run Me!")); - } - - [Test] - public void CanMarkIndividualTestCasesExplicit() - { - TestSuite test = (TestSuite)TestBuilder.MakeTestCase( - typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases"); - - Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); - - testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); - - testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); - Assert.That(testCase.Properties.GetSetting(PropertyNames.SkipReason, ""), Is.EqualTo("Connection failing")); - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/TestCaseSourceTests.cs b/test/NUnitLite/src/tests/Attributes/TestCaseSourceTests.cs deleted file mode 100644 index 8402c0350..000000000 --- a/test/NUnitLite/src/tests/Attributes/TestCaseSourceTests.cs +++ /dev/null @@ -1,354 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.Collections; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData.TestCaseSourceAttributeFixture; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Tests -{ - [TestFixture] - public class TestCaseSourceTests - { - [Test, TestCaseSource("StaticProperty")] - public void SourceCanBeStaticProperty(string source) - { - Assert.AreEqual("StaticProperty", source); - } - - internal static IEnumerable StaticProperty - { - get { return new object[] { new object[] { "StaticProperty" } }; } - } - - [Test, TestCaseSource("InstanceProperty")] - public void SourceCanBeInstanceProperty(string source) - { - Assert.AreEqual("InstanceProperty", source); - } - - internal IEnumerable InstanceProperty - { - get { return new object[] { new object[] { "InstanceProperty" } }; } - } - - [Test, TestCaseSource("StaticMethod")] - public void SourceCanBeStaticMethod(string source) - { - Assert.AreEqual("StaticMethod", source); - } - - internal static IEnumerable StaticMethod() - { - return new object[] { new object[] { "StaticMethod" } }; - } - - [Test, TestCaseSource("InstanceMethod")] - public void SourceCanBeInstanceMethod(string source) - { - Assert.AreEqual("InstanceMethod", source); - } - - internal IEnumerable InstanceMethod() - { - return new object[] { new object[] { "InstanceMethod" } }; - } - - [Test, TestCaseSource("StaticField")] - public void SourceCanBeStaticField(string source) - { - Assert.AreEqual("StaticField", source); - } - - internal static object[] StaticField = - { new object[] { "StaticField" } }; - - [Test, TestCaseSource("InstanceField")] - public void SourceCanBeInstanceField(string source) - { - Assert.AreEqual("InstanceField", source); - } - - internal static object[] InstanceField = - { new object[] { "InstanceField" } }; - -#if CLR_2_0 || CLR_4_0 - [Test, TestCaseSource(typeof(DataSourceClass))] - public void SourceCanBeInstanceOfIEnumerable(string source) - { - Assert.AreEqual("DataSourceClass", source); - } - - internal class DataSourceClass : IEnumerable - { - public IEnumerator GetEnumerator() - { - yield return "DataSourceClass"; - } - } -#endif - - [Test, TestCaseSource("MyData")] - public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q) - { - Assert.AreEqual(q, n / d); - } - - [TestCaseSource("MyData")] - public void TestAttributeIsOptional(int n, int d, int q) - { - Assert.AreEqual(q, n / d); - } - - [Test, TestCaseSource("MyIntData")] - public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q) - { - Assert.AreEqual(q, n / d); - } - - [Test, TestCaseSource("EvenNumbers")] - public void SourceMayReturnSinglePrimitiveArgumentAlone(int n) - { - Assert.AreEqual(0, n % 2); - } - - [Test, TestCaseSource("Params")] - public int SourceMayReturnArgumentsAsParamSet(int n, int d) - { - return n / d; - } - - [Test] - [TestCaseSource("MyData")] - [TestCaseSource("MoreData", Category="Extra")] - [TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException))] - public void TestMayUseMultipleSourceAttributes(int n, int d, int q) - { - Assert.AreEqual(q, n / d); - } - - [Test, TestCaseSource("FourArgs")] - public void TestWithFourArguments(int n, int d, int q, int r) - { - Assert.AreEqual(q, n / d); - Assert.AreEqual(r, n % d); - } - -#if CLR_2_0 || CLR_4_0 - [Test, TestCaseSource(typeof(DivideDataProvider), "HereIsTheData")] - //[Category("Top")] - public void SourceMayBeInAnotherClass(int n, int d, int q) - { - Assert.AreEqual(q, n / d); - } -#endif - - [Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), "TestCases")] - public int SourceMayBeInAnotherClassWithReturn(int n, int d) - { - return n / d; - } - - [Test] - public void CanSpecifyExpectedException() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseSourceAttributeFixture), "MethodThrowsExpectedException").Children[0]; - Assert.AreEqual(ResultState.Success, result.ResultState); - } - - [Test] - public void CanSpecifyExpectedException_WrongException() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseSourceAttributeFixture), "MethodThrowsWrongException").Children[0]; - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.That(result.Message, Is.StringStarting("An unexpected exception type was thrown")); - } - - [Test] - public void CanSpecifyExpectedException_NoneThrown() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseSourceAttributeFixture), "MethodThrowsNoException").Children[0]; - Assert.AreEqual(ResultState.Failure, result.ResultState); - Assert.AreEqual("System.ArgumentNullException was expected", result.Message); - } - - [Test] - public void IgnoreTakesPrecedenceOverExpectedException() - { - ITestResult result = (ITestResult)TestBuilder.RunTestCase( - typeof(TestCaseSourceAttributeFixture), "MethodCallsIgnore").Children[0]; - Assert.AreEqual(ResultState.Ignored, result.ResultState); - Assert.AreEqual("Ignore this", result.Message); - } - - [Test] - public void CanIgnoreIndividualTestCases() - { - TestSuite test = (TestSuite)TestBuilder.MakeTestCase( - typeof(TestCaseSourceAttributeFixture), "MethodWithIgnoredTestCases"); - - Test testCase = TestFinder.MustFind("MethodWithIgnoredTestCases(1)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); - - testCase = TestFinder.MustFind("MethodWithIgnoredTestCases(2)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); - - testCase = TestFinder.MustFind("MethodWithIgnoredTestCases(3)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); - Assert.That(testCase.Properties.GetSetting(PropertyNames.SkipReason, ""), Is.EqualTo("Don't Run Me!")); - } - - [Test] - public void CanMarkIndividualTestCasesExplicit() - { - TestSuite test = (TestSuite)TestBuilder.MakeTestCase( - typeof(TestCaseSourceAttributeFixture), "MethodWithExplicitTestCases"); - - Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); - - testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); - - testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", test, false); - Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); - Assert.That(testCase.Properties.GetSetting(PropertyNames.SkipReason, ""), Is.EqualTo("Connection failing")); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void HandlesExceptionInTestCaseSource() - { - Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( - typeof(TestCaseSourceAttributeFixture), "MethodWithSourceThrowingException").Tests[0]; - Assert.AreEqual(RunState.NotRunnable, test.RunState); - ITestResult result = TestBuilder.RunTest(test, null); - Assert.AreEqual(ResultState.NotRunnable, result.ResultState); - Assert.AreEqual("System.Exception : my message", result.Message); - } -#endif - -#if !NUNITLITE - [TestCaseSource("exception_source"), Explicit] - public void HandlesExceptioninTestCaseSource_GuiDisplay(string lhs, string rhs) - { - Assert.AreEqual(lhs, rhs); - } -#endif - - internal object[] testCases = - { - new TestCaseData( - new string[] { "A" }, - new string[] { "B" }) - }; - - [Test, TestCaseSource("testCases")] - public void MethodTakingTwoStringArrays(string[] a, string[] b) - { - Assert.That(a, Is.TypeOf(typeof(string[]))); - Assert.That(b, Is.TypeOf(typeof(string[]))); - } - - #region Sources used by the tests - internal static object[] MyData = new object[] { - new object[] { 12, 3, 4 }, - new object[] { 12, 4, 3 }, - new object[] { 12, 6, 2 } }; - - internal static object[] MyIntData = new object[] { - new int[] { 12, 3, 4 }, - new int[] { 12, 4, 3 }, - new int[] { 12, 6, 2 } }; - - internal static object[] FourArgs = new object[] { - new TestCaseData( 12, 3, 4, 0 ), - new TestCaseData( 12, 4, 3, 0 ), - new TestCaseData( 12, 5, 2, 2 ) }; - - internal static int[] EvenNumbers = new int[] { 2, 4, 6, 8 }; - - internal static object[] MoreData = new object[] { - new object[] { 12, 1, 12 }, - new object[] { 12, 2, 6 } }; - - internal static object[] Params = new object[] { - new TestCaseData(24, 3).Returns(8), - new TestCaseData(24, 2).Returns(12) }; - -#if CLR_2_0 || CLR_4_0 - public class DivideDataProvider - { - public static IEnumerable HereIsTheData - { - get - { - yield return new TestCaseData(0, 0, 0) - .SetName("ThisOneShouldThrow") - .SetDescription("Demonstrates use of ExpectedException") - .SetCategory("Junk") - .SetProperty("MyProp", "zip") - .Throws(typeof(System.DivideByZeroException)); - yield return new object[] { 100, 20, 5 }; - yield return new object[] { 100, 4, 25 }; - } - } - } -#endif - - public class DivideDataProviderWithReturnValue - { - public static IEnumerable TestCases - { - get - { - return new object[] { - new TestCaseData(12, 3).Returns(5).Throws(typeof(AssertionException)).SetName("TC1"), - new TestCaseData(12, 2).Returns(6).SetName("TC2"), - new TestCaseData(12, 4).Returns(3).SetName("TC3") - }; - } - } - } - -#if CLR_2_0 || CLR_4_0 - internal static IEnumerable exception_source - { - get - { - yield return new TestCaseData("a", "a"); - yield return new TestCaseData("b", "b"); - - throw new System.Exception("my message"); - } - } -#endif - - #endregion - } -} diff --git a/test/NUnitLite/src/tests/Attributes/TestDummy.cs b/test/NUnitLite/src/tests/Attributes/TestDummy.cs deleted file mode 100644 index c178c6e89..000000000 --- a/test/NUnitLite/src/tests/Attributes/TestDummy.cs +++ /dev/null @@ -1,83 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Attributes -{ - public class TestDummy : Test - { - public TestDummy() : base("TestDummy") { } - - #region Overrides - - public string TestKind - { - get { return "dummy-test"; } - } - - public override Internal.WorkItems.WorkItem CreateWorkItem(ITestFilter childFilter) - { - throw new NotImplementedException(); - } - - public override bool HasChildren - { - get - { - return false; - } - } - -#if CLR_2_0 || CLR_4_0 - public override System.Collections.Generic.IList Tests -#else - public override System.Collections.IList Tests -#endif - { - get - { - return new ITest[0]; - } - } - - public override XmlNode AddToXml(XmlNode parentNode, bool recursive) - { - throw new NotImplementedException(); - } - - public override TestResult MakeTestResult() - { - throw new NotImplementedException(); - } - - public override string XmlElementName - { - get { throw new NotImplementedException(); } - } - - #endregion - } -} diff --git a/test/NUnitLite/src/tests/Attributes/TestFixtureAttributeTests.cs b/test/NUnitLite/src/tests/Attributes/TestFixtureAttributeTests.cs deleted file mode 100644 index be81aaea1..000000000 --- a/test/NUnitLite/src/tests/Attributes/TestFixtureAttributeTests.cs +++ /dev/null @@ -1,92 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Attributes -{ - public class TestFixtureAttributeTests - { - static object[] fixtureArgs = new object[] { 10, 20, "Charlie" }; -#if CLR_2_0 || CLR_4_0 - static Type[] typeArgs = new Type[] { typeof(int), typeof(string) }; - static object[] combinedArgs = new object[] { typeof(int), typeof(string), 10, 20, "Charlie" }; -#endif - - [Test] - public void ConstructWithoutArguments() - { - TestFixtureAttribute attr = new TestFixtureAttribute(); - Assert.That(attr.Arguments.Length == 0); -#if CLR_2_0 || CLR_4_0 - Assert.That(attr.TypeArgs.Length == 0); -#endif - } - - [Test] - public void ConstructWithFixtureArgs() - { - TestFixtureAttribute attr = new TestFixtureAttribute(fixtureArgs); - Assert.That(attr.Arguments, Is.EqualTo( fixtureArgs ) ); -#if CLR_2_0 || CLR_4_0 - Assert.That(attr.TypeArgs.Length == 0 ); -#endif - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void ConstructWithJustTypeArgs() - { - TestFixtureAttribute attr = new TestFixtureAttribute(typeArgs); - Assert.That(attr.Arguments.Length == 0); - Assert.That(attr.TypeArgs, Is.EqualTo(typeArgs)); - } - - [Test] - public void ConstructWithNoArgumentsAndSetTypeArgs() - { - TestFixtureAttribute attr = new TestFixtureAttribute(); - attr.TypeArgs = typeArgs; - Assert.That(attr.Arguments.Length == 0); - Assert.That(attr.TypeArgs, Is.EqualTo(typeArgs)); - } - - [Test] - public void ConstructWithFixtureArgsAndSetTypeArgs() - { - TestFixtureAttribute attr = new TestFixtureAttribute(fixtureArgs); - attr.TypeArgs = typeArgs; - Assert.That(attr.Arguments, Is.EqualTo(fixtureArgs)); - Assert.That(attr.TypeArgs, Is.EqualTo(typeArgs)); - } - - [Test] - public void ConstructWithCombinedArgs() - { - TestFixtureAttribute attr = new TestFixtureAttribute(combinedArgs); - Assert.That(attr.Arguments, Is.EqualTo(fixtureArgs)); - Assert.That(attr.TypeArgs, Is.EqualTo(typeArgs)); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/TheoryTests.cs b/test/NUnitLite/src/tests/Attributes/TheoryTests.cs deleted file mode 100644 index 30ad0e3a6..000000000 --- a/test/NUnitLite/src/tests/Attributes/TheoryTests.cs +++ /dev/null @@ -1,163 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; -using NUnit.TestData.TheoryFixture; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Tests -{ - public class TheoryTests - { - static readonly Type fixtureType = typeof(TheoryFixture); - - [Test] - public void TheoryWithNoArgumentsIsTreatedAsTest() - { - TestAssert.IsRunnable(fixtureType, "TheoryWithNoArguments", ResultState.Success); - } - - [Test] - public void TheoryWithNoDatapointsIsNotRunnable() - { - TestAssert.IsNotRunnable(fixtureType, "TheoryWithArgumentsButNoDatapoints"); - } - - [Test] - public void TheoryWithDatapointsIsRunnable() - { - Test test = TestBuilder.MakeTestCase(fixtureType, "TheoryWithArgumentsAndDatapoints"); - TestAssert.IsRunnable(test); - Assert.That(test.TestCaseCount, Is.EqualTo(9)); - } - - [Test] - public void BooleanArgumentsAreSuppliedAutomatically() - { - Test test = TestBuilder.MakeTestCase(fixtureType, "TestWithBooleanArguments"); - TestAssert.IsRunnable(test); - Assert.That(test.TestCaseCount, Is.EqualTo(4)); - } - - [Datapoint] - internal object nullObj = null; - - [Theory] - public void NullDatapointIsOK(object o) - { - Assert.Null(o); - Assert.Null(nullObj); // to avoid a warning - } - - - [Test] - public void EnumArgumentsAreSuppliedAutomatically() - { - Test test = TestBuilder.MakeTestCase(fixtureType, "TestWithEnumAsArgument"); - TestAssert.IsRunnable(test); -#if CLR_2_0 || CLR_4_0 - Assert.That(test.TestCaseCount, Is.EqualTo(16)); -#else - Assert.That(test.TestCaseCount, Is.EqualTo(15)); // No GenericParameter member -#endif - Assert.That(test.TestCaseCount, Is.EqualTo(TypeHelper.GetEnumValues(typeof(AttributeTargets)).Length)); - } - - [Theory] - public void SquareRootWithAllGoodValues( - [Values(12.0, 4.0, 9.0)] double d) - { - SquareRootTest(d); - } - - [Theory] - public void SquareRootWithOneBadValue( - [Values(12.0, -4.0, 9.0)] double d) - { - SquareRootTest(d); - } - - [Datapoints] - internal string[] vals = new string[] { "xyz1", "xyz2", "xyz3" }; - - [Theory] - public void ArrayWithDatapointsAttributeIsUsed(string s) - { - Assert.That(s.StartsWith("xyz")); - } - - private static void SquareRootTest(double d) - { - Assume.That(d > 0); - double root = Math.Sqrt(d); - Assert.That(root * root, Is.EqualTo(d).Within(0.000001)); - Assert.That(root > 0); - } - - [Test] - public void SimpleTestIgnoresDataPoints() - { - Test test = TestBuilder.MakeTestCase(fixtureType, "TestWithArguments"); - Assert.That(test.TestCaseCount, Is.EqualTo(2)); - } - - [Theory] - public void TheoryFailsIfAllTestsAreInconclusive() - { - ITestResult result = TestBuilder.RunTestCase(fixtureType, "TestWithAllBadValues"); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); - Assert.That(result.Message, Is.EqualTo("All test cases were inconclusive")); - } - - public class SqrtTests - { - [Datapoint] - public double zero = 0; - - [Datapoint] - public double positive = 1; - - [Datapoint] - public double negative = -1; - - [Datapoint] - public double max = double.MaxValue; - - [Datapoint] - public double infinity = double.PositiveInfinity; - - [Theory] - public void SqrtTimesItselfGivesOriginal(double num) - { - Assume.That(num >= 0.0 && num < double.MaxValue); - - double sqrt = Math.Sqrt(num); - - Assert.That(sqrt >= 0.0); - Assert.That(sqrt * sqrt, Is.EqualTo(num).Within(0.000001)); - } - } - } -} diff --git a/test/NUnitLite/src/tests/Attributes/TimeoutTests.cs b/test/NUnitLite/src/tests/Attributes/TimeoutTests.cs deleted file mode 100644 index 165aa5e1d..000000000 --- a/test/NUnitLite/src/tests/Attributes/TimeoutTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if (CLR_2_0 || CLR_4_0) -using System; -using System.Threading; -using NUnit.Framework; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; -using NUnit.TestData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - public class TimeoutTests - { - Thread parentThread; - Thread setupThread; - - [TestFixtureSetUp] - public void GetParentThreadInfo() - { - this.parentThread = Thread.CurrentThread; - } - - [SetUp] - public void GetSetUpThreadInfo() - { - this.setupThread = Thread.CurrentThread; - } - - [Test, Timeout(50)] - public void TestWithTimeoutRunsOnSeparateThread() - { - Assert.That(Thread.CurrentThread, Is.Not.EqualTo(parentThread)); - } - - [Test, Timeout(50)] - public void TestWithTimeoutRunsSetUpAndTestOnSameThread() - { - Assert.That(Thread.CurrentThread, Is.EqualTo(setupThread)); - } - - [Test] - [Platform(Exclude = "Mono", Reason = "Runner hangs at end when this is run")] - [Platform(Exclude = "Net-1.1,Net-1.0", Reason = "Cancels the run when executed")] - public void TestWithInfiniteLoopTimesOut() - { - TimeoutFixture fixture = new TimeoutFixture(); - TestSuite suite = TestBuilder.MakeFixture(fixture); - Test test = TestFinder.Find("InfiniteLoopWith50msTimeout", suite, false); - ITestResult result = TestBuilder.RunTest(test, fixture); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); - Assert.That(result.Message, Contains.Substring("50ms")); - Assert.That(fixture.TearDownWasRun, "TearDown was not run"); - } - - [Test] - [Platform(Exclude = "Mono", Reason = "Runner hangs at end when this is run")] - public void TimeoutCanBeSetOnTestFixture() - { - TestResult suiteResult = TestBuilder.RunTestFixture(typeof(ThreadingFixtureWithTimeout)); - Assert.That(suiteResult.ResultState, Is.EqualTo(ResultState.Failure)); - Assert.That(suiteResult.Message, Is.EqualTo("One or more child tests had errors")); - ITestResult result = TestFinder.Find("Test2WithInfiniteLoop", suiteResult, false); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); - Assert.That(result.Message, Contains.Substring("50ms")); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Attributes/ValueSourceTests.cs b/test/NUnitLite/src/tests/Attributes/ValueSourceTests.cs deleted file mode 100644 index 0d5bd8d23..000000000 --- a/test/NUnitLite/src/tests/Attributes/ValueSourceTests.cs +++ /dev/null @@ -1,142 +0,0 @@ -// **************************************************************** -// Copyright 2009, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Attributes -{ - [TestFixture] - public class ValueSourceTests - { -#if CLR_2_0 || CLR_4_0 - [Test] - public void ValueSourceCanBeStaticProperty( - [ValueSource("StaticProperty")] string source) - { - Assert.AreEqual("StaticProperty", source); - } - - internal static IEnumerable StaticProperty - { - get - { - yield return "StaticProperty"; - } - } -#endif - - [Test] - public void ValueSourceCanBeInstanceProperty( - [ValueSource("InstanceProperty")] string source) - { - Assert.AreEqual("InstanceProperty", source); - } - - internal IEnumerable InstanceProperty - { - get { return new object[] { "InstanceProperty" }; } - } - - [Test] - public void ValueSourceCanBeStaticMethod( - [ValueSource("StaticMethod")] string source) - { - Assert.AreEqual("StaticMethod", source); - } - - internal static IEnumerable StaticMethod() - { - return new object[] { "StaticMethod" }; - } - - [Test] - public void ValueSourceCanBeInstanceMethod( - [ValueSource("InstanceMethod")] string source) - { - Assert.AreEqual("InstanceMethod", source); - } - - internal IEnumerable InstanceMethod() - { - return new object[] { "InstanceMethod" }; - } - - [Test] - public void ValueSourceCanBeStaticField( - [ValueSource("StaticField")] string source) - { - Assert.AreEqual("StaticField", source); - } - - internal static object[] StaticField = { "StaticField" }; - - [Test] - public void ValueSourceCanBeInstanceField( - [ValueSource("InstanceField")] string source) - { - Assert.AreEqual("InstanceField", source); - } - - internal object[] InstanceField = { "InstanceField" }; - - [Test, Sequential] - public void MultipleArguments( - [ValueSource("Numerators")] int n, - [ValueSource("Denominators")] int d, - [ValueSource("Quotients")] int q) - { - Assert.AreEqual(q, n / d); - } - - internal static int[] Numerators = new int[] { 12, 12, 12 }; - internal static int[] Denominators = new int[] { 3, 4, 6 }; - internal static int[] Quotients = new int[] { 4, 3, 2 }; - - [Test, Sequential] - public void ValueSourceMayBeInAnotherClass( - [ValueSource(typeof(DivideDataProvider), "Numerators")] int n, - [ValueSource(typeof(DivideDataProvider), "Denominators")] int d, - [ValueSource(typeof(DivideDataProvider), "Quotients")] int q) - { - Assert.AreEqual(q, n / d); - } - - public class DivideDataProvider - { - internal static int[] Numerators = new int[] { 12, 12, 12 }; - internal static int[] Denominators = new int[] { 3, 4, 6 }; - internal static int[] Quotients = new int[] { 4, 3, 2 }; - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void ValueSourceMayBeGeneric( - [ValueSourceAttribute(typeof(ValueProvider), "IntegerProvider")] int val) - { - Assert.That(2 * val, Is.EqualTo(val + val)); - } - - public class ValueProvider - { - public IEnumerable IntegerProvider() - { - List dataList = new List(); - - dataList.Add(1); - dataList.Add(2); - dataList.Add(4); - dataList.Add(8); - - return dataList; - } - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Attributes/ValuesAttributeTests.cs b/test/NUnitLite/src/tests/Attributes/ValuesAttributeTests.cs deleted file mode 100644 index 57e3bcbaa..000000000 --- a/test/NUnitLite/src/tests/Attributes/ValuesAttributeTests.cs +++ /dev/null @@ -1,157 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; - -namespace NUnit.Framework.Attributes -{ - public class ValuesAttributeTests - { - [Test] - public void ValuesAttributeProvidesSpecifiedValues() - { - CheckValues("MethodWithValues", 1, 2, 3); - } - - private void MethodWithValues( [Values(1, 2, 3)] int x) { } - - [Test] - public void CanConvertSmallIntsToShort([Values(5)]short x) - { - } - - [Test] - public void CanConvertSmallIntsToByte([Values(5)]byte x) - { - } - - [Test] - public void CanConvertSmallIntsToSByte([Values(5)]sbyte x) - { - } - - [Test] - public void CanConvertIntToDecimal([Values(12)]decimal x) - { - } - - [Test] - public void CanConverDoubleToDecimal([Values(12.5)]decimal x) - { - } - - [Test] - public void CanConvertStringToDecimal([Values("12.5")]decimal x) - { - } - - [Test] - public void RangeAttributeWithIntRange() - { - CheckValues("MethodWithIntRange", 11, 12, 13, 14, 15); - } - - private void MethodWithIntRange([Range(11, 15)] int x) { } - - [Test] - public void RangeAttributeWithIntRangeAndStep() - { - CheckValues("MethodWithIntRangeAndStep", 11, 13, 15); - } - - private void MethodWithIntRangeAndStep([Range(11, 15, 2)] int x) { } - - [Test] - public void RangeAttributeWithLongRangeAndStep() - { - CheckValues("MethodWithLongRangeAndStep", 11L, 13L, 15L); - } - - private void MethodWithLongRangeAndStep([Range(11L, 15L, 2)] long x) { } - - [Test] - public void RangeAttributeWithDoubleRangeAndStep() - { - CheckValuesWithinTolerance("MethodWithDoubleRangeAndStep", 0.7, 0.9, 1.1); - } - - private void MethodWithDoubleRangeAndStep([Range(0.7, 1.2, 0.2)] double x) { } - - [Test] - public void RangeAttributeWithFloatRangeAndStep() - { - CheckValuesWithinTolerance("MethodWithFloatRangeAndStep", 0.7f, 0.9f, 1.1f); - } - - private void MethodWithFloatRangeAndStep([Range(0.7f, 1.2f, 0.2f)] float x) { } - - [Test] - public void CanConvertIntRangeToShort([Range(1, 3)] short x) { } - - [Test] - public void CanConvertIntRangeToByte([Range(1, 3)] byte x) { } - - [Test] - public void CanConvertIntRangeToSByte([Range(1, 3)] sbyte x) { } - - [Test] - public void CanConvertIntRangeToDecimal([Range(1, 3)] decimal x) { } - - [Test] - public void CanConvertDoubleRangeToDecimal([Range(1.0, 1.3, 0.1)] decimal x) { } - - [Test] - public void CanConvertRandomIntToShort([Random(1, 10, 3)] short x) { } - - [Test] - public void CanConvertRandomIntToByte([Random(1, 10, 3)] byte x) { } - - [Test] - public void CanConvertRandomIntToSByte([Random(1, 10, 3)] sbyte x) { } - - [Test] - public void CanConvertRandomIntToDecimal([Random(1, 10, 3)] decimal x) { } - - [Test] - public void CanConvertRandomDoubleToDecimal([Random(1.0, 10.0, 3)] decimal x) { } - - #region Helper Methods - private void CheckValues(string methodName, params object[] expected) - { - MethodInfo method = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); - ParameterInfo param = method.GetParameters()[0]; - ValuesAttribute attr = param.GetCustomAttributes(typeof(ValuesAttribute), false)[0] as ValuesAttribute; - Assert.That(attr.GetData(param), Is.EqualTo(expected)); - } - - private void CheckValuesWithinTolerance(string methodName, params object[] expected) - { - MethodInfo method = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); - ParameterInfo param = method.GetParameters()[0]; - ValuesAttribute attr = param.GetCustomAttributes(typeof(ValuesAttribute), false)[0] as ValuesAttribute; - Assert.That(attr.GetData(param), Is.EqualTo(expected).Within(0.000001)); - } - #endregion - } -} diff --git a/test/NUnitLite/src/tests/Constraints/AllItemsConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/AllItemsConstraintTests.cs deleted file mode 100644 index d7c69d48f..000000000 --- a/test/NUnitLite/src/tests/Constraints/AllItemsConstraintTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; -#if CLR_2_0 || CLR_4_0 -using RangeConstraint = NUnit.Framework.Constraints.RangeConstraint; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class AllItemsConstraintTests : NUnit.Framework.Assertions.MessageChecker - { - [Test] - public void AllItemsAreNotNull() - { - object[] c = new object[] { 1, "hello", 3, Environment.OSVersion }; - Assert.That(c, new AllItemsConstraint(Is.Not.Null)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void AllItemsAreNotNullFails() - { - object[] c = new object[] { 1, "hello", null, 3 }; - expectedMessage = - TextMessageWriter.Pfx_Expected + "all items not null" + NL + - TextMessageWriter.Pfx_Actual + "< 1, \"hello\", null, 3 >" + NL; - Assert.That(c, new AllItemsConstraint(new NotConstraint(new EqualConstraint(null)))); - } - - [Test] - public void AllItemsAreInRange() - { - int[] c = new int[] { 12, 27, 19, 32, 45, 99, 26 }; - Assert.That(c, new AllItemsConstraint(new RangeConstraint(10, 100))); - } - - [Test] - public void AllItemsAreInRange_UsingIComparer() - { - int[] c = new int[] { 12, 27, 19, 32, 45, 99, 26 }; - Assert.That(c, new AllItemsConstraint(new RangeConstraint(10, 100).Using(new SimpleObjectComparer()))); - } - - [Test] - public void AllItemsAreInRange_UsingIComparerOfT() - { - int[] c = new int[] { 12, 27, 19, 32, 45, 99, 26 }; - Assert.That(c, new AllItemsConstraint(new RangeConstraint(10, 100).Using(new SimpleObjectComparer()))); - } - - [Test] - public void AllItemsAreInRange_UsingComparisonOfT() - { - int[] c = new int[] { 12, 27, 19, 32, 45, 99, 26 }; - Assert.That(c, new AllItemsConstraint(new RangeConstraint(10, 100).Using(new SimpleObjectComparer()))); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void AllItemsAreInRangeFailureMessage() - { - int[] c = new int[] { 12, 27, 19, 32, 107, 99, 26 }; - expectedMessage = - TextMessageWriter.Pfx_Expected + "all items in range (10,100)" + NL + - TextMessageWriter.Pfx_Actual + "< 12, 27, 19, 32, 107, 99, 26 >" + NL; - Assert.That(c, new AllItemsConstraint(new RangeConstraint(10, 100))); - } - - [Test] - public void AllItemsAreInstancesOfType() - { - object[] c = new object[] { 'a', 'b', 'c' }; - Assert.That(c, new AllItemsConstraint(new InstanceOfTypeConstraint(typeof(char)))); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void AllItemsAreInstancesOfTypeFailureMessage() - { - object[] c = new object[] { 'a', "b", 'c' }; - expectedMessage = - TextMessageWriter.Pfx_Expected + "all items instance of " + NL + - TextMessageWriter.Pfx_Actual + "< 'a', \"b\", 'c' >" + NL; - Assert.That(c, new AllItemsConstraint(new InstanceOfTypeConstraint(typeof(char)))); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/AndConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/AndConstraintTests.cs deleted file mode 100644 index 9938b7c9e..000000000 --- a/test/NUnitLite/src/tests/Constraints/AndConstraintTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class AndConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new AndConstraint(new GreaterThanConstraint(40), new LessThanConstraint(50)); - expectedDescription = "greater than 40 and less than 50"; - stringRepresentation = " >"; - } - - internal object[] SuccessData = new object[] { 42 }; - - internal object[] FailureData = new object[] { new object[] { 37, "37" }, new object[] { 53, "53" } }; - - [Test] - public void CanCombineTestsWithAndOperator() - { - Assert.That(42, new GreaterThanConstraint(40) & new LessThanConstraint(50)); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/AssignableFromConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/AssignableFromConstraintTests.cs deleted file mode 100644 index 8e207e391..000000000 --- a/test/NUnitLite/src/tests/Constraints/AssignableFromConstraintTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class AssignableFromConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new AssignableFromConstraint(typeof(D1)); - expectedDescription = string.Format("assignable from <{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); - } - - internal object[] SuccessData = new object[] { new D1(), new B() }; - - internal object[] FailureData = new object[] { - new TestCaseData( new D2(), "" ) }; - - class B { } - - class D1 : B { } - - class D2 : D1 { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/AssignableToConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/AssignableToConstraintTests.cs deleted file mode 100644 index e16a978a2..000000000 --- a/test/NUnitLite/src/tests/Constraints/AssignableToConstraintTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class AssignableToConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new AssignableToConstraint(typeof(D1)); - expectedDescription = string.Format("assignable to <{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); - } - - internal object[] SuccessData = new object[] { new D1(), new D2() }; - - internal object[] FailureData = new object[] { - new TestCaseData( new B(), "" ) }; - - class B { } - - class D1 : B { } - - class D2 : D1 { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/AsyncDelayedConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/AsyncDelayedConstraintTests.cs deleted file mode 100644 index fd2cc3db0..000000000 --- a/test/NUnitLite/src/tests/Constraints/AsyncDelayedConstraintTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -#if NET_4_5 -using System; -using System.Threading.Tasks; -using NUnit.Framework; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class AsyncDelayedConstraintTests - { - [Test] - public void ConstraintSuccess() - { - Assert.IsTrue(new DelayedConstraint(new EqualConstraint(1), 100) - .Matches(async () => await One())); - } - - [Test] - public void ConstraintFailure() - { - Assert.IsFalse(new DelayedConstraint(new EqualConstraint(2), 100) - .Matches(async () => await One())); - } - - [Test] - public void ConstraintError() - { - Assert.Throws(() => - new DelayedConstraint(new EqualConstraint(1), 100).Matches(async () => await Throw())); - } - - [Test] - public void ConstraintVoidDelegateFailureAsDelegateIsNotCalled() - { - Assert.IsFalse(new DelayedConstraint(new EqualConstraint(1), 100) - .Matches(new TestDelegate(async () => { await One(); }))); - } - - [Test] - public void ConstraintVoidDelegateExceptionIsFailureAsDelegateIsNotCalled() - { - Assert.IsFalse(new DelayedConstraint(new EqualConstraint(1), 100) - .Matches(new TestDelegate(async () => { await Throw(); }))); - } - - [Test] - public void SyntaxSuccess() - { - Assert.That(async () => await One(), Is.EqualTo(1).After(100)); - } - - - [Test] - public void SyntaxFailure() - { - Assert.Throws(() => - Assert.That(async () => await One(), Is.EqualTo(2).After(100))); - } - - [Test] - public void SyntaxError() - { - Assert.Throws(() => - Assert.That(async () => await Throw(), Is.EqualTo(1).After(100))); - } - - [Test] - public void SyntaxVoidDelegateExceptionIsFailureAsCodeIsNotCalled() - { - Assert.Throws(() => - Assert.That(new TestDelegate(async () => await Throw()), Is.EqualTo(1).After(100))); - } - - private static async Task One() - { - return await Task.Run(() => 1); - } - - private static async Task Throw() - { - await One(); - throw new InvalidOperationException(); - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/AttributeExistsConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/AttributeExistsConstraintTests.cs deleted file mode 100644 index 9d795cf1a..000000000 --- a/test/NUnitLite/src/tests/Constraints/AttributeExistsConstraintTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class AttributeExistsConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new AttributeExistsConstraint(typeof(TestFixtureAttribute)); - expectedDescription = "type with attribute "; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { typeof(AttributeExistsConstraintTests) }; - - internal object[] FailureData = new object[] { - new TestCaseData( typeof(D2), "" ) }; - - [Test, ExpectedException(typeof(System.ArgumentException))] - public void NonAttributeThrowsException() - { - new AttributeExistsConstraint(typeof(string)); - } - - [Test] - public void AttributeExistsOnMethodInfo() - { - Assert.That( - GetType().GetMethod("AttributeExistsOnMethodInfo"), - new AttributeExistsConstraint(typeof(TestAttribute))); - } - - [Test, Description("my description")] - public void AttributeTestPropertyValueOnMethodInfo() - { - Assert.That( - GetType().GetMethod("AttributeTestPropertyValueOnMethodInfo"), - Has.Attribute(typeof(DescriptionAttribute)).Property("Properties").Property("Keys").Contains("Description")); - } - - class B { } - - class D1 : B { } - - class D2 : D1 { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/BasicConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/BasicConstraintTests.cs deleted file mode 100644 index 57b535b26..000000000 --- a/test/NUnitLite/src/tests/Constraints/BasicConstraintTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class NullConstraintTest : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new NullConstraint(); - stringRepresentation = ""; - expectedDescription = "null"; - } - - internal object[] SuccessData = new object[] { null }; - - internal object[] FailureData = new object[] { new object[] { "hello", "\"hello\"" } }; - } - - [TestFixture] - public class TrueConstraintTest : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new TrueConstraint(); - stringRepresentation = ""; - expectedDescription = "True"; - } - - internal object[] SuccessData = new object[] { true, 2 + 2 == 4 }; - - internal object[] FailureData = new object[] { - new object[] { null, "null" }, - new object[] { "hello", "\"hello\"" }, - new object[] { false, "False" }, - new object[] { 2 + 2 == 5, "False" } }; - } - - [TestFixture] - public class FalseConstraintTest : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new FalseConstraint(); - stringRepresentation = ""; - expectedDescription = "False"; - } - - internal object[] SuccessData = new object[] { false, 2 + 2 == 5 }; - - internal object[] FailureData = new object[] { - new object[] { null, "null" }, - new object[] { "hello", "\"hello\"" }, - new object[] { true, "True" }, - new object[] { 2 + 2 == 4, "True" } }; - } - - [TestFixture] - public class NaNConstraintTest : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new NaNConstraint(); - stringRepresentation = ""; - expectedDescription = "NaN"; - } - - internal object[] SuccessData = new object[] { double.NaN, float.NaN }; - - internal object[] FailureData = new object[] { - new object[] { null, "null" }, - new object[] { "hello", "\"hello\"" }, - new object[] { 42, "42" }, - new object[] { double.PositiveInfinity, "Infinity" }, - new object[] { double.NegativeInfinity, "-Infinity" }, - new object[] { float.PositiveInfinity, "Infinity" }, - new object[] { float.NegativeInfinity, "-Infinity" } }; - } -} diff --git a/test/NUnitLite/src/tests/Constraints/BinarySerializableTest.cs b/test/NUnitLite/src/tests/Constraints/BinarySerializableTest.cs deleted file mode 100644 index 1d2b97adc..000000000 --- a/test/NUnitLite/src/tests/Constraints/BinarySerializableTest.cs +++ /dev/null @@ -1,48 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if !NETCF && !SILVERLIGHT -using System; -using System.Collections; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class BinarySerializableTest : ConstraintTestBaseWithArgumentException - { - [SetUp] - public void SetUp() - { - theConstraint = new BinarySerializableConstraint(); - expectedDescription = "binary serializable"; - stringRepresentation = ""; - } - - object[] SuccessData = new object[] { 1, "a", new ArrayList(), new InternalWithSerializableAttributeClass() }; - - object[] FailureData = new object[] { new TestCaseData( new InternalClass(), "" ) }; - - object[] InvalidData = new object[] { null }; - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/CollectionContainsConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/CollectionContainsConstraintTests.cs deleted file mode 100644 index 86545665c..000000000 --- a/test/NUnitLite/src/tests/Constraints/CollectionContainsConstraintTests.cs +++ /dev/null @@ -1,220 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class CollectionContainsConstraintTests - { - [Test] - public void CanTestContentsOfArray() - { - object item = "xyz"; - object[] c = new object[] { 123, item, "abc" }; - Assert.That(c, new CollectionContainsConstraint(item)); - } - -#if !SILVERLIGHT - [Test] - public void CanTestContentsOfArrayList() - { - object item = "xyz"; - ArrayList list = new ArrayList(new object[] { 123, item, "abc" }); - Assert.That(list, new CollectionContainsConstraint(item)); - } - - [Test] - public void CanTestContentsOfSortedList() - { - object item = "xyz"; - SortedList list = new SortedList(); - list.Add("a", 123); - list.Add("b", item); - list.Add("c", "abc"); - Assert.That(list.Values, new CollectionContainsConstraint(item)); - Assert.That(list.Keys, new CollectionContainsConstraint("b")); - } -#endif - - [Test] - public void CanTestContentsOfCollectionNotImplementingIList() - { - SimpleObjectCollection ints = new SimpleObjectCollection(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); - Assert.That(ints, new CollectionContainsConstraint(9)); - } - - [Test] - public void IgnoreCaseIsHonored() - { - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("WORLD").IgnoreCase); - } - [Test] - public void UsesProvidedIComparer() - { - MyComparer comparer = new MyComparer(); - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("World").Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparer : IComparer - { - public bool Called; - - public int Compare(object x, object y) - { - Called = true; - return 0; - } - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void UsesProvidedEqualityComparer() - { - MyEqualityComparer comparer = new MyEqualityComparer(); - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("World").Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyEqualityComparer : IEqualityComparer - { - public bool Called; - - bool IEqualityComparer.Equals(object x, object y) - { - Called = true; - return x == y; - } - - int IEqualityComparer.GetHashCode(object x) - { - return x.GetHashCode(); - } - } - - [Test] - public void UsesProvidedEqualityComparerOfT() - { - MyEqualityComparerOfT comparer = new MyEqualityComparerOfT(); - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("World").Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyEqualityComparerOfT : IEqualityComparer - { - public bool Called; - - bool IEqualityComparer.Equals(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y) == 0; - } - - int IEqualityComparer.GetHashCode(T x) - { - return x.GetHashCode(); - } - } - - [Test] - public void UsesProvidedComparerOfT() - { - MyComparer comparer = new MyComparer(); - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("World").Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparer : IComparer - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - - [Test] - public void UsesProvidedComparisonOfT() - { - MyComparison comparer = new MyComparison(); - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("World").Using(new Comparison(comparer.Compare))); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparison - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - - [Test] - public void ContainsWithRecursiveStructure() - { - SelfRecursiveEnumerable item = new SelfRecursiveEnumerable(); - SelfRecursiveEnumerable[] container = new SelfRecursiveEnumerable[] { new SelfRecursiveEnumerable(), item }; - - Assert.That(container, new CollectionContainsConstraint(item)); - } - - class SelfRecursiveEnumerable : IEnumerable - { - public IEnumerator GetEnumerator() - { - yield return this; - } - } - - -#if !NETCF_2_0 - [Test] - public void UsesProvidedLambdaExpression() - { - Assert.That(new string[] { "Hello", "World" }, - new CollectionContainsConstraint("WORLD").Using((x, y) => StringUtil.Compare(x, y, true))); - } -#endif -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/CollectionEquivalentConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/CollectionEquivalentConstraintTests.cs deleted file mode 100644 index b12e05120..000000000 --- a/test/NUnitLite/src/tests/Constraints/CollectionEquivalentConstraintTests.cs +++ /dev/null @@ -1,169 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - public class CollectionEquivalentConstraintTests - { - [Test] - public void EqualCollectionsAreEquivalent() - { - ICollection set1 = new SimpleObjectCollection("x", "y", "z"); - ICollection set2 = new SimpleObjectCollection("x", "y", "z"); - - Assert.That(new CollectionEquivalentConstraint(set1).Matches(set2)); - } - - [Test] - public void WorksWithCollectionsOfArrays() - { - byte[] array1 = new byte[] { 0x20, 0x44, 0x56, 0x76, 0x1e, 0xff }; - byte[] array2 = new byte[] { 0x42, 0x52, 0x72, 0xef }; - byte[] array3 = new byte[] { 0x20, 0x44, 0x56, 0x76, 0x1e, 0xff }; - byte[] array4 = new byte[] { 0x42, 0x52, 0x72, 0xef }; - - ICollection set1 = new SimpleObjectCollection(array1, array2); - ICollection set2 = new SimpleObjectCollection(array3, array4); - - Constraint constraint = new CollectionEquivalentConstraint(set1); - Assert.That(constraint.Matches(set2)); - - set2 = new SimpleObjectCollection(array4, array3); - Assert.That(constraint.Matches(set2)); - } - - [Test] - public void EquivalentIgnoresOrder() - { - ICollection set1 = new SimpleObjectCollection("x", "y", "z"); - ICollection set2 = new SimpleObjectCollection("z", "y", "x"); - - Assert.That(new CollectionEquivalentConstraint(set1).Matches(set2)); - } - - [Test] - public void EquivalentFailsWithDuplicateElementInActual() - { - ICollection set1 = new SimpleObjectCollection("x", "y", "z"); - ICollection set2 = new SimpleObjectCollection("x", "y", "x"); - - Assert.False(new CollectionEquivalentConstraint(set1).Matches(set2)); - } - - [Test] - public void EquivalentFailsWithDuplicateElementInExpected() - { - ICollection set1 = new SimpleObjectCollection("x", "y", "x"); - ICollection set2 = new SimpleObjectCollection("x", "y", "z"); - - Assert.False(new CollectionEquivalentConstraint(set1).Matches(set2)); - } - - [Test] - public void EquivalentHandlesNull() - { - ICollection set1 = new SimpleObjectCollection(null, "x", null, "z"); - ICollection set2 = new SimpleObjectCollection("z", null, "x", null); - - Assert.That(new CollectionEquivalentConstraint(set1).Matches(set2)); - } - - [Test] - public void EquivalentHonorsIgnoreCase() - { - ICollection set1 = new SimpleObjectCollection("x", "y", "z"); - ICollection set2 = new SimpleObjectCollection("z", "Y", "X"); - - Assert.That(new CollectionEquivalentConstraint(set1).IgnoreCase.Matches(set2)); - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF_2_0 - [Test] - public void EquivalentHonorsUsing() - { - ICollection set1 = new SimpleObjectCollection("x", "y", "z"); - ICollection set2 = new SimpleObjectCollection("z", "Y", "X"); - - Assert.That(new CollectionEquivalentConstraint(set1) - .Using((x, y) => StringUtil.Compare(x, y, true)) - .Matches(set2)); - } -#endif - -#if NET_3_5 || NET_4_0 - [Test, Platform("Net-3.5,Mono-3.5,Net-4.0,Mono-4.0,Silverlight")] - public void WorksWithHashSets() - { - var hash1 = new HashSet(new string[] { "presto", "abracadabra", "hocuspocus" }); - var hash2 = new HashSet(new string[] { "abracadabra", "presto", "hocuspocus" }); - - Assert.That(new CollectionEquivalentConstraint(hash1).Matches(hash2)); - } - - [Test, Platform("Net-3.5,Mono-3.5,Net-4.0,Mono-4.0,Silverlight")] - public void WorksWithHashSetAndArray() - { - var hash = new HashSet(new string[] { "presto", "abracadabra", "hocuspocus" }); - var array = new string[] { "abracadabra", "presto", "hocuspocus" }; - - var constraint = new CollectionEquivalentConstraint(hash); - Assert.That(constraint.Matches(array)); - } - - [Test, Platform("Net-3.5,Mono-3.5,Net-4.0,Mono-4.0,Silverlight")] - public void WorksWithArrayAndHashSet() - { - var hash = new HashSet(new string[] { "presto", "abracadabra", "hocuspocus" }); - var array = new string[] { "abracadabra", "presto", "hocuspocus" }; - - var constraint = new CollectionEquivalentConstraint(array); - Assert.That(constraint.Matches(hash)); - } - - [Test, Platform("Net-3.5,Mono-3.5,Net-4.0,Mono-4.0,Silverlight")] - public void FailureMessageWithHashSetAndArray() - { - var hash = new HashSet(new string[] { "presto", "abracadabra", "hocuspocus" }); - var array = new string[] { "abracadabra", "presto", "hocusfocus" }; - - var constraint = new CollectionEquivalentConstraint(hash); - Assert.False(constraint.Matches(array)); - - TextMessageWriter writer = new TextMessageWriter(); - constraint.WriteMessageTo(writer); - Assert.That(writer.ToString(), Is.EqualTo( - " Expected: equivalent to < \"presto\", \"abracadabra\", \"hocuspocus\" >" + Environment.NewLine + - " But was: < \"abracadabra\", \"presto\", \"hocusfocus\" >" + Environment.NewLine)); - Console.WriteLine(writer.ToString()); - } -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/CollectionOrderedConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/CollectionOrderedConstraintTests.cs deleted file mode 100644 index 82325d9bb..000000000 --- a/test/NUnitLite/src/tests/Constraints/CollectionOrderedConstraintTests.cs +++ /dev/null @@ -1,227 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class CollectionOrderedConstraintTests : NUnit.Framework.Assertions.MessageChecker - { - [Test] - public void IsOrdered() - { - ICollection collection = new SimpleObjectCollection("x", "y", "z"); - Assert.That(collection, Is.Ordered); - } - - [Test] - public void IsOrderedDescending() - { - ICollection collection = new SimpleObjectCollection("z", "y", "x"); - Assert.That(collection, Is.Ordered.Descending); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void IsOrdered_Fails() - { - ICollection collection = new SimpleObjectCollection("x", "z", "y"); - expectedMessage = - " Expected: collection ordered" + NL + - " But was: < \"x\", \"z\", \"y\" >" + NL; - - Assert.That(collection, Is.Ordered); - } - - [Test] - public void IsOrdered_Allows_adjacent_equal_values() - { - ICollection collection = new SimpleObjectCollection("x", "x", "z"); - Assert.That(collection, Is.Ordered); - } - - [Test, ExpectedException(typeof(ArgumentNullException), - ExpectedMessage = "index 1", MatchType = MessageMatch.Contains)] - public void IsOrdered_Handles_null() - { - ICollection collection = new SimpleObjectCollection("x", null, "z"); - Assert.That(collection, Is.Ordered); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public void IsOrdered_TypesMustBeComparable() - { - ICollection collection = new SimpleObjectCollection(1, "x"); - Assert.That(collection, Is.Ordered); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public void IsOrdered_AtLeastOneArgMustImplementIComparable() - { - ICollection collection = new SimpleObjectCollection(new object(), new object()); - Assert.That(collection, Is.Ordered); - } - - [Test] - public void IsOrdered_Handles_custom_comparison() - { - ICollection collection = new SimpleObjectCollection(new object(), new object()); - - AlwaysEqualComparer comparer = new AlwaysEqualComparer(); - Assert.That(collection, Is.Ordered.Using(comparer)); - Assert.That(comparer.Called, "TestComparer was not called"); - } - - [Test] - public void IsOrdered_Handles_custom_comparison2() - { - ICollection collection = new SimpleObjectCollection(2, 1); - - TestComparer comparer = new TestComparer(); - Assert.That(collection, Is.Ordered.Using(comparer)); - Assert.That(comparer.Called, "TestComparer was not called"); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void UsesProvidedComparerOfT() - { - ICollection al = new SimpleObjectCollection(1, 2); - - MyComparer comparer = new MyComparer(); - Assert.That(al, Is.Ordered.Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparer : IComparer - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - - [Test] - public void UsesProvidedComparisonOfT() - { - ICollection al = new SimpleObjectCollection(1, 2); - - MyComparison comparer = new MyComparison(); - Assert.That(al, Is.Ordered.Using(new Comparison(comparer.Compare))); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparison - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - -#if !NETCF_2_0 - [Test] - public void UsesProvidedLambda() - { - ICollection al = new SimpleObjectCollection(1, 2); - - Comparison comparer = (x, y) => x.CompareTo(y); - Assert.That(al, Is.Ordered.Using(comparer)); - } -#endif -#endif - - [Test] - public void IsOrderedBy() - { - ICollection collection = new SimpleObjectCollection( - new OrderedByTestClass(1), - new OrderedByTestClass(2)); - - Assert.That(collection, Is.Ordered.By("Value")); - } - - [Test] - public void IsOrderedBy_Comparer() - { - ICollection collection = new SimpleObjectCollection( - new OrderedByTestClass(1), - new OrderedByTestClass(2)); - - Assert.That(collection, Is.Ordered.By("Value").Using(new SimpleObjectComparer())); - } - - [Test] - public void IsOrderedBy_Handles_heterogeneous_classes_as_long_as_the_property_is_of_same_type() - { - ICollection al = new SimpleObjectCollection( - new OrderedByTestClass(1), - new OrderedByTestClass2(2)); - - Assert.That(al, Is.Ordered.By("Value")); - } - - public class OrderedByTestClass - { - private int myValue; - - public int Value - { - get { return myValue; } - set { myValue = value; } - } - - public OrderedByTestClass(int value) - { - Value = value; - } - } - - public class OrderedByTestClass2 - { - private int myValue; - public int Value - { - get { return myValue; } - set { myValue = value; } - } - - public OrderedByTestClass2(int value) - { - Value = value; - } - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/CollectionSubsetConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/CollectionSubsetConstraintTests.cs deleted file mode 100644 index 6e18f5dde..000000000 --- a/test/NUnitLite/src/tests/Constraints/CollectionSubsetConstraintTests.cs +++ /dev/null @@ -1,42 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class CollectionSubsetConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new CollectionSubsetConstraint(new int[] { 1, 2, 3, 4, 5 }); - stringRepresentation = ""; - expectedDescription = "subset of < 1, 2, 3, 4, 5 >"; - } - - internal object[] SuccessData = new object[] { new int[] { 1, 3, 5 }, new int[] { 1, 2, 3, 4, 5 } }; - internal object[] FailureData = new object[] { - new object[] { new int[] { 1, 3, 7 }, "< 1, 3, 7 >" }, - new object[] { new int[] { 1, 2, 2, 2, 5 }, "< 1, 2, 2, 2, 5 >" } }; - } -} diff --git a/test/NUnitLite/src/tests/Constraints/ComparisonConstraintTest.cs b/test/NUnitLite/src/tests/Constraints/ComparisonConstraintTest.cs deleted file mode 100644 index c8ba195b2..000000000 --- a/test/NUnitLite/src/tests/Constraints/ComparisonConstraintTest.cs +++ /dev/null @@ -1,138 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - #region ComparisonConstraintTest - - public abstract class ComparisonConstraintTest : ConstraintTestBaseWithArgumentException - { - protected ComparisonConstraint comparisonConstraint; - - [Test] - public void UsesProvidedIComparer() - { - SimpleObjectComparer comparer = new SimpleObjectComparer(); - comparisonConstraint.Using(comparer).Matches(0); - Assert.That(comparer.Called, "Comparer was not called"); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void UsesProvidedComparerOfT() - { - MyComparer comparer = new MyComparer(); - comparisonConstraint.Using(comparer).Matches(0); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparer : IComparer - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - - [Test] - public void UsesProvidedComparisonOfT() - { - MyComparison comparer = new MyComparison(); - comparisonConstraint.Using(new Comparison(comparer.Compare)).Matches(0); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparison - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - -#if !NETCF_2_0 - [Test] - public void UsesProvidedLambda() - { - Comparison comparer = (x, y) => x.CompareTo(y); - comparisonConstraint.Using(comparer).Matches(0); - } -#endif -#endif - } - - #endregion - - #region Comparison Test Classes - - class ClassWithIComparable : IComparable - { - private int val; - - public ClassWithIComparable(int val) - { - this.val = val; - } - - public int CompareTo(object x) - { - ClassWithIComparable other = x as ClassWithIComparable; - if (x is ClassWithIComparable) - return val.CompareTo(other.val); - - throw new ArgumentException(); - } - } - -#if CLR_2_0 || CLR_4_0 - class ClassWithIComparableOfT : IComparable - { - private int val; - - public ClassWithIComparableOfT(int val) - { - this.val = val; - } - - public int CompareTo(ClassWithIComparableOfT other) - { - return val.CompareTo(other.val); - } - } -#endif - - #endregion -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/ConstraintTestBase.cs b/test/NUnitLite/src/tests/Constraints/ConstraintTestBase.cs deleted file mode 100644 index 44dce2a8b..000000000 --- a/test/NUnitLite/src/tests/Constraints/ConstraintTestBase.cs +++ /dev/null @@ -1,103 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints.Tests -{ - public abstract class ConstraintTestBaseNoData - { - protected Constraint theConstraint; - protected string expectedDescription = ""; - protected string stringRepresentation = ""; - - [Test] - public void ProvidesProperDescription() - { - TextMessageWriter writer = new TextMessageWriter(); - theConstraint.WriteDescriptionTo(writer); - Assert.That(writer.ToString(), Is.EqualTo(expectedDescription)); - } - - [Test] - public void ProvidesProperStringRepresentation() - { - Assert.That(theConstraint.ToString(), Is.EqualTo(stringRepresentation)); - } - } - - public abstract class ConstraintTestBase : ConstraintTestBaseNoData - { - [Test, TestCaseSource("SuccessData")] - public void SucceedsWithGoodValues(object value) - { - if (!theConstraint.Matches(value)) - { - MessageWriter writer = new TextMessageWriter(); - theConstraint.WriteMessageTo(writer); - Assert.Fail(writer.ToString()); - } - } - - [Test, TestCaseSource("FailureData")] - public void FailsWithBadValues(object badValue, string message) - { - string NL = Env.NewLine; - - Assert.IsFalse(theConstraint.Matches(badValue)); - - TextMessageWriter writer = new TextMessageWriter(); - theConstraint.WriteMessageTo(writer); - Assert.That( writer.ToString(), Is.EqualTo( - TextMessageWriter.Pfx_Expected + expectedDescription + NL + - TextMessageWriter.Pfx_Actual + message + NL )); - } - } - - /// - /// Base class for testing constraints that can throw an ArgumentException - /// - public abstract class ConstraintTestBaseWithArgumentException : ConstraintTestBase - { - [Test, TestCaseSource("InvalidData")] - [ExpectedException(typeof(ArgumentException))] - public void InvalidDataThrowsArgumentException(object value) - { - theConstraint.Matches(value); - } - } - - /// - /// Base class for tests that can throw multiple exceptions. Use - /// TestCaseData class to specify the expected exception type. - /// - public abstract class ConstraintTestBaseWithExceptionTests : ConstraintTestBase - { - [Test, TestCaseSource("InvalidData")] - public void InvalidDataThrowsException(object value) - { - theConstraint.Matches(value); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/DelayedConstraintTest.cs b/test/NUnitLite/src/tests/Constraints/DelayedConstraintTest.cs deleted file mode 100644 index 6b06292f4..000000000 --- a/test/NUnitLite/src/tests/Constraints/DelayedConstraintTest.cs +++ /dev/null @@ -1,212 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.ComponentModel; -using System.Threading; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate; -#else -using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class DelayedConstraintTest : ConstraintTestBase - { - private static bool value; - - [SetUp] - public void SetUp() - { - theConstraint = new DelayedConstraint(new EqualConstraint(true), 500); - expectedDescription = "True after 500 millisecond delay"; - stringRepresentation = ">"; - - value = false; - //SetValueTrueAfterDelay(300); - } - - object[] SuccessData = new object[] { true }; - object[] FailureData = new object[] { - new TestCaseData( false, "False" ), - new TestCaseData( 0, "0" ), - new TestCaseData( null, "null" ) }; - - object[] InvalidData = new object[] { InvalidDelegate }; - - ActualValueDelegate[] SuccessDelegates = new ActualValueDelegate[] { DelegateReturningValue }; - ActualValueDelegate[] FailureDelegates = new ActualValueDelegate[] { DelegateReturningFalse, DelegateReturningZero }; - - [Test, TestCaseSource("SuccessDelegates")] - public void SucceedsWithGoodDelegates(ActualValueDelegate del) - { - SetValueTrueAfterDelay(300); - Assert.That(theConstraint.Matches(del)); - } - - [Test, TestCaseSource("FailureDelegates")] - public void FailsWithBadDelegates(ActualValueDelegate del) - { - Assert.IsFalse(theConstraint.Matches(del)); - } - - [Test] - public void SimpleTest() - { - SetValueTrueAfterDelay(500); - Assert.That(DelegateReturningValue, new DelayedConstraint(new EqualConstraint(true), 5000, 200)); - } - - [Test] - public void SimpleTestUsingReference() - { - SetValueTrueAfterDelay(500); - Assert.That(ref value, new DelayedConstraint(new EqualConstraint(true), 5000, 200)); - } - - [Test] - public void ThatOverload_ZeroDelayIsAllowed() - { - Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), 0)); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public void ThatOverload_DoesNotAcceptNegativeDelayValues() - { - Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), -1)); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void SimpleTestBoolDelegate() - { - SetValueTrueAfterDelay(500); - Assert.That(DelegateReturningValue, new DelayedConstraint(new EqualConstraint(true), 5000, 200)); - } - - [Test] - public void ThatOverload_ZeroDelayIsAllowed_IntDelegate() - { - Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), 0)); - } - - [Test, ExpectedException(typeof(ArgumentException))] - public void ThatOverload_DoesNotAcceptNegativeDelayValues_IntDelegate() - { - Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), -1)); - } - -#if !NETCF - [Test] - public void CanTestContentsOfList() - { - BackgroundWorker worker = new BackgroundWorker(); - List list = new System.Collections.Generic.List(); - worker.RunWorkerCompleted += delegate { list.Add(1); }; - worker.DoWork += delegate { Thread.Sleep(1); }; - worker.RunWorkerAsync(); - Assert.That(list, Has.Count.EqualTo(1).After(5000, 100)); - } - - [Test] - public void CanTestContentsOfRefList() - { - BackgroundWorker worker = new BackgroundWorker(); - List list = new List(); - worker.RunWorkerCompleted += delegate { list.Add(1); }; - worker.DoWork += delegate { Thread.Sleep(1); }; - worker.RunWorkerAsync(); - Assert.That(ref list, Has.Count.EqualTo(1).After(5000, 100)); - } - - [Test] - public void CanTestContentsOfDelegateReturningList() - { - var worker = new BackgroundWorker(); - var list = new List(); - worker.RunWorkerCompleted += delegate { list.Add(1); }; - worker.DoWork += delegate { Thread.Sleep(1); }; - worker.RunWorkerAsync(); - Assert.That(() => list, Has.Count.EqualTo(1).After(5000, 100)); - } - - [Test] - public void CanTestInitiallyNullReference() - { - string statusString = null; // object starts off as null - - BackgroundWorker worker = new BackgroundWorker(); - worker.RunWorkerCompleted += delegate { statusString = "finished"; /* object non-null after work */ }; - worker.DoWork += delegate { Thread.Sleep(TimeSpan.FromSeconds(1)); /* simulate work */ }; - worker.RunWorkerAsync(); - - Assert.That(ref statusString, Has.Length.GreaterThan(0).After(3000, 100)); - } - - [Test] - public void CanTestInitiallyNullDelegate() - { - string statusString = null; // object starts off as null - - BackgroundWorker worker = new BackgroundWorker(); - worker.RunWorkerCompleted += delegate { statusString = "finished"; /* object non-null after work */ }; - worker.DoWork += delegate { Thread.Sleep(TimeSpan.FromSeconds(1)); /* simulate work */ }; - worker.RunWorkerAsync(); - - Assert.That(() => statusString, Has.Length.GreaterThan(0).After(3000, 100)); - } -#endif -#endif - - private static int setValueTrueDelay; - - private void SetValueTrueAfterDelay(int delay) - { - setValueTrueDelay = delay; - Thread thread = new Thread(SetValueTrueDelegate); - thread.Start(); - } - - private static void MethodReturningVoid() { } - private static TestDelegate InvalidDelegate = new TestDelegate(MethodReturningVoid); - - private static object MethodReturningValue() { return value; } - private static ActualValueDelegate DelegateReturningValue = new ActualValueDelegate(MethodReturningValue); - - private static object MethodReturningFalse() { return false; } - private static ActualValueDelegate DelegateReturningFalse = new ActualValueDelegate(MethodReturningFalse); - - private static object MethodReturningZero() { return 0; } - private static ActualValueDelegate DelegateReturningZero = new ActualValueDelegate(MethodReturningZero); - - private static void MethodSetsValueTrue() - { - Thread.Sleep(setValueTrueDelay); - value = true; - } - private ThreadStart SetValueTrueDelegate = new ThreadStart(MethodSetsValueTrue); - } -} diff --git a/test/NUnitLite/src/tests/Constraints/EmptyConstraintTest.cs b/test/NUnitLite/src/tests/Constraints/EmptyConstraintTest.cs deleted file mode 100644 index 0ab94c339..000000000 --- a/test/NUnitLite/src/tests/Constraints/EmptyConstraintTest.cs +++ /dev/null @@ -1,91 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class EmptyConstraintTest : ConstraintTestBaseWithArgumentException - { - [SetUp] - public void SetUp() - { - theConstraint = new EmptyConstraint(); - expectedDescription = ""; - stringRepresentation = ""; - } - - internal static object[] SuccessData = new object[] - { -#if CLR_2_0 || CLR_4_0 - new System.Collections.Generic.List(), -#endif - string.Empty, - new object[0], - new SimpleObjectCollection() - }; - - internal static object[] FailureData = new object[] - { - new TestCaseData( "Hello", "\"Hello\"" ), - new TestCaseData( new object[] { 1, 2, 3 }, "< 1, 2, 3 >" ) - }; - - internal static object[] InvalidData = new object[] - { - null, - 5 - }; - } - - [TestFixture] - public class NullOrEmptyStringConstraintTest : ConstraintTestBaseWithArgumentException - { - [SetUp] - public void SetUp() - { - theConstraint = new NullOrEmptyStringConstraint(); - expectedDescription = "null or empty string"; - stringRepresentation = ""; - } - - internal static object[] SuccessData = new object[] - { - string.Empty, - null - }; - - internal static object[] FailureData = new object[] - { - new TestCaseData( "Hello", "\"Hello\"" ) - }; - - internal static object[] InvalidData = new object[] - { - 5 - }; - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/EndsWithConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/EndsWithConstraintTests.cs deleted file mode 100644 index 1aca9ebf0..000000000 --- a/test/NUnitLite/src/tests/Constraints/EndsWithConstraintTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class EndsWithConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new EndsWithConstraint("hello"); - expectedDescription = "String ending with \"hello\""; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { "hello", "I said hello" }; - - internal object[] FailureData = new object[] { - new TestCaseData( "goodbye", "\"goodbye\"" ), - new TestCaseData( "hello there", "\"hello there\"" ), - new TestCaseData( "say hello to Fred", "\"say hello to Fred\"" ), - new TestCaseData( string.Empty, "" ), - new TestCaseData( null , "null" ) }; - } - - [TestFixture] - public class EndsWithConstraintTestsIgnoringCase : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new EndsWithConstraint("hello").IgnoreCase; - expectedDescription = "String ending with \"hello\", ignoring case"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { "HELLO", "I said Hello" }; - - internal object[] FailureData = new object[] { - new TestCaseData( "goodbye", "\"goodbye\"" ), - new TestCaseData( "What the hell?", "\"What the hell?\"" ), - new TestCaseData( "hello there", "\"hello there\"" ), - new TestCaseData( "say hello to Fred", "\"say hello to Fred\"" ), - new TestCaseData( string.Empty, "" ), - new TestCaseData( null , "null" ) }; - } -} diff --git a/test/NUnitLite/src/tests/Constraints/EqualConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/EqualConstraintTests.cs deleted file mode 100644 index 7ab346c42..000000000 --- a/test/NUnitLite/src/tests/Constraints/EqualConstraintTests.cs +++ /dev/null @@ -1,459 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class EqualConstraintTest : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new EqualConstraint(4); - expectedDescription = "4"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 4, 4.0f, 4.0d, 4.0000m }; - - internal object[] FailureData = new object[] { - new TestCaseData( 5, "5" ), - new TestCaseData( null, "null" ), - new TestCaseData( "Hello", "\"Hello\"" ), - new TestCaseData( double.NaN, "NaN" ), - new TestCaseData( double.PositiveInfinity, "Infinity" ) }; - - [TestCase(double.NaN)] - [TestCase(double.PositiveInfinity)] - [TestCase(double.NegativeInfinity)] - [TestCase(float.NaN)] - [TestCase(float.PositiveInfinity)] - [TestCase(float.NegativeInfinity)] - public void CanMatchSpecialFloatingPointValues(object value) - { - Assert.That(value, new EqualConstraint(value)); - } - - [Test] - public void CanMatchDates() - { - DateTime expected = new DateTime(2007, 4, 1); - DateTime actual = new DateTime(2007, 4, 1); - Assert.That(actual, new EqualConstraint(expected)); - } - - [Test] - public void CanMatchDatesWithinTimeSpan() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); - TimeSpan tolerance = TimeSpan.FromMinutes(5.0); - Assert.That(actual, new EqualConstraint(expected).Within(tolerance)); - } - - [Test] - public void CanMatchDatesWithinDays() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 4, 13, 0, 0); - Assert.That(actual, new EqualConstraint(expected).Within(5).Days); - } - - [Test] - public void CanMatchDatesWithinHours() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 1, 16, 0, 0); - Assert.That(actual, new EqualConstraint(expected).Within(5).Hours); - } - - [Test] - public void CanMatchDatesWithinMinutes() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); - Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes); - } - - [Test] - public void CanMatchTimeSpanWithinMinutes() - { - TimeSpan expected = new TimeSpan(10, 0, 0); - TimeSpan actual = new TimeSpan(10, 2, 30); - Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes); - } - - [Test] - public void CanMatchDatesWithinSeconds() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); - Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds); - } - - [Test] - public void CanMatchDatesWithinMilliseconds() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); - Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds); - } - - [Test] - public void CanMatchDatesWithinTicks() - { - DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); - DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); - Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute * 5).Ticks); - } - - #region Dictionary Tests - -#if (CLR_2_0 || CLR_4_0) && !NETCF_2_0 -#if !SILVERLIGHT - // TODO: Move these to a separate fixture - [Test] - public void CanMatchHashtables_SameOrder() - { - Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void CanMatchHashtables_Failure() - { - Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Hashtable { { 0, 0 }, { 1, 5 }, { 2, 2 } }); - } - - [Test] - public void CanMatchHashtables_DifferentOrder() - { - Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Hashtable { { 0, 0 }, { 2, 2 }, { 1, 1 } }); - } -#endif - - [Test] - public void CanMatchDictionaries_SameOrder() - { - Assert.AreEqual(new Dictionary { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Dictionary { { 0, 0 }, { 1, 1 }, { 2, 2 } }); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void CanMatchDictionaries_Failure() - { - Assert.AreEqual(new Dictionary { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Dictionary { { 0, 0 }, { 1, 5 }, { 2, 2 } }); - } - - [Test] - public void CanMatchDictionaries_DifferentOrder() - { - Assert.AreEqual(new Dictionary { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Dictionary { { 0, 0 }, { 2, 2 }, { 1, 1 } }); - } - -#if !SILVERLIGHT - [Test] - public void CanMatchHashtableWithDictionary() - { - Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, - new Dictionary { { 0, 0 }, { 2, 2 }, { 1, 1 } }); - } -#endif -#endif - - #endregion - - [TestCase(20000000000000004.0)] - [TestCase(19999999999999996.0)] - public void CanMatchDoublesWithUlpTolerance(object value) - { - Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps); - } - - [ExpectedException(typeof(AssertionException), ExpectedMessage = "+/- 1 Ulps", MatchType = MessageMatch.Contains)] - [TestCase(20000000000000008.0)] - [TestCase(19999999999999992.0)] - public void FailsOnDoublesOutsideOfUlpTolerance(object value) - { - Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps); - } - - [TestCase(19999998.0f)] - [TestCase(20000002.0f)] - public void CanMatchSinglesWithUlpTolerance(object value) - { - Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps); - } - - [ExpectedException(typeof(AssertionException), ExpectedMessage = "+/- 1 Ulps", MatchType = MessageMatch.Contains)] - [TestCase(19999996.0f)] - [TestCase(20000004.0f)] - public void FailsOnSinglesOutsideOfUlpTolerance(object value) - { - Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps); - } - - [TestCase(9500.0)] - [TestCase(10000.0)] - [TestCase(10500.0)] - public void CanMatchDoublesWithRelativeTolerance(object value) - { - Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent); - } - - [ExpectedException(typeof(AssertionException), ExpectedMessage = "+/- 10.0d Percent", MatchType = MessageMatch.Contains)] - [TestCase(8500.0)] - [TestCase(11500.0)] - public void FailsOnDoublesOutsideOfRelativeTolerance(object value) - { - Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent); - } - - [TestCase(9500.0f)] - [TestCase(10000.0f)] - [TestCase(10500.0f)] - public void CanMatchSinglesWithRelativeTolerance(object value) - { - Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent); - } - - [ExpectedException(typeof(AssertionException), ExpectedMessage = "+/- 10.0f Percent", MatchType = MessageMatch.Contains)] - [TestCase(8500.0f)] - [TestCase(11500.0f)] - public void FailsOnSinglesOutsideOfRelativeTolerance(object value) - { - Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent); - } - - /// Applies both the Percent and Ulps modifiers to cause an exception - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorWithPercentAndUlpsToleranceModes() - { - EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Percent.Ulps; - } - - /// Applies both the Ulps and Percent modifiers to cause an exception - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorWithUlpsAndPercentToleranceModes() - { - EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Ulps.Percent; - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfPercentPrecedesWithin() - { - Assert.That(1010, Is.EqualTo(1000).Percent.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfUlpsPrecedesWithin() - { - Assert.That(1010.0, Is.EqualTo(1000.0).Ulps.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfDaysPrecedesWithin() - { - Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Days.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfHoursPrecedesWithin() - { - Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Hours.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfMinutesPrecedesWithin() - { - Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Minutes.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfSecondsPrecedesWithin() - { - Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Seconds.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfMillisecondsPrecedesWithin() - { - Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Milliseconds.Within(5)); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfTicksPrecedesWithin() - { - Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Ticks.Within(5)); - } - - [ExpectedException(typeof(InvalidOperationException))] - [TestCase(1000, 1010)] - [TestCase(1000U, 1010U)] - [TestCase(1000L, 1010L)] - [TestCase(1000UL, 1010UL)] - public void ErrorIfUlpsIsUsedOnIntegralType(object x, object y) - { - Assert.That(y, Is.EqualTo(x).Within(2).Ulps); - } - - [Test, ExpectedException(typeof(InvalidOperationException))] - public void ErrorIfUlpsIsUsedOnDecimal() - { - Assert.That(100m, Is.EqualTo(100m).Within(2).Ulps); - } - - [Test] - public void UsesProvidedIComparer() - { - SimpleObjectComparer comparer = new SimpleObjectComparer(); - Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void UsesProvidedEqualityComparer() - { - SimpleEqualityComparer comparer = new SimpleEqualityComparer(); - Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - [Test] - public void UsesProvidedEqualityComparerOfT() - { - SimpleEqualityComparer comparer = new SimpleEqualityComparer(); - Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - [Test] - public void UsesProvidedComparerOfT() - { - SimpleEqualityComparer comparer = new SimpleEqualityComparer(); - Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - [Test] - public void UsesProvidedComparisonOfT() - { - MyComparison comparer = new MyComparison(); - Assert.That(2 + 2, Is.EqualTo(4).Using(new Comparison(comparer.Compare))); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparison - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - -#if !NETCF_2_0 - [Test] - public void UsesProvidedLambda_IntArgs() - { - Assert.That(2 + 2, Is.EqualTo(4).Using((x, y) => x.CompareTo(y))); - } - - [Test] - public void UsesProvidedLambda_StringArgs() - { - Assert.That("hello", Is.EqualTo("HELLO").Using((x, y) => StringUtil.Compare(x, y, true))); - } - - [Test] - public void UsesProvidedListComparer() - { - var list1 = new List() { 2, 3 }; - var list2 = new List() { 3, 4 }; - - var list11 = new List>() { list1 }; - var list22 = new List>() { list2 }; - var comparer = new IntListEqualComparer(); - - Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer)); - } -#endif - - public class IntListEqualComparer : IEqualityComparer> - { - public bool Equals(List x, List y) - { - return x.Count == y.Count; - } - - public int GetHashCode(List obj) - { - return obj.Count.GetHashCode(); - } - } - -#if !NETCF_2_0 - [Test] - public void UsesProvidedArrayComparer() - { - var array1 = new int[] { 2, 3 }; - var array2 = new int[] { 3, 4 }; - - var list11 = new List() { array1 }; - var list22 = new List() { array2 }; - var comparer = new IntArrayEqualComparer(); - - Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer)); - } - - public class IntArrayEqualComparer : IEqualityComparer - { - public bool Equals(int[] x, int[] y) - { - return x.Length == y.Length; - } - - public int GetHashCode(int[] obj) - { - return obj.Length.GetHashCode(); - } - } -#endif -#endif - } -} diff --git a/test/NUnitLite/src/tests/Constraints/ExactCountConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/ExactCountConstraintTests.cs deleted file mode 100644 index 685e77dc6..000000000 --- a/test/NUnitLite/src/tests/Constraints/ExactCountConstraintTests.cs +++ /dev/null @@ -1,83 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Assertions; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints.Tests -{ - public class ExactCountConstraintTests : MessageChecker - { - private static readonly string[] names = new string[] { "Charlie", "Fred", "Joe", "Charlie" }; - - [Test] - public void ZeroItemsMatch() - { - Assert.That(names, new ExactCountConstraint(0, Is.EqualTo("Sam"))); - Assert.That(names, Has.Exactly(0).EqualTo("Sam")); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ZeroItemsMatchFails() - { - expectedMessage = - TextMessageWriter.Pfx_Expected + "no item \"Charlie\"" + Env.NewLine + - TextMessageWriter.Pfx_Actual + "< \"Charlie\", \"Fred\", \"Joe\", \"Charlie\" >" + Env.NewLine; - Assert.That(names, new ExactCountConstraint(0, Is.EqualTo("Charlie"))); - } - - [Test] - public void ExactlyOneItemMatches() - { - Assert.That(names, new ExactCountConstraint(1, Is.EqualTo("Fred"))); - Assert.That(names, Has.Exactly(1).EqualTo("Fred")); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ExactlyOneItemMatchFails() - { - expectedMessage = - TextMessageWriter.Pfx_Expected + "exactly one item \"Charlie\"" + Env.NewLine + - TextMessageWriter.Pfx_Actual + "< \"Charlie\", \"Fred\", \"Joe\", \"Charlie\" >" + Env.NewLine; - Assert.That(names, new ExactCountConstraint(1, Is.EqualTo("Charlie"))); - } - - [Test] - public void ExactlyTwoItemsMatch() - { - Assert.That(names, new ExactCountConstraint(2, Is.EqualTo("Charlie"))); - Assert.That(names, Has.Exactly(2).EqualTo("Charlie")); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void ExactlyTwoItemsMatchFails() - { - expectedMessage = - TextMessageWriter.Pfx_Expected + "exactly 2 items \"Fred\"" + Env.NewLine + - TextMessageWriter.Pfx_Actual + "< \"Charlie\", \"Fred\", \"Joe\", \"Charlie\" >" + Env.NewLine; - Assert.That(names, new ExactCountConstraint(2, Is.EqualTo("Fred"))); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/ExactTypeConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/ExactTypeConstraintTests.cs deleted file mode 100644 index 3221c1059..000000000 --- a/test/NUnitLite/src/tests/Constraints/ExactTypeConstraintTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class ExactTypeConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new ExactTypeConstraint(typeof(D1)); - expectedDescription = string.Format("<{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); - } - - internal object[] SuccessData = new object[] { new D1() }; - - internal object[] FailureData = new object[] { - new TestCaseData( new B(), "" ), - new TestCaseData( new D2(), "" ) - }; - - class B { } - - class D1 : B { } - - class D2 : D1 { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/FloatingPointNumericsTest.cs b/test/NUnitLite/src/tests/Constraints/FloatingPointNumericsTest.cs deleted file mode 100644 index b5871a184..000000000 --- a/test/NUnitLite/src/tests/Constraints/FloatingPointNumericsTest.cs +++ /dev/null @@ -1,120 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class FloatingPointNumericsTest - { - - /// Tests the floating point value comparison helper - [Test] - public void FloatEqualityWithUlps() - { - Assert.IsTrue( - FloatingPointNumerics.AreAlmostEqualUlps(0.00000001f, 0.0000000100000008f, 1) - ); - Assert.IsFalse( - FloatingPointNumerics.AreAlmostEqualUlps(0.00000001f, 0.0000000100000017f, 1) - ); - - Assert.IsTrue( - FloatingPointNumerics.AreAlmostEqualUlps(1000000.00f, 1000000.06f, 1) - ); - Assert.IsFalse( - FloatingPointNumerics.AreAlmostEqualUlps(1000000.00f, 1000000.13f, 1) - ); - } - - /// Tests the double precision floating point value comparison helper - [Test] - public void DoubleEqualityWithUlps() - { - Assert.IsTrue( - FloatingPointNumerics.AreAlmostEqualUlps(0.00000001, 0.000000010000000000000002, 1) - ); - Assert.IsFalse( - FloatingPointNumerics.AreAlmostEqualUlps(0.00000001, 0.000000010000000000000004, 1) - ); - - Assert.IsTrue( - FloatingPointNumerics.AreAlmostEqualUlps(1000000.00, 1000000.0000000001, 1) - ); - Assert.IsFalse( - FloatingPointNumerics.AreAlmostEqualUlps(1000000.00, 1000000.0000000002, 1) - ); - } - - /// Tests the integer reinterpretation functions - [Test] - public void MirroredIntegerReinterpretation() - { - Assert.AreEqual( - 12345.0f, - FloatingPointNumerics.ReinterpretAsFloat( - FloatingPointNumerics.ReinterpretAsInt(12345.0f) - ) - ); - } - - /// Tests the long reinterpretation functions - [Test] - public void MirroredLongReinterpretation() - { - Assert.AreEqual( - 12345.67890, - FloatingPointNumerics.ReinterpretAsDouble( - FloatingPointNumerics.ReinterpretAsLong(12345.67890) - ) - ); - } - - /// Tests the floating point reinterpretation functions - [Test] - public void MirroredFloatReinterpretation() - { - Assert.AreEqual( - 12345, - FloatingPointNumerics.ReinterpretAsInt( - FloatingPointNumerics.ReinterpretAsFloat(12345) - ) - ); - } - - - /// - /// Tests the double prevision floating point reinterpretation functions - /// - [Test] - public void MirroredDoubleReinterpretation() - { - Assert.AreEqual( - 1234567890, - FloatingPointNumerics.ReinterpretAsLong( - FloatingPointNumerics.ReinterpretAsDouble(1234567890) - ) - ); - } - - } -} diff --git a/test/NUnitLite/src/tests/Constraints/GreaterThanConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/GreaterThanConstraintTests.cs deleted file mode 100644 index 4762b3440..000000000 --- a/test/NUnitLite/src/tests/Constraints/GreaterThanConstraintTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class GreaterThanConstraintTests : ComparisonConstraintTest - { - [SetUp] - public void SetUp() - { - theConstraint = comparisonConstraint = new GreaterThanConstraint(5); - expectedDescription = "greater than 5"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 6, 5.001 }; - - internal object[] FailureData = new object[] { new object[] { 4, "4" }, new object[] { 5, "5" } }; - - internal object[] InvalidData = new object[] { null, "xxx" }; - - [Test] - public void CanCompareIComparables() - { - ClassWithIComparable expected = new ClassWithIComparable(0); - ClassWithIComparable actual = new ClassWithIComparable(42); - Assert.That(actual, Is.GreaterThan(expected)); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void CanCompareIComparablesOfT() - { - ClassWithIComparableOfT expected = new ClassWithIComparableOfT(0); - ClassWithIComparableOfT actual = new ClassWithIComparableOfT(42); - Assert.That(actual, Is.GreaterThan(expected)); - } -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/GreaterThanOrEqualConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/GreaterThanOrEqualConstraintTests.cs deleted file mode 100644 index 3c679d070..000000000 --- a/test/NUnitLite/src/tests/Constraints/GreaterThanOrEqualConstraintTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class GreaterThanOrEqualConstraintTests : ComparisonConstraintTest - { - [SetUp] - public void SetUp() - { - theConstraint = comparisonConstraint = new GreaterThanOrEqualConstraint(5); - expectedDescription = "greater than or equal to 5"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 6, 5 }; - - internal object[] FailureData = new object[] { new object[] { 4, "4" } }; - - internal object[] InvalidData = new object[] { null, "xxx" }; - - [Test] - public void CanCompareIComparables() - { - ClassWithIComparable expected = new ClassWithIComparable(0); - ClassWithIComparable actual = new ClassWithIComparable(42); - Assert.That(actual, Is.GreaterThanOrEqualTo(expected)); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void CanCompareIComparablesOfT() - { - ClassWithIComparableOfT expected = new ClassWithIComparableOfT(0); - ClassWithIComparableOfT actual = new ClassWithIComparableOfT(42); - Assert.That(actual, Is.GreaterThanOrEqualTo(expected)); - } -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/InstanceOfTypeConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/InstanceOfTypeConstraintTests.cs deleted file mode 100644 index 32e3f25d3..000000000 --- a/test/NUnitLite/src/tests/Constraints/InstanceOfTypeConstraintTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class InstanceOfTypeConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new InstanceOfTypeConstraint(typeof(D1)); - expectedDescription = string.Format("instance of <{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); - } - - internal object[] SuccessData = new object[] { new D1(), new D2() }; - - internal object[] FailureData = new object[] { - new TestCaseData( new B(), "" ) - }; - - class B { } - - class D1 : B { } - - class D2 : D1 { } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/LessThanConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/LessThanConstraintTests.cs deleted file mode 100644 index d7e155d22..000000000 --- a/test/NUnitLite/src/tests/Constraints/LessThanConstraintTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class LessThanConstraintTests : ComparisonConstraintTest - { - [SetUp] - public void SetUp() - { - theConstraint = comparisonConstraint = new LessThanConstraint(5); - expectedDescription = "less than 5"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 4, 4.999 }; - - internal object[] FailureData = new object[] { new object[] { 6, "6" }, new object[] { 5, "5" } }; - - internal object[] InvalidData = new object[] { null, "xxx" }; - - [Test] - public void CanCompareIComparables() - { - ClassWithIComparable expected = new ClassWithIComparable(42); - ClassWithIComparable actual = new ClassWithIComparable(0); - Assert.That(actual, Is.LessThan(expected)); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void CanCompareIComparablesOfT() - { - ClassWithIComparableOfT expected = new ClassWithIComparableOfT(42); - ClassWithIComparableOfT actual = new ClassWithIComparableOfT(0); - Assert.That(actual, Is.LessThan(expected)); - } -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/LessThanOrEqualConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/LessThanOrEqualConstraintTests.cs deleted file mode 100644 index fdb2e5060..000000000 --- a/test/NUnitLite/src/tests/Constraints/LessThanOrEqualConstraintTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class LessThanOrEqualConstraintTests : ComparisonConstraintTest - { - [SetUp] - public void SetUp() - { - theConstraint = comparisonConstraint = new LessThanOrEqualConstraint(5); - expectedDescription = "less than or equal to 5"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 4, 5 }; - - internal object[] FailureData = new object[] { new object[] { 6, "6" } }; - - internal object[] InvalidData = new object[] { null, "xxx" }; - - [Test] - public void CanCompareIComparables() - { - ClassWithIComparable expected = new ClassWithIComparable(42); - ClassWithIComparable actual = new ClassWithIComparable(0); - Assert.That(actual, Is.LessThanOrEqualTo(expected)); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void CanCompareIComparablesOfT() - { - ClassWithIComparableOfT expected = new ClassWithIComparableOfT(42); - ClassWithIComparableOfT actual = new ClassWithIComparableOfT(0); - Assert.That(actual, Is.LessThanOrEqualTo(expected)); - } -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/MessageWriterTests.cs b/test/NUnitLite/src/tests/Constraints/MessageWriterTests.cs deleted file mode 100644 index 3718a83eb..000000000 --- a/test/NUnitLite/src/tests/Constraints/MessageWriterTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Internal; - -namespace NUnitLite.Tests -{ - class MessageWriterTests - { - protected TextMessageWriter writer; - - [SetUp] - public void SetUp() - { - writer = new TextMessageWriter(); - } - } - - [TestFixture] - class TestMessageWriterTests : MessageWriterTests - { - [Test] - public void ConnectorIsWrittenWithSurroundingSpaces() - { - writer.WriteConnector("and"); - Assert.That(writer.ToString(), Is.EqualTo(" and ")); - } - - [Test] - public void PredicateIsWrittenWithTrailingSpace() - { - writer.WritePredicate("contains"); - Assert.That(writer.ToString(), Is.EqualTo("contains ")); - } - - [TestFixture] - public class ExpectedValueTests : ValueTests - { - protected override void WriteValue(object obj) - { - writer.WriteExpectedValue(obj); - } - } - - [TestFixture] - public class ActualValueTests : ValueTests - { - protected override void WriteValue(object obj) - { - writer.WriteActualValue( obj ); - } - } - - public abstract class ValueTests : MessageWriterTests - { - protected abstract void WriteValue( object obj); - - [Test] - public void IntegerIsWrittenAsIs() - { - WriteValue(42); - Assert.That(writer.ToString(), Is.EqualTo("42")); - } - - [Test] - public void StringIsWrittenWithQuotes() - { - WriteValue("Hello"); - Assert.That(writer.ToString(), Is.EqualTo("\"Hello\"")); - } - - //[Test] - //public void ControlCharactersInStringsAreEscaped() - //{ - // WriteValue("Best Wishes,\r\n\tCharlie\r\n"); - // Assert.That(writer.ToString(), Is.EqualTo("\"Best Wishes,\\r\\n\\tCharlie\\r\\n\"")); - //} - - [Test] - public void FloatIsWrittenWithTrailingF() - { - WriteValue(0.5f); - Assert.That(writer.ToString(), Is.EqualTo("0.5f")); - } - - [Test] - public void FloatIsWrittenToNineDigits() - { - WriteValue(0.33333333333333f); - int digits = writer.ToString().Length - 3; // 0.dddddddddf - Assert.That(digits, Is.EqualTo(9)); - } - - [Test] - public void DoubleIsWrittenWithTrailingD() - { - WriteValue(0.5d); - Assert.That(writer.ToString(), Is.EqualTo("0.5d")); - } - - [Test] - public void DoubleIsWrittenToSeventeenDigits() - { - WriteValue(0.33333333333333333333333333333333333333333333d); - int digits = writer.ToString().Length - 3; - Assert.That(digits, Is.EqualTo(17)); - } - - [Test] - public void DecimalIsWrittenWithTrailingM() - { - WriteValue(0.5m); - Assert.That(writer.ToString(), Is.EqualTo("0.5m")); - } - - [Test] - public void DecimalIsWrittenToTwentyNineDigits() - { - WriteValue(12345678901234567890123456789m); - Assert.That(writer.ToString(), Is.EqualTo("12345678901234567890123456789m")); - } - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/MsgUtilTests.cs b/test/NUnitLite/src/tests/Constraints/MsgUtilTests.cs deleted file mode 100644 index 65d207ed1..000000000 --- a/test/NUnitLite/src/tests/Constraints/MsgUtilTests.cs +++ /dev/null @@ -1,128 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - /// - /// Summary description for MsgUtilTests. - /// - [TestFixture] - public class MsgUtilTests - { - [TestCase("\n", "\\n")] - [TestCase("\n\n", "\\n\\n")] - [TestCase("\n\n\n", "\\n\\n\\n")] - [TestCase("\r", "\\r")] - [TestCase("\r\r", "\\r\\r")] - [TestCase("\r\r\r", "\\r\\r\\r")] - [TestCase("\r\n", "\\r\\n")] - [TestCase("\n\r", "\\n\\r")] - [TestCase("This is a\rtest message", "This is a\\rtest message")] - [TestCase("", "")] -#if CLR_2_0 || CLR_4_0 - [TestCase(null, null)] -#endif - [TestCase("\t", "\\t")] - [TestCase("\t\n", "\\t\\n")] - [TestCase("\\r\\n", "\\\\r\\\\n")] - // TODO: Figure out why this fails in Mono - //[TestCase("\0", "\\0")] - [TestCase("\a", "\\a")] - [TestCase("\b", "\\b")] - [TestCase("\f", "\\f")] - [TestCase("\v", "\\v")] - [TestCase("\x0085", "\\x0085", Description = "Next line character")] - [TestCase("\x2028", "\\x2028", Description = "Line separator character")] - [TestCase("\x2029", "\\x2029", Description = "Paragraph separator character")] - public void EscapeControlCharsTest(string input, string expected) - { - Assert.That( MsgUtils.EscapeControlChars(input), Is.EqualTo(expected) ); - } - - [Test] - public void EscapeNullCharInString() - { - Assert.That(MsgUtils.EscapeControlChars("\0"), Is.EqualTo("\\0")); - } - - private const string s52 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - [TestCase(s52, 52, 0, s52, TestName="NoClippingNeeded")] - [TestCase(s52, 29, 0, "abcdefghijklmnopqrstuvwxyz...", TestName="ClipAtEnd")] - [TestCase(s52, 29, 26, "...ABCDEFGHIJKLMNOPQRSTUVWXYZ", TestName="ClipAtStart")] - [TestCase(s52, 28, 26, "...ABCDEFGHIJKLMNOPQRSTUV...", TestName="ClipAtStartAndEnd")] - public void TestClipString(string input, int max, int start, string result) - { - System.Console.WriteLine("input= \"{0}\"", input); - System.Console.WriteLine("result= \"{0}\"", result); - Assert.That(MsgUtils.ClipString(input, max, start), Is.EqualTo(result)); - } - - //[TestCase('\0')] - //[TestCase('\r')] - //public void CharacterArgumentTest(char c) - //{ - //} - - [Test] - public void ClipExpectedAndActual_StringsFitInLine() - { - string eClip = s52; - string aClip = "abcde"; - MsgUtils.ClipExpectedAndActual(ref eClip, ref aClip, 52, 5); - Assert.That(eClip, Is.EqualTo(s52)); - Assert.That(aClip, Is.EqualTo("abcde")); - - eClip = s52; - aClip = "abcdefghijklmno?qrstuvwxyz"; - MsgUtils.ClipExpectedAndActual(ref eClip, ref aClip, 52, 15); - Assert.That(eClip, Is.EqualTo(s52)); - Assert.That(aClip, Is.EqualTo("abcdefghijklmno?qrstuvwxyz")); - } - - [Test] - public void ClipExpectedAndActual_StringTailsFitInLine() - { - string s1 = s52; - string s2 = s52.Replace('Z', '?'); - MsgUtils.ClipExpectedAndActual(ref s1, ref s2, 29, 51); - Assert.That(s1, Is.EqualTo("...ABCDEFGHIJKLMNOPQRSTUVWXYZ")); - } - - [Test] - public void ClipExpectedAndActual_StringsDoNotFitInLine() - { - string s1 = s52; - string s2 = "abcdefghij"; - MsgUtils.ClipExpectedAndActual(ref s1, ref s2, 29, 10); - Assert.That(s1, Is.EqualTo("abcdefghijklmnopqrstuvwxyz...")); - Assert.That(s2, Is.EqualTo("abcdefghij")); - - s1 = s52; - s2 = "abcdefghijklmno?qrstuvwxyz"; - MsgUtils.ClipExpectedAndActual(ref s1, ref s2, 25, 15); - Assert.That(s1, Is.EqualTo("...efghijklmnopqrstuvw...")); - Assert.That(s2, Is.EqualTo("...efghijklmno?qrstuvwxyz")); - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/NUnitComparerTests.cs b/test/NUnitLite/src/tests/Constraints/NUnitComparerTests.cs deleted file mode 100644 index e06873935..000000000 --- a/test/NUnitLite/src/tests/Constraints/NUnitComparerTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class NUnitComparerTests - { - private Tolerance tolerance; - private NUnitComparer comparer; - - [SetUp] - public void SetUp() - { - tolerance = Tolerance.Empty; - comparer = new NUnitComparer(); - } - - [TestCase(4, 4)] - [TestCase(4.0d, 4.0d)] - [TestCase(4.0f, 4.0f)] - [TestCase(4, 4.0d)] - [TestCase(4, 4.0f)] - [TestCase(4.0d, 4)] - [TestCase(4.0d, 4.0f)] - [TestCase(4.0f, 4)] - [TestCase(4.0f, 4.0d)] - [TestCase(SpecialValue.Null, SpecialValue.Null)] -#if CLR_2_0 || CLR_4_0 - [TestCase(null, null)] -#endif - public void EqualItems(object x, object y) - { - Assert.That(comparer.Compare(x, y) == 0); - } - - [TestCase(4, 2)] - [TestCase(4.0d, 2.0d)] - [TestCase(4.0f, 2.0f)] - [TestCase(4, 2.0d)] - [TestCase(4, 2.0f)] - [TestCase(4.0d, 2)] - [TestCase(4.0d, 2.0f)] - [TestCase(4.0f, 2)] - [TestCase(4.0f, 2.0d)] - [TestCase(4, SpecialValue.Null)] -#if CLR_2_0 || CLR_4_0 - [TestCase(4, null)] -#endif - public void UnequalItems(object greater, object lesser) - { - Assert.That(comparer.Compare(greater, lesser) > 0); - Assert.That(comparer.Compare(lesser, greater) < 0); - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/NUnitEqualityComparerTests.cs b/test/NUnitLite/src/tests/Constraints/NUnitEqualityComparerTests.cs deleted file mode 100644 index 411fef1ef..000000000 --- a/test/NUnitLite/src/tests/Constraints/NUnitEqualityComparerTests.cs +++ /dev/null @@ -1,208 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2011 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - [TestFixture] - public class EqualityComparerTests - { - private Tolerance tolerance; - private NUnitEqualityComparer comparer; - - [SetUp] - public void Setup() - { - tolerance = Tolerance.Empty; - comparer = new NUnitEqualityComparer(); - } - - [TestCase(4, 4)] - [TestCase(4.0d, 4.0d)] - [TestCase(4.0f, 4.0f)] - [TestCase(4, 4.0d)] - [TestCase(4, 4.0f)] - [TestCase(4.0d, 4)] - [TestCase(4.0d, 4.0f)] - [TestCase(4.0f, 4)] - [TestCase(4.0f, 4.0d)] - [TestCase(SpecialValue.Null, SpecialValue.Null)] -#if CLR_2_0 || CLR_4_0 - [TestCase(null, null)] -#endif - public void EqualItems(object x, object y) - { - Assert.That(comparer.AreEqual(x, y, ref tolerance)); - } - - [TestCase(4, 2)] - [TestCase(4.0d, 2.0d)] - [TestCase(4.0f, 2.0f)] - [TestCase(4, 2.0d)] - [TestCase(4, 2.0f)] - [TestCase(4.0d, 2)] - [TestCase(4.0d, 2.0f)] - [TestCase(4.0f, 2)] - [TestCase(4.0f, 2.0d)] - [TestCase(4, SpecialValue.Null)] -#if CLR_2_0 || CLR_4_0 - [TestCase(4, null)] -#endif - public void UnequalItems(object greater, object lesser) - { - Assert.False(comparer.AreEqual(greater, lesser, ref tolerance)); - Assert.False(comparer.AreEqual(lesser, greater, ref tolerance)); - } - - [TestCase(double.PositiveInfinity, double.PositiveInfinity)] - [TestCase(double.NegativeInfinity, double.NegativeInfinity)] - [TestCase(double.NaN, double.NaN)] - [TestCase(float.PositiveInfinity, float.PositiveInfinity)] - [TestCase(float.NegativeInfinity, float.NegativeInfinity)] - [TestCase(float.NaN, float.NaN)] - public void SpecialFloatingPointValuesCompareAsEqual(object x, object y) - { - Assert.That(comparer.AreEqual(x, y, ref tolerance)); - } - - [Test] - public void CanCompareArrayContainingSelfToSelf() - { - object[] array = new object[1]; - array[0] = array; - - Assert.True(comparer.AreEqual(array, array, ref tolerance)); - } - -#if CLR_2_0 || CLR_4_0 -#if !NETCF - [Test] - public void IEquatableSuccess() - { - IEquatableWithoutEqualsOverridden x = new IEquatableWithoutEqualsOverridden(1); - IEquatableWithoutEqualsOverridden y = new IEquatableWithoutEqualsOverridden(1); - - Assert.IsTrue(comparer.AreEqual(x, y, ref tolerance)); - } - - [Test] - public void IEquatableDifferentTypesSuccess_WhenActualImplementsIEquatable() - { - int x = 1; - Int32IEquatable y = new Int32IEquatable(1); - - // y.Equals(x) is what gets actually called - // TODO: This should work both ways - Assert.IsTrue(comparer.AreEqual(x, y, ref tolerance)); - } - - [Test] - public void IEquatableDifferentTypesSuccess_WhenExpectedImplementsIEquatable() - { - int x = 1; - Int32IEquatable y = new Int32IEquatable(1); - - // y.Equals(x) is what gets actually called - // TODO: This should work both ways - Assert.IsTrue(comparer.AreEqual(y, x, ref tolerance)); - } - - [Test] - public void IEquatableHasPrecedenceOverDefaultEquals() - { - NeverEqualIEquatableWithOverriddenAlwaysTrueEquals x = new NeverEqualIEquatableWithOverriddenAlwaysTrueEquals(); - NeverEqualIEquatableWithOverriddenAlwaysTrueEquals y = new NeverEqualIEquatableWithOverriddenAlwaysTrueEquals(); - - Assert.IsFalse(comparer.AreEqual(x, y, ref tolerance)); - } -#endif - - [Test] - public void ReferenceEqualityHasPrecedenceOverIEquatable() - { - NeverEqualIEquatable z = new NeverEqualIEquatable(); - - Assert.IsTrue(comparer.AreEqual(z, z, ref tolerance)); - } -#endif - } - -#if CLR_2_0 || CLR_4_0 - public class NeverEqualIEquatableWithOverriddenAlwaysTrueEquals : IEquatable - { - public bool Equals(NeverEqualIEquatableWithOverriddenAlwaysTrueEquals other) - { - return false; - } - - public override bool Equals(object obj) - { - return true; - } - - public override int GetHashCode() - { - return base.GetHashCode(); - } - } - - public class Int32IEquatable : IEquatable - { - private readonly int value; - - public Int32IEquatable(int value) - { - this.value = value; - } - - public bool Equals(int other) - { - return value.Equals(other); - } - } - - public class NeverEqualIEquatable : IEquatable - { - public bool Equals(NeverEqualIEquatable other) - { - return false; - } - } - - public class IEquatableWithoutEqualsOverridden : IEquatable - { - private readonly int value; - - public IEquatableWithoutEqualsOverridden(int value) - { - this.value = value; - } - - public bool Equals(IEquatableWithoutEqualsOverridden other) - { - return value.Equals(other.value); - } - } -#endif -} diff --git a/test/NUnitLite/src/tests/Constraints/NotConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/NotConstraintTests.cs deleted file mode 100644 index 72656e9d4..000000000 --- a/test/NUnitLite/src/tests/Constraints/NotConstraintTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class NotConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new NotConstraint( new EqualConstraint(null) ); - expectedDescription = "not null"; - stringRepresentation = ">"; - } - - internal object[] SuccessData = new object[] { 42, "Hello" }; - - internal object[] FailureData = new object[] { new object[] { null, "null" } }; - - [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "ignoring case", MatchType = MessageMatch.Contains)] - public void NotHonorsIgnoreCaseUsingConstructors() - { - Assert.That("abc", new NotConstraint(new EqualConstraint("ABC").IgnoreCase)); - } - - [Test,ExpectedException(typeof(AssertionException),ExpectedMessage="ignoring case",MatchType=MessageMatch.Contains)] - public void NotHonorsIgnoreCaseUsingPrefixNotation() - { - Assert.That( "abc", Is.Not.EqualTo( "ABC" ).IgnoreCase ); - } - - [Test,ExpectedException(typeof(AssertionException),ExpectedMessage="+/-",MatchType=MessageMatch.Contains)] - public void NotHonorsTolerance() - { - Assert.That( 4.99d, Is.Not.EqualTo( 5.0d ).Within( .05d ) ); - } - - [Test] - public void CanUseNotOperator() - { - Assert.That(42, !new EqualConstraint(99)); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/NumericsTest.cs b/test/NUnitLite/src/tests/Constraints/NumericsTest.cs deleted file mode 100644 index 64baa3866..000000000 --- a/test/NUnitLite/src/tests/Constraints/NumericsTest.cs +++ /dev/null @@ -1,112 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class NumericsTest - { - private Tolerance tenPercent, zeroTolerance; - - [SetUp] - public void SetUp() - { - tenPercent = new Tolerance(10.0).Percent; - zeroTolerance = new Tolerance(0); - } - - [TestCase(123456789)] - [TestCase(123456789U)] - [TestCase(123456789L)] - [TestCase(123456789UL)] - [TestCase(1234.5678f)] - [TestCase(1234.5678)] - [Test] - public void CanMatchWithoutToleranceMode(object value) - { - Assert.IsTrue(Numerics.AreEqual(value, value, ref zeroTolerance)); - } - - // Separate test case because you can't use decimal in an attribute (24.1.3) - [Test] - public void CanMatchDecimalWithoutToleranceMode() - { - Assert.IsTrue(Numerics.AreEqual(123m, 123m, ref zeroTolerance)); - } - - [TestCase((int)9500)] - [TestCase((int)10000)] - [TestCase((int)10500)] - [TestCase((uint)9500)] - [TestCase((uint)10000)] - [TestCase((uint)10500)] - [TestCase((long)9500)] - [TestCase((long)10000)] - [TestCase((long)10500)] - [TestCase((ulong)9500)] - [TestCase((ulong)10000)] - [TestCase((ulong)10500)] - [Test] - public void CanMatchIntegralsWithPercentage(object value) - { - Assert.IsTrue(Numerics.AreEqual(10000, value, ref tenPercent)); - } - - [Test] - public void CanMatchDecimalWithPercentage() - { - Assert.IsTrue(Numerics.AreEqual(10000m, 9500m, ref tenPercent)); - Assert.IsTrue(Numerics.AreEqual(10000m, 10000m, ref tenPercent)); - Assert.IsTrue(Numerics.AreEqual(10000m, 10500m, ref tenPercent)); - } - - [TestCase((int)8500)] - [TestCase((int)11500)] - [TestCase((uint)8500)] - [TestCase((uint)11500)] - [TestCase((long)8500)] - [TestCase((long)11500)] - [TestCase((ulong)8500)] - [TestCase((ulong)11500)] - [Test, ExpectedException(typeof(AssertionException))] - public void FailsOnIntegralsOutsideOfPercentage(object value) - { - Assert.IsTrue(Numerics.AreEqual(10000, value, ref tenPercent)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailsOnDecimalBelowPercentage() - { - Assert.IsTrue(Numerics.AreEqual(10000m, 8500m, ref tenPercent)); - } - - [Test, ExpectedException(typeof(AssertionException))] - public void FailsOnDecimalAbovePercentage() - { - Assert.IsTrue(Numerics.AreEqual(10000m, 11500m, ref tenPercent)); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/OrConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/OrConstraintTests.cs deleted file mode 100644 index 23b61f308..000000000 --- a/test/NUnitLite/src/tests/Constraints/OrConstraintTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class OrConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new OrConstraint(new EqualConstraint(42), new EqualConstraint(99)); - expectedDescription = "42 or 99"; - stringRepresentation = " >"; - } - - internal object[] SuccessData = new object[] { 99, 42 }; - - internal object[] FailureData = new object[] { new object[] { 37, "37" } }; - - [Test] - public void CanCombineTestsWithOrOperator() - { - Assert.That(99, new EqualConstraint(42) | new EqualConstraint(99) ); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/PathConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/PathConstraintTests.cs deleted file mode 100644 index 6b06ba896..000000000 --- a/test/NUnitLite/src/tests/Constraints/PathConstraintTests.cs +++ /dev/null @@ -1,252 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints.Tests -{ - /// - /// Summary description for PathConstraintTests. - /// ] - [TestFixture] - public class SamePathTest_Windows : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SamePathConstraint( @"C:\folder1\file.tmp" ).IgnoreCase; - expectedDescription = @"Path matching ""C:\folder1\file.tmp"""; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] - { - @"C:\folder1\file.tmp", - @"C:\Folder1\File.TMP", - @"C:\folder1\.\file.tmp", - @"C:\folder1\folder2\..\file.tmp", - @"C:\FOLDER1\.\folder2\..\File.TMP", - @"C:/folder1/file.tmp" - }; - internal object[] FailureData = new object[] - { - new TestCaseData( 123, "123" ), - new TestCaseData( @"C:\folder2\file.tmp", "\"C:\\folder2\\file.tmp\"" ), - new TestCaseData( @"C:\folder1\.\folder2\..\file.temp", "\"C:\\folder1\\.\\folder2\\..\\file.temp\"" ) - }; - - [Test] - public void RootPathEquality() - { - Assert.That("c:\\", Is.SamePath("C:\\junk\\..\\").IgnoreCase); - } - } - - [TestFixture] - public class SamePathTest_Linux : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SamePathConstraint(@"/folder1/folder2").RespectCase; - expectedDescription = @"Path matching ""/folder1/folder2"""; - stringRepresentation = @""; - } - - internal object[] SuccessData = new object[] - { - @"/folder1/folder2", - @"/folder1/folder2/", - @"/folder1/./folder2", - @"/folder1/./folder2/", - @"/folder1/junk/../folder2", - @"/folder1/junk/../folder2/", - @"/folder1/./junk/../folder2", - @"/folder1/./junk/../folder2/", - @"\folder1\folder2", - @"\folder1\folder2\" - }; - internal object[] FailureData = new object[] - { - new TestCaseData( 123, "123" ), - new TestCaseData("folder1/folder2", "\"folder1/folder2\""), - new TestCaseData("//folder1/folder2", "\"//folder1/folder2\""), - new TestCaseData( @"/junk/folder2", "\"/junk/folder2\"" ), - new TestCaseData( @"/folder1/./junk/../file.temp", "\"/folder1/./junk/../file.temp\"" ), - new TestCaseData( @"/Folder1/FOLDER2", "\"/Folder1/FOLDER2\"" ), - new TestCaseData( @"/FOLDER1/./junk/../FOLDER2", "\"/FOLDER1/./junk/../FOLDER2\"" ) - }; - - [Test] - public void RootPathEquality() - { - Assert.That("/", Is.SamePath("/junk/../")); - } - } - - [TestFixture] - public class SubPathTest_Windows : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SubPathConstraint(@"C:\folder1\folder2").IgnoreCase; - expectedDescription = @"Path under ""C:\folder1\folder2"""; - stringRepresentation = @""; - } - - internal object[] SuccessData = new object[] - { - @"C:\folder1\folder2\folder3", - @"C:\folder1\.\folder2\folder3", - @"C:\folder1\junk\..\folder2\folder3", - @"C:\FOLDER1\.\junk\..\Folder2\temp\..\Folder3", - @"C:/folder1/folder2/folder3", - }; - internal object[] FailureData = new object[] - { - new TestCaseData(123, "123"), - new TestCaseData(@"C:\folder1\folder3", "\"C:\\folder1\\folder3\""), - new TestCaseData(@"C:\folder1\.\folder2\..\file.temp", "\"C:\\folder1\\.\\folder2\\..\\file.temp\""), - new TestCaseData(@"C:\folder1\folder2", "\"C:\\folder1\\folder2\""), - new TestCaseData(@"C:\Folder1\Folder2", "\"C:\\Folder1\\Folder2\""), - new TestCaseData(@"C:\folder1\.\folder2", "\"C:\\folder1\\.\\folder2\""), - new TestCaseData(@"C:\folder1\junk\..\folder2", "\"C:\\folder1\\junk\\..\\folder2\""), - new TestCaseData(@"C:\FOLDER1\.\junk\..\Folder2", "\"C:\\FOLDER1\\.\\junk\\..\\Folder2\""), - new TestCaseData(@"C:/folder1/folder2", "\"C:/folder1/folder2\"") - }; - - [Test] - public void SubPathOfRoot() - { - Assert.That("C:\\junk\\file.temp", new SubPathConstraint("C:\\")); - } - } - - [TestFixture] - public class SubPathTest_Linux : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SubPathConstraint(@"/folder1/folder2").RespectCase; - expectedDescription = @"Path under ""/folder1/folder2"""; - stringRepresentation = @""; - } - - internal object[] SuccessData = new object[] - { - @"/folder1/folder2/folder3", - @"/folder1/./folder2/folder3", - @"/folder1/junk/../folder2/folder3", - @"\folder1\folder2\folder3", - }; - internal object[] FailureData = new object[] - { - new TestCaseData(123, "123"), - new TestCaseData("/Folder1/Folder2", "\"/Folder1/Folder2\""), - new TestCaseData("/FOLDER1/./junk/../Folder2", "\"/FOLDER1/./junk/../Folder2\""), - new TestCaseData("/FOLDER1/./junk/../Folder2/temp/../Folder3", "\"/FOLDER1/./junk/../Folder2/temp/../Folder3\""), - new TestCaseData("/folder1/folder3", "\"/folder1/folder3\""), - new TestCaseData("/folder1/./folder2/../folder3", "\"/folder1/./folder2/../folder3\""), - new TestCaseData("/folder1", "\"/folder1\""), - new TestCaseData("/folder1/folder2", "\"/folder1/folder2\""), - new TestCaseData("/folder1/./folder2", "\"/folder1/./folder2\""), - new TestCaseData("/folder1/junk/../folder2", "\"/folder1/junk/../folder2\""), - new TestCaseData(@"\folder1\folder2", "\"\\folder1\\folder2\"") - }; - - [Test] - public void SubPathOfRoot() - { - Assert.That("/junk/file.temp", new SubPathConstraint("/")); - } - } - - [TestFixture] - public class SamePathOrUnderTest_Windows : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SamePathOrUnderConstraint( @"C:\folder1\folder2" ).IgnoreCase; - expectedDescription = @"Path under or matching ""C:\folder1\folder2"""; - stringRepresentation = @""; - } - - internal object[] SuccessData = new object[] - { - @"C:\folder1\folder2", - @"C:\Folder1\Folder2", - @"C:\folder1\.\folder2", - @"C:\folder1\junk\..\folder2", - @"C:\FOLDER1\.\junk\..\Folder2", - @"C:/folder1/folder2", - @"C:\folder1\folder2\folder3", - @"C:\folder1\.\folder2\folder3", - @"C:\folder1\junk\..\folder2\folder3", - @"C:\FOLDER1\.\junk\..\Folder2\temp\..\Folder3", - @"C:/folder1/folder2/folder3", - }; - internal object[] FailureData = new object[] - { - new TestCaseData( 123, "123" ), - new TestCaseData( @"C:\folder1\folder3", "\"C:\\folder1\\folder3\"" ), - new TestCaseData( @"C:\folder1\.\folder2\..\file.temp", "\"C:\\folder1\\.\\folder2\\..\\file.temp\"" ) - }; - } - - [TestFixture] - public class SamePathOrUnderTest_Linux : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SamePathOrUnderConstraint( @"/folder1/folder2" ).RespectCase; - expectedDescription = @"Path under or matching ""/folder1/folder2"""; - stringRepresentation = @""; - } - - internal object[] SuccessData = new object[] - { - @"/folder1/folder2", - @"/folder1/./folder2", - @"/folder1/junk/../folder2", - @"\folder1\folder2", - @"/folder1/folder2/folder3", - @"/folder1/./folder2/folder3", - @"/folder1/junk/../folder2/folder3", - @"\folder1\folder2\folder3", - }; - internal object[] FailureData = new object[] - { - new TestCaseData( 123, "123" ), - new TestCaseData( "/Folder1/Folder2", "\"/Folder1/Folder2\"" ), - new TestCaseData( "/FOLDER1/./junk/../Folder2", "\"/FOLDER1/./junk/../Folder2\"" ), - new TestCaseData( "/FOLDER1/./junk/../Folder2/temp/../Folder3", "\"/FOLDER1/./junk/../Folder2/temp/../Folder3\"" ), - new TestCaseData( "/folder1/folder3", "\"/folder1/folder3\"" ), - new TestCaseData( "/folder1/./folder2/../folder3", "\"/folder1/./folder2/../folder3\"" ), - new TestCaseData( "/folder1", "\"/folder1\"" ) - }; - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/PredicateConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/PredicateConstraintTests.cs deleted file mode 100644 index aa36533f9..000000000 --- a/test/NUnitLite/src/tests/Constraints/PredicateConstraintTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if (CLR_2_0 || CLR_4_0) && !NETCF_2_0 -using System; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class PredicateConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new PredicateConstraint((x) => x < 5 ); - expectedDescription = @"value matching lambda expression"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] - { - 0, - -5 - }; - - internal object[] FailureData = new object[] - { - new TestCaseData(123, "123") - }; - - [Test] - public void CanUseConstraintExpressionSyntax() - { - Assert.That(123, Is.TypeOf().And.Matches((int x) => x > 100)); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Constraints/PropertyTests.cs b/test/NUnitLite/src/tests/Constraints/PropertyTests.cs deleted file mode 100644 index e4b2d8d4f..000000000 --- a/test/NUnitLite/src/tests/Constraints/PropertyTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -// TODO: Remove NUNITLITE conditional code -using System; -using System.Collections; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - public class PropertyExistsTest -#if NUNITLITE - : ConstraintTestBase -#else - : ConstraintTestBaseWithExceptionTests -#endif - { - [SetUp] - public void SetUp() - { - theConstraint = new PropertyExistsConstraint("Length"); - expectedDescription = "property Length"; - stringRepresentation = ""; - } - - internal static object[] SuccessData = new object[] { new int[0], "hello", typeof(Array) }; - - internal static object[] FailureData = new object[] { - new TestCaseData( 42, "" ), - new TestCaseData( new SimpleObjectCollection(), "" ), - new TestCaseData( typeof(Int32), "" ) }; -#if !NUNITLITE - internal static object[] InvalidData = new TestCaseData[] - { - new TestCaseData(null).Throws(typeof(ArgumentNullException)) - }; -#endif - } - - public class PropertyTest -#if NUNITLITE - : ConstraintTestBase -#else - : ConstraintTestBaseWithExceptionTests -#endif - { - [SetUp] - public void SetUp() - { - theConstraint = new PropertyConstraint("Length", new EqualConstraint(5)); - expectedDescription = "property Length equal to 5"; - stringRepresentation = ">"; - } - - internal static object[] SuccessData = new object[] { new int[5], "hello" }; - - internal static object[] FailureData = new object[] { - new TestCaseData( new int[3], "3" ), - new TestCaseData( "goodbye", "7" ) }; -#if !NUNITLITE - internal static object[] InvalidData = new object[] - { - new TestCaseData(null).Throws(typeof(ArgumentNullException)), - new TestCaseData(42).Throws(typeof(ArgumentException)), - new TestCaseData(new System.Collections.ArrayList()).Throws(typeof(ArgumentException)) - }; -#endif - - [Test] - public void PropertyEqualToValueWithTolerance() - { - Constraint c = new EqualConstraint(105m).Within(0.1m); - TextMessageWriter w = new TextMessageWriter(); - c.WriteDescriptionTo(w); - Assert.That(w.ToString(), Is.EqualTo("105m +/- 0.1m")); - - c = new PropertyConstraint("D", new EqualConstraint(105m).Within(0.1m)); - w = new TextMessageWriter(); - c.WriteDescriptionTo(w); - Assert.That(w.ToString(), Is.EqualTo("property D equal to 105m +/- 0.1m")); - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/RangeConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/RangeConstraintTests.cs deleted file mode 100644 index eab4e4e96..000000000 --- a/test/NUnitLite/src/tests/Constraints/RangeConstraintTests.cs +++ /dev/null @@ -1,117 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class RangeConstraintTest : ConstraintTestBaseWithArgumentException - { -#if CLR_2_0 || CLR_4_0 - RangeConstraint rangeConstraint; -#else - RangeConstraint rangeConstraint; -#endif - - [SetUp] - public void SetUp() - { -#if CLR_2_0 || CLR_4_0 - theConstraint = rangeConstraint = new RangeConstraint(5, 42); -#else - theConstraint = rangeConstraint = new RangeConstraint(5, 42); -#endif - expectedDescription = "in range (5,42)"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 5, 23, 42 }; - - internal object[] FailureData = new object[] { new object[] { 4, "4" }, new object[] { 43, "43" } }; - - internal object[] InvalidData = new object[] { null, "xxx" }; - - [Test] - public void UsesProvidedIComparer() - { - SimpleObjectComparer comparer = new SimpleObjectComparer(); - Assert.That(rangeConstraint.Using(comparer).Matches(19)); - Assert.That(comparer.Called, "Comparer was not called"); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void UsesProvidedComparerOfT() - { - MyComparer comparer = new MyComparer(); - Assert.That(rangeConstraint.Using(comparer).Matches(19)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparer : IComparer - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - - [Test] - public void UsesProvidedComparisonOfT() - { - MyComparison comparer = new MyComparison(); - Assert.That(rangeConstraint.Using(new Comparison(comparer.Compare)).Matches(19)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - class MyComparison - { - public bool Called; - - public int Compare(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y); - } - } - -#if !NETCF_2_0 - [Test] - public void UsesProvidedLambda() - { - Comparison comparer = (x, y) => x.CompareTo(y); - Assert.That(rangeConstraint.Using(comparer).Matches(19)); - } -#endif -#endif - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/RangeTests.cs b/test/NUnitLite/src/tests/Constraints/RangeTests.cs deleted file mode 100644 index 15b688495..000000000 --- a/test/NUnitLite/src/tests/Constraints/RangeTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class RangeTests - { - [Test] - public void InRangeSucceeds() - { - Assert.That( 7, Is.InRange(5, 10) ); - Assert.That(0.23, Is.InRange(-1.0, 1.0)); - Assert.That(DateTime.Parse("12-December-2008"), - Is.InRange(DateTime.Parse("1-October-2008"), DateTime.Parse("31-December-2008"))); - } - - [Test] - public void InRangeFails() - { - string expectedMessage = string.Format(" Expected: in range (5,10){0} But was: 12{0}", - Env.NewLine); - - Assert.That( - new TestDelegate( FailingInRangeMethod ), - Throws.TypeOf(typeof(AssertionException)).With.Message.EqualTo(expectedMessage)); - } - - private void FailingInRangeMethod() - { - Assert.That(12, Is.InRange(5, 10)); - } - - [Test] - public void NotInRangeSucceeds() - { - Assert.That(12, Is.Not.InRange(5, 10)); - Assert.That(2.57, Is.Not.InRange(-1.0, 1.0)); - } - - [Test] - public void NotInRangeFails() - { - string expectedMessage = string.Format(" Expected: not in range (5,10){0} But was: 7{0}", - Env.NewLine); - - Assert.That( - new TestDelegate(FailingNotInRangeMethod), - Throws.TypeOf(typeof(AssertionException)).With.Message.EqualTo(expectedMessage)); - } - - private void FailingNotInRangeMethod() - { - Assert.That(7, Is.Not.InRange(5, 10)); - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/ReusableConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/ReusableConstraintTests.cs deleted file mode 100644 index 209a84094..000000000 --- a/test/NUnitLite/src/tests/Constraints/ReusableConstraintTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -// **************************************************************** -// Copyright 2012, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - [TestFixture] - public class ReusableConstraintTests - { - [Datapoints] - internal static readonly ReusableConstraint[] constraints = new ReusableConstraint[] { - Is.Not.Empty, - Is.Not.Null, - Has.Length.GreaterThan(3), - Has.Property("Length").EqualTo(4).And.StartsWith("te") - }; - - [Theory] - public void CanReuseReusableConstraintMultipleTimes(ReusableConstraint c) - { - string s = "test"; - - Assume.That(s, c); - - Assert.That(s, c, "Should pass first time"); - Assert.That(s, c, "Should pass second time"); - Assert.That(s, c, "Should pass third time"); - } - - [Test] - public void CanCreateReusableConstraintByImplicitConversion() - { - ReusableConstraint c = Is.Not.Null; - - string s = "test"; - Assert.That(s, c, "Should pass first time"); - Assert.That(s, c, "Should pass second time"); - Assert.That(s, c, "Should pass third time"); - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/SameAsTest.cs b/test/NUnitLite/src/tests/Constraints/SameAsTest.cs deleted file mode 100644 index 8d41d943a..000000000 --- a/test/NUnitLite/src/tests/Constraints/SameAsTest.cs +++ /dev/null @@ -1,47 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class SameAsTest : ConstraintTestBase - { - private static readonly object obj1 = new object(); - private static readonly object obj2 = new object(); - - [SetUp] - public void SetUp() - { - theConstraint = new SameAsConstraint(obj1); - expectedDescription = "same as "; - stringRepresentation = ""; - } - - internal static object[] SuccessData = new object[] { obj1 }; - - internal static object[] FailureData = new object[] { - new TestCaseData( obj2, "" ), - new TestCaseData( 3, "3" ), - new TestCaseData( "Hello", "\"Hello\"" ) }; - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Constraints/StartsWithConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/StartsWithConstraintTests.cs deleted file mode 100644 index 566df125b..000000000 --- a/test/NUnitLite/src/tests/Constraints/StartsWithConstraintTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class StartsWithConstraintTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new StartsWithConstraint("hello"); - expectedDescription = "String starting with \"hello\""; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { "hello", "hello there" }; - - internal object[] FailureData = new object[] { - new TestCaseData( "goodbye", "\"goodbye\"" ), - new TestCaseData( "HELLO THERE", "\"HELLO THERE\"" ), - new TestCaseData( "I said hello", "\"I said hello\"" ), - new TestCaseData( "say hello to Fred", "\"say hello to Fred\"" ), - new TestCaseData( string.Empty, "" ), - new TestCaseData( null , "null" ) }; - } - - [TestFixture] - public class StartsWithConstraintTestsIgnoringCase : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new StartsWithConstraint("hello").IgnoreCase; - expectedDescription = "String starting with \"hello\", ignoring case"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { "Hello", "HELLO there" }; - - internal object[] FailureData = new object[] { - new TestCaseData( "goodbye", "\"goodbye\"" ), - new TestCaseData( "What the hell?", "\"What the hell?\"" ), - new TestCaseData( "I said hello", "\"I said hello\"" ), - new TestCaseData( "say hello to Fred", "\"say hello to Fred\"" ), - new TestCaseData( string.Empty, "" ), - new TestCaseData( null , "null" ) }; - } -} diff --git a/test/NUnitLite/src/tests/Constraints/SubstringConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/SubstringConstraintTests.cs deleted file mode 100644 index f61b85639..000000000 --- a/test/NUnitLite/src/tests/Constraints/SubstringConstraintTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class SubstringConstraintTests : ConstraintTestBase, IExpectException - { - [SetUp] - public void SetUp() - { - theConstraint = new SubstringConstraint("hello"); - expectedDescription = "String containing \"hello\""; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { "hello", "hello there", "I said hello", "say hello to fred" }; - - internal object[] FailureData = new object[] { - new TestCaseData( "goodbye", "\"goodbye\"" ), - new TestCaseData( "HELLO", "\"HELLO\"" ), - new TestCaseData( "What the hell?", "\"What the hell?\"" ), - new TestCaseData( string.Empty, "" ), - new TestCaseData( null, "null" ) }; - - public void HandleException(Exception ex) - { - string NL = Env.NewLine; - - Assert.That(ex.Message, new EqualConstraint( - TextMessageWriter.Pfx_Expected + "String containing \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...\"" + NL + - TextMessageWriter.Pfx_Actual + "\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...\"" + NL)); - } - } - - [TestFixture] - public class SubstringConstraintTestsIgnoringCase : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new SubstringConstraint("hello").IgnoreCase; - expectedDescription = "String containing \"hello\", ignoring case"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { "Hello", "HellO there", "I said HELLO", "say hello to fred" }; - - internal object[] FailureData = new object[] { - new TestCaseData( "goodbye", "\"goodbye\"" ), - new TestCaseData( "What the hell?", "\"What the hell?\"" ), - new TestCaseData( string.Empty, "" ), - new TestCaseData( null, "null" ) }; - } - - //[TestFixture] - //public class EqualIgnoringCaseTest : ConstraintTest - //{ - // [SetUp] - // public void SetUp() - // { - // Matcher = new EqualConstraint("Hello World!").IgnoreCase; - // Description = "\"Hello World!\", ignoring case"; - // } - - // internal object[] SuccessData = new object[] { "hello world!", "Hello World!", "HELLO world!" }; - - // internal object[] FailureData = new object[] { "goodbye", "Hello Friends!", string.Empty, null }; - - - // internal string[] ActualValues = new string[] { "\"goodbye\"", "\"Hello Friends!\"", "", "null" }; - //} -} diff --git a/test/NUnitLite/src/tests/Constraints/TestDelegates.cs b/test/NUnitLite/src/tests/Constraints/TestDelegates.cs deleted file mode 100644 index d1d45eb9c..000000000 --- a/test/NUnitLite/src/tests/Constraints/TestDelegates.cs +++ /dev/null @@ -1,35 +0,0 @@ -// **************************************************************** -// Copyright 2008, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org/?p=license&r=2.4 -// **************************************************************** -using System; - -namespace NUnitLite.Tests -{ - public class TestDelegates - { - public static void ThrowsArgumentException() - { - throw new ArgumentException("myMessage", "myParam"); - } - - public static void ThrowsSystemException() - { - throw new Exception(); - } - - public static void ThrowsNothing() - { - } - - public static void ThrowsDerivedException() - { - throw new DerivedException(); - } - - public class DerivedException : Exception - { - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/ThrowsConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/ThrowsConstraintTests.cs deleted file mode 100644 index 472a908e1..000000000 --- a/test/NUnitLite/src/tests/Constraints/ThrowsConstraintTests.cs +++ /dev/null @@ -1,107 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class ThrowsConstraintTest_ExactType : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new ThrowsConstraint( - new ExactTypeConstraint(typeof(ArgumentException))); - expectedDescription = ""; - stringRepresentation = ">"; - } - - internal static object[] SuccessData = new object[] - { - new TestDelegate( TestDelegates.ThrowsArgumentException ) - }; - - internal static object[] FailureData = new object[] - { - new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), - new TestCaseData( new TestDelegate( TestDelegates.ThrowsSystemException ), "" ) - }; - } - - [TestFixture] - public class ThrowsConstraintTest_InstanceOfType : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new ThrowsConstraint( - new InstanceOfTypeConstraint(typeof(TestDelegates.CustomException))); - expectedDescription = "instance of "; - stringRepresentation = ">"; - } - - internal static object[] SuccessData = new object[] - { - new TestDelegate( TestDelegates.ThrowsCustomException ), - new TestDelegate( TestDelegates.ThrowsDerivedCustomException ) - }; - - internal static object[] FailureData = new object[] - { - new TestCaseData( new TestDelegate( TestDelegates.ThrowsArgumentException ), "" ), - new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), - new TestCaseData( new TestDelegate( TestDelegates.ThrowsSystemException ), "" ) - }; - } - -// TODO: Find a different example for use with NETCF - ArgumentException does not have a ParamName member -#if !NETCF && !SILVERLIGHT - public class ThrowsConstraintTest_WithConstraint : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new ThrowsConstraint( - new AndConstraint( - new ExactTypeConstraint(typeof(ArgumentException)), - new PropertyConstraint("ParamName", new EqualConstraint("myParam")))); - expectedDescription = @" and property ParamName equal to ""myParam"""; - stringRepresentation = @" >>>"; - } - - internal static object[] SuccessData = new object[] - { - new TestDelegate( TestDelegates.ThrowsArgumentException ) - }; - - internal static object[] FailureData = new object[] - { - new TestCaseData( new TestDelegate( TestDelegates.ThrowsCustomException ), "" ), - new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), - new TestCaseData( new TestDelegate( TestDelegates.ThrowsSystemException ), "" ) - }; - } -#endif -} diff --git a/test/NUnitLite/src/tests/Constraints/ToStringTests.cs b/test/NUnitLite/src/tests/Constraints/ToStringTests.cs deleted file mode 100644 index efdec05fe..000000000 --- a/test/NUnitLite/src/tests/Constraints/ToStringTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// **************************************************************** -// Copyright 2010, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** - -using System; - -namespace NUnit.Framework.Constraints -{ - public class ToStringTests - { - [Test] - public void CanDisplaySimpleConstraints_Unresolved() - { - Assert.That(Is.EqualTo(5).ToString(), Is.EqualTo("")); - Assert.That(Has.Property("X").ToString(), Is.EqualTo("")); - Assert.That(Has.Attribute(typeof(TestAttribute)).ToString(), - Is.EqualTo("")); - } - - [Test] - public void CanDisplaySimpleConstraints_Resolved() - { - IResolveConstraint constraint = Is.EqualTo(5); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo("")); - constraint = Has.Property("X"); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo("")); - constraint = Has.Attribute(typeof(TestAttribute)).With.Property("Description").EqualTo("smoke"); - Assert.That(constraint.Resolve().ToString(), - Is.EqualTo(">>")); - } - - [Test] - public void DisplayPrefixConstraints_Unresolved() - { - Assert.That(Is.Not.EqualTo(5).ToString(), Is.EqualTo(">")); - Assert.That(Is.Not.All.EqualTo(5).ToString(), Is.EqualTo(">")); - Assert.That(Has.Property("X").EqualTo(5).ToString(), Is.EqualTo(">")); - Assert.That(Has.Attribute(typeof(TestAttribute)).With.Property("Description").EqualTo("smoke").ToString(), - Is.EqualTo(">")); - } - - [Test] - public void CanDisplayPrefixConstraints_Resolved() - { - IResolveConstraint constraint = Is.Not.EqualTo(5); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo(">")); - constraint = Is.Not.All.EqualTo(5); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo(">>")); - constraint = Has.Property("X").EqualTo(5); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo(">")); - } - - [Test] - public void DisplayBinaryConstraints_Resolved() - { - IResolveConstraint constraint = Is.GreaterThan(0).And.LessThan(100); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo(" >")); - } - - [Test] - public void DisplayBinaryConstraints_UnResolved() - { - IResolveConstraint constraint = Is.GreaterThan(0).And.LessThan(100); - Assert.That(constraint.ToString(), Is.EqualTo(">")); - } - } -} diff --git a/test/NUnitLite/src/tests/Constraints/UniqueItemsConstraintTests.cs b/test/NUnitLite/src/tests/Constraints/UniqueItemsConstraintTests.cs deleted file mode 100644 index 41bcc8cd4..000000000 --- a/test/NUnitLite/src/tests/Constraints/UniqueItemsConstraintTests.cs +++ /dev/null @@ -1,42 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Internal; - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class UniqueItemsTests : ConstraintTestBase - { - [SetUp] - public void SetUp() - { - theConstraint = new UniqueItemsConstraint(); - stringRepresentation = ""; - expectedDescription = "all items unique"; - } - - internal object[] SuccessData = new object[] { new int[] { 1, 3, 17, -2, 34 }, new object[0] }; - internal object[] FailureData = new object[] { new object[] { new int[] { 1, 3, 17, 3, 34 }, "< 1, 3, 17, 3, 34 >" } }; - } -} diff --git a/test/NUnitLite/src/tests/Constraints/XmlSerializableTest.cs b/test/NUnitLite/src/tests/Constraints/XmlSerializableTest.cs deleted file mode 100644 index cfe4c14bf..000000000 --- a/test/NUnitLite/src/tests/Constraints/XmlSerializableTest.cs +++ /dev/null @@ -1,65 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if !SILVERLIGHT - -using System; -using System.Collections; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Constraints.Tests -{ - [TestFixture] - public class XmlSerializableTest : ConstraintTestBaseWithArgumentException - { - [SetUp] - public void SetUp() - { - theConstraint = new XmlSerializableConstraint(); - expectedDescription = "xml serializable"; - stringRepresentation = ""; - } - - internal object[] SuccessData = new object[] { 1, "a", new ArrayList() }; - - internal object[] FailureData = new object[] { -#if CLR_2_0 || CLR_4_0 - new TestCaseData( new Dictionary(), "" ), -#endif - new TestCaseData( new InternalClass(), "" ), - new TestCaseData( new InternalWithSerializableAttributeClass(), "" ) - }; - - internal object[] InvalidData = new object[] { null }; - } - - internal class InternalClass - { } - - [Serializable] - internal class InternalWithSerializableAttributeClass - { } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Framework/StackFilterTest.cs b/test/NUnitLite/src/tests/Framework/StackFilterTest.cs deleted file mode 100644 index 1fc6381a9..000000000 --- a/test/NUnitLite/src/tests/Framework/StackFilterTest.cs +++ /dev/null @@ -1,80 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Internal; - -namespace NUnitLite.Tests -{ - [TestFixture] - class StackFilterTest - { - private static readonly string NL = NUnit.Env.NewLine; - - private static readonly string rawTrace1 = - @" at NUnit.Framework.Assert.Fail(String message) in D:\Dev\NUnitLite\NUnitLite\Framework\Assert.cs:line 56" + NL + - @" at NUnit.Framework.Assert.That(String label, Object actual, Matcher expectation, String message) in D:\Dev\NUnitLite\NUnitLite\Framework\Assert.cs:line 50" + NL + - @" at NUnit.Framework.Assert.That(Object actual, Matcher expectation) in D:\Dev\NUnitLite\NUnitLite\Framework\Assert.cs:line 19" + NL + - @" at NUnit.Tests.GreaterThanMatcherTest.MatchesGoodValue() in D:\Dev\NUnitLite\NUnitLiteTests\GreaterThanMatcherTest.cs:line 12" + NL; - - private static readonly string filteredTrace1 = - @" at NUnit.Tests.GreaterThanMatcherTest.MatchesGoodValue() in D:\Dev\NUnitLite\NUnitLiteTests\GreaterThanMatcherTest.cs:line 12" + NL; - - private static readonly string rawTrace2 = - @" at NUnit.Framework.Assert.Fail(String message, Object[] args)" + NL + - @" at MyNamespace.MyAppsTests.AssertFailTest()" + NL + - @" at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)" + NL + - @" at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean verifyAccess, StackCrawlMark& stackMark)" + NL + - @" at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)" + NL + - @" at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)" + NL + - @" at NUnitLite.ProxyTestCase.InvokeMethod(MethodInfo method, Object[] args)" + NL + - @" at NUnit.Framework.TestCase.RunTest()" + NL + - @" at NUnit.Framework.TestCase.RunBare()" + NL + - @" at NUnit.Framework.TestCase.Run(TestResult result, TestListener listener)" + NL + - @" at NUnit.Framework.TestCase.Run(TestListener listener)" + NL + - @" at NUnit.Framework.TestSuite.Run(TestListener listener)" + NL + - @" at NUnit.Framework.TestSuite.Run(TestListener listener)" + NL + - @" at NUnitLite.Runner.TestRunner.Run(ITest test)" + NL + - @" at NUnitLite.Runner.ConsoleUI.Run(ITest test)" + NL + - @" at NUnitLite.Runner.TestRunner.Run(Assembly assembly)" + NL + - @" at NUnitLite.Runner.ConsoleUI.Run()" + NL + - @" at NUnitLite.Runner.ConsoleUI.Main(String[] args)" + NL + - @" at OpenNETCF.Linq.Demo.Program.Main(String[] args)" + NL; - - private static readonly string filteredTrace2 = - @" at MyNamespace.MyAppsTests.AssertFailTest()" + NL + - @" at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)" + NL + - @" at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean verifyAccess, StackCrawlMark& stackMark)" + NL + - @" at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)" + NL + - @" at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)" + NL + - @" at NUnitLite.ProxyTestCase.InvokeMethod(MethodInfo method, Object[] args)" + NL + - @" at NUnit.Framework.TestCase.RunTest()" + NL + - @" at NUnit.Framework.TestCase.RunBare()" + NL + - @" at NUnit.Framework.TestCase.Run(TestResult result, TestListener listener)" + NL + - @" at NUnit.Framework.TestCase.Run(TestListener listener)" + NL + - @" at NUnit.Framework.TestSuite.Run(TestListener listener)" + NL + - @" at NUnit.Framework.TestSuite.Run(TestListener listener)" + NL + - @" at NUnitLite.Runner.TestRunner.Run(ITest test)" + NL + - @" at NUnitLite.Runner.ConsoleUI.Run(ITest test)" + NL + - @" at NUnitLite.Runner.TestRunner.Run(Assembly assembly)" + NL + - @" at NUnitLite.Runner.ConsoleUI.Run()" + NL + - @" at NUnitLite.Runner.ConsoleUI.Main(String[] args)" + NL + - @" at OpenNETCF.Linq.Demo.Program.Main(String[] args)" + NL; - - [Test] - public void FilterFailureTrace1() - { - Assert.That(StackFilter.Filter(rawTrace1), Is.EqualTo(filteredTrace1)); - } - - [Test] - public void FilterFailureTrace2() - { - Assert.That(StackFilter.Filter(rawTrace2), Is.EqualTo(filteredTrace2)); - } - } -} diff --git a/test/NUnitLite/src/tests/Framework/SyntaxTests.cs b/test/NUnitLite/src/tests/Framework/SyntaxTests.cs deleted file mode 100644 index 9d845c4cb..000000000 --- a/test/NUnitLite/src/tests/Framework/SyntaxTests.cs +++ /dev/null @@ -1,196 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Constraints; - -namespace NUnitLite.Tests -{ - [TestFixture] - public class SyntaxTests - { - [Test] - public void NullTests() - { - object myObject = null; - Assert.That(myObject, Is.Null); - Assert.Null(null); - } - - [Test] - public void NotNullTests() - { - Assert.That(42, Is.Not.Null); - Assert.NotNull(42); - } - - [Test] - public void TrueTests() - { - Assert.That(true, Is.True); - Assert.True(true); - } - - [Test] - public void FalseTests() - { - Assert.That(false, Is.False); - Assert.False(false); - } - - [Test] - public void NaNTests() - { - Assert.That(double.NaN, Is.NaN); - Assert.That(float.NaN, Is.NaN); - } - - [Test] - public void EmptyTests() - { - Assert.That("", Is.Empty); - Assert.That(new bool[0], Is.Empty); - Assert.That(new int[] { 1, 2, 3 }, Is.Not.Empty); - } - - [Test] - public void TypeTests() - { - Assert.That("Hello", Is.TypeOf(typeof(string))); - Assert.That("Hello", Is.InstanceOf(typeof(string))); - Assert.That("Hello".GetType(), Is.EqualTo(typeof(string))); - Assert.That("Hello".GetType().FullName, Is.EqualTo("System.String")); - } - - [Test] - public void StringTests() - { - string phrase = "Hello World!"; - Assert.That(phrase, Is.Not.Empty); - Assert.That(phrase, Is.StringContaining("World")); - Assert.That(phrase, Is.StringStarting("Hello")); - Assert.That(phrase, Is.StringEnding("!")); - Assert.That(phrase, Is.EqualTo("hello world!").IgnoreCase); - Assert.That(new string[] { "Hello", "World" }, Is.EqualTo( new object[] { "HELLO", "WORLD" } ).IgnoreCase); - Assert.That("", Is.Empty); - } - - [Test] - public void EqualToTests() - { - Assert.That(2 + 2, Is.EqualTo(4)); - Assert.That(2 + 2 == 4); - Assert.That(new int[] { 1, 2, 3 }, Is.EqualTo(new double[] { 1.0, 2.0, 3.0 })); - } - - [Test] - public void ComparisonTests() - { - Assert.That(7, Is.GreaterThan(3)); - Assert.That(7, Is.GreaterThanOrEqualTo(3)); - Assert.That(7, Is.AtLeast(3)); - Assert.That(7, Is.GreaterThanOrEqualTo(7)); - Assert.That(7, Is.AtLeast(7)); - - Assert.That(3, Is.LessThan(7)); - Assert.That(3, Is.LessThanOrEqualTo(7)); - Assert.That(3, Is.AtMost(7)); - Assert.That(3, Is.LessThanOrEqualTo(3)); - Assert.That(3, Is.AtMost(3)); - } - - [Test] - public void AllItemsTests() - { - object[] c = new object[] { 1, 2, 3, 4 }; - Assert.That(c, Is.All.Not.Null); - Assert.That(c, Is.All.InstanceOf(typeof(int))); - } - - [Test] - public void CollectionContainsTests() - { - Assert.That(new int[] { 1, 2, 3 }, Contains.Item(3)); - Assert.That(new string[] { "a", "b", "c" }, Contains.Item("b")); - } - - [Test] - public void CollectionEquivalenceTests() - { - int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; - Assert.That(new int[] { 2, 1, 4, 3, 5 }, Is.EquivalentTo(ints1to5)); - Assert.That(new int[] { 2, 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); - Assert.That(new int[] { 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); - Assert.That(new int[] { 2, 2, 1, 1, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); - Assert.That(new int[] { 1, 2, 2, 2, 5 }, Is.Not.EquivalentTo(ints1to5)); - } - - [Test] - public void SubsetTests() - { - int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; - Assert.That(new int[] { 1, 3, 5 }, Is.SubsetOf(ints1to5)); - Assert.That(new int[] { 1, 2, 3, 4, 5 }, Is.SubsetOf(ints1to5)); - Assert.That(new int[] { 2, 4, 6 }, Is.Not.SubsetOf(ints1to5)); - } - - [Test] - public void NotTests() - { - Assert.That(42, Is.Not.Null); - Assert.That(42, Is.Not.True); - Assert.That(42, Is.Not.False); - Assert.That(42, !Is.Null); - Assert.That(2.5, Is.Not.NaN); - Assert.That(2 + 2, Is.Not.EqualTo(3)); - Assert.That(2 + 2, Is.Not.Not.EqualTo(4)); - Assert.That(2 + 2, Is.Not.Not.Not.EqualTo(5)); - } - - [Test] - public void AndTests() - { - Assert.That(7, Is.GreaterThan(5) & Is.LessThan(10)); - } - - [Test] - public void OrTests() - { - Assert.That(3, Is.LessThan(5) | Is.GreaterThan(10)); - } - - [Test] - public void ComplexTests() - { - Assert.That(7, Is.Not.Null & Is.Not.LessThan(5) & Is.Not.GreaterThan(10)); - Assert.That(7, !Is.Null & !Is.LessThan(5) & !Is.GreaterThan(10)); -// TODO: Remove #if when mono compiler can handle null -#if MONO - Constraint x = null; - Assert.That(7, !x & !Is.LessThan(5) & !Is.GreaterThan(10)); -#else - Assert.That(7, !(Constraint)null & !Is.LessThan(5) & !Is.GreaterThan(10)); -#endif - } - - // This method contains assertions that should not compile - // You can check by uncommenting it. - //public void WillNotCompile() - //{ - // Assert.That(42, Is.Not); - // Assert.That(42, Is.All); - // Assert.That(42, Is.Null.Not); - // Assert.That(42, Is.Not.Null.GreaterThan(10)); - // Assert.That(42, Is.GreaterThan(10).LessThan(99)); - - // object[] c = new object[0]; - // Assert.That(c, Is.Null.All); - // Assert.That(c, Is.Not.All); - // Assert.That(c, Is.All.Not); - //} - } -} diff --git a/test/NUnitLite/src/tests/Framework/TestContextTests.cs b/test/NUnitLite/src/tests/Framework/TestContextTests.cs deleted file mode 100644 index 64a8d8c24..000000000 --- a/test/NUnitLite/src/tests/Framework/TestContextTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -// **************************************************************** -// Copyright 2012, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** - -using System; -using System.IO; -using NUnit.Framework; -using NUnit.TestData.TestContextData; -using NUnit.TestUtilities; -using System.Reflection; - -namespace NUnit.Framework.Tests -{ - [TestFixture] - public class TestContextTests - { - [Test] - public void TestCanAccessItsOwnName() - { - Assert.That(TestContext.CurrentContext.Test.Name, Is.EqualTo("TestCanAccessItsOwnName")); - } - - [Test] - public void TestCanAccessItsOwnFullName() - { - Assert.That(TestContext.CurrentContext.Test.FullName, - Is.EqualTo("NUnit.Framework.Tests.TestContextTests.TestCanAccessItsOwnFullName")); - } - - [Test] - [Property("Answer", 42)] - public void TestCanAccessItsOwnProperties() - { - Assert.That(TestContext.CurrentContext.Test.Properties.Get("Answer"), Is.EqualTo(42)); - } - -#if !NETCF - [Test] - public void TestCanAccessTestDirectory() - { - string testDirectory = TestContext.CurrentContext.TestDirectory; - Assert.NotNull(testDirectory); - Assert.That(Directory.Exists(testDirectory), "Directory not found: {0}", testDirectory); - Assert.That(File.Exists(Path.Combine(testDirectory, "nunitlite.tests.exe"))); - } -#endif - - [Test] - public void TestCanAccessWorkDirectory() - { - string workDirectory = TestContext.CurrentContext.WorkDirectory; - Assert.NotNull(workDirectory); - Assert.That(Directory.Exists(workDirectory), string.Format("Directory {0} does not exist", workDirectory)); - } - - [Test] - public void TestCanAccessTestState_PassingTest() - { - TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>Inconclusive=>Passed")); - //Assert.That(fixture.statusList, Is.EqualTo("Inconclusive=>Inconclusive=>Passed")); - } - - [Test] - public void TestCanAccessTestState_FailureInSetUp() - { - TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - fixture.setUpFailure = true; - TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>=>Failed")); - //Assert.That(fixture.statusList, Is.EqualTo("Inconclusive=>=>Failed")); - } - - [Test] - public void TestCanAccessTestState_FailingTest() - { - TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - fixture.testFailure = true; - TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>Inconclusive=>Failed")); - //Assert.That(fixture.statusList, Is.EqualTo("Inconclusive=>Inconclusive=>Failed")); - } - - [Test] - public void TestCanAccessTestState_IgnoredInSetUp() - { - TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - fixture.setUpIgnore = true; - TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>=>Skipped:Ignored")); - //Assert.That(fixture.statusList, Is.EqualTo("Inconclusive=>=>Skipped")); - } - - //[Test, RequiresThread] - //public void CanAccessTestContextOnSeparateThread() - //{ - // Assert.That(TestContext.CurrentContext.Test.Name, Is.EqualTo("CanAccessTestContextOnSeparateThread")); - //} - } -} diff --git a/test/NUnitLite/src/tests/Framework/TestResultTests.cs b/test/NUnitLite/src/tests/Framework/TestResultTests.cs deleted file mode 100644 index 8de008929..000000000 --- a/test/NUnitLite/src/tests/Framework/TestResultTests.cs +++ /dev/null @@ -1,83 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnitLite.Tests -{ - [TestFixture] - public class TestResultTests - { - private static readonly string MESSAGE = "my message"; - private static readonly string STACKTRACE = "stack trace"; - - private TestResult result; - - [SetUp] - public void SetUp() - { - result = new TestCaseResult(null); - } - - void VerifyResultState(ResultState expectedState, string message ) - { - Assert.That( result.ResultState , Is.EqualTo( expectedState ) ); - //if ( expectedState == ResultState.Error ) - // Assert.That(result.Message, Is.EqualTo("System.Exception : " + message)); - //else - Assert.That(result.Message, Is.EqualTo(message)); - } - - [Test] - public void DefaultStateIsInconclusive() - { - VerifyResultState(ResultState.Inconclusive, null); - } - - [Test] - public void CanMarkAsSuccess() - { - result.SetResult(ResultState.Success); - VerifyResultState(ResultState.Success, null); - } - - [Test] - public void CanMarkAsFailure() - { - result.SetResult(ResultState.Failure, MESSAGE, STACKTRACE); - VerifyResultState(ResultState.Failure, MESSAGE); - Assert.That( result.StackTrace, Is.EqualTo( STACKTRACE ) ); - } - - [Test] - public void CanMarkAsError() - { - Exception caught; - try - { - throw new Exception(MESSAGE); - } - catch(Exception ex) - { - caught = ex; - } - - result.SetResult(ResultState.Error, caught.Message, caught.StackTrace); - VerifyResultState(ResultState.Error, MESSAGE); - Assert.That( result.StackTrace, Is.EqualTo( caught.StackTrace ) ); - } - - [Test] - public void CanMarkAsIgnored() - { - result.SetResult(ResultState.Ignored, MESSAGE); - VerifyResultState(ResultState.Ignored, MESSAGE); - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/AssemblyHelperTests.cs b/test/NUnitLite/src/tests/Internal/AssemblyHelperTests.cs deleted file mode 100644 index 01803fb2d..000000000 --- a/test/NUnitLite/src/tests/Internal/AssemblyHelperTests.cs +++ /dev/null @@ -1,84 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2012 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if !NETCF -using System; -using System.IO; -using System.Reflection; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class AssemblyHelperTests - { - [Test] - public void GetPathForAssembly() - { - string path = AssemblyHelper.GetAssemblyPath(this.GetType().Assembly); - Assert.That(Path.GetFileName(path), Is.EqualTo("nunitlite.tests.exe").IgnoreCase); - Assert.That(File.Exists(path)); - } - - //[Test] - //public void GetPathForType() - //{ - // string path = AssemblyHelper.GetAssemblyPath(this.GetType()); - // Assert.That(Path.GetFileName(path), Is.EqualTo("nunitlite.tests.exe").IgnoreCase); - // Assert.That(File.Exists(path)); - //} - - // The following tests are only useful to the extent that the test cases - // match what will actually be provided to the method in production. - // As currently used, NUnit's codebase can only use the file: schema, - // since we don't load assemblies from anything but files. The uri's - // provided can be absolute file paths or UNC paths. - - // Local paths - Windows Drive - [TestCase(@"file:///C:/path/to/assembly.dll", @"C:\path\to\assembly.dll")] - [TestCase(@"file:///C:/my path/to my/assembly.dll", @"C:/my path/to my/assembly.dll")] - [TestCase(@"file:///C:/dev/C#/assembly.dll", @"C:\dev\C#\assembly.dll")] - [TestCase(@"file:///C:/dev/funnychars?:=/assembly.dll", @"C:\dev\funnychars?:=\assembly.dll")] - // Local paths - Linux or Windows absolute without a drive - [TestCase(@"file:///path/to/assembly.dll", @"/path/to/assembly.dll")] - [TestCase(@"file:///my path/to my/assembly.dll", @"/my path/to my/assembly.dll")] - [TestCase(@"file:///dev/C#/assembly.dll", @"/dev/C#/assembly.dll")] - [TestCase(@"file:///dev/funnychars?:=/assembly.dll", @"/dev/funnychars?:=/assembly.dll")] - // Windows drive specified as if it were a server - odd case, sometimes seen - [TestCase(@"file://C:/path/to/assembly.dll", @"C:\path\to\assembly.dll")] - [TestCase(@"file://C:/my path/to my/assembly.dll", @"C:\my path\to my\assembly.dll")] - [TestCase(@"file://C:/dev/C#/assembly.dll", @"C:\dev\C#\assembly.dll")] - [TestCase(@"file://C:/dev/funnychars?:=/assembly.dll", @"C:\dev\funnychars?:=\assembly.dll")] - // UNC format with server and path - [TestCase(@"file://server/path/to/assembly.dll", @"//server/path/to/assembly.dll")] - [TestCase(@"file://server/my path/to my/assembly.dll", @"//server/my path/to my/assembly.dll")] - [TestCase(@"file://server/dev/C#/assembly.dll", @"//server/dev/C#/assembly.dll")] - [TestCase(@"file://server/dev/funnychars?:=/assembly.dll", @"//server/dev/funnychars?:=/assembly.dll")] - //[TestCase(@"http://server/path/to/assembly.dll", "//server/path/to/assembly.dll")] - public void GetAssemblyPathFromCodeBase(string uri, string expectedPath) - { - string localPath = AssemblyHelper.GetAssemblyPathFromCodeBase(uri); - Assert.That(localPath, Is.SamePath(expectedPath)); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Internal/AsyncTestMethodTests.cs b/test/NUnitLite/src/tests/Internal/AsyncTestMethodTests.cs deleted file mode 100644 index 08491de11..000000000 --- a/test/NUnitLite/src/tests/Internal/AsyncTestMethodTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -#if NET_4_5 -using System.Collections; -using System.Reflection; -using System.Threading; -using NUnit.Framework.Api; -using NUnit.Framework.Builders; -using NUnit.TestData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class NUnitAsyncTestMethodTests - { - private NUnitTestCaseBuilder _builder; - private object _testObject; - - [SetUp] - public void Setup() - { - _builder = new NUnitTestCaseBuilder(); - _testObject = new AsyncRealFixture(); - } - - public IEnumerable TestCases - { - get - { - yield return new object[] { Method("AsyncVoidSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncVoidFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("AsyncVoidError"), ResultState.Error, 0 }; - - yield return new object[] { Method("AsyncTaskSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncTaskFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("AsyncTaskError"), ResultState.Error, 0 }; - - yield return new object[] { Method("AsyncTaskResultSuccess"), ResultState.NotRunnable, 0 }; - yield return new object[] { Method("AsyncTaskResultFailure"), ResultState.NotRunnable, 0 }; - yield return new object[] { Method("AsyncTaskResultError"), ResultState.NotRunnable, 0 }; - - yield return new object[] { Method("AsyncTaskResultCheckSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncVoidTestCaseWithParametersSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncTaskResultCheckSuccessReturningNull"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncTaskResultCheckFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("AsyncTaskResultCheckError"), ResultState.Failure, 0 }; - - yield return new object[] { Method("AsyncVoidExpectedException"), ResultState.Success, 0 }; - yield return new object[] { Method("AsyncTaskExpectedException"), ResultState.Success, 0 }; - yield return new object[] { Method("AsyncTaskResultExpectedException"), ResultState.NotRunnable, 0 }; - - yield return new object[] { Method("NestedAsyncVoidSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("NestedAsyncVoidFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("NestedAsyncVoidError"), ResultState.Error, 0 }; - - yield return new object[] { Method("NestedAsyncTaskSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("NestedAsyncTaskFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("NestedAsyncTaskError"), ResultState.Error, 0 }; - - yield return new object[] { Method("AsyncVoidMultipleSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncVoidMultipleFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("AsyncVoidMultipleError"), ResultState.Error, 0 }; - - yield return new object[] { Method("AsyncTaskMultipleSuccess"), ResultState.Success, 1 }; - yield return new object[] { Method("AsyncTaskMultipleFailure"), ResultState.Failure, 1 }; - yield return new object[] { Method("AsyncTaskMultipleError"), ResultState.Error, 0 }; - - yield return new object[] { Method("VoidCheckTestContextAcrossTasks"), ResultState.Success, 2 }; - yield return new object[] { Method("VoidCheckTestContextWithinTestBody"), ResultState.Success, 2 }; - yield return new object[] { Method("TaskCheckTestContextAcrossTasks"), ResultState.Success, 2 }; - yield return new object[] { Method("TaskCheckTestContextWithinTestBody"), ResultState.Success, 2 }; - - yield return new object[] { Method("VoidAsyncVoidChildCompletingEarlierThanTest"), ResultState.Success, 0 }; - yield return new object[] { Method("VoidAsyncVoidChildThrowingImmediately"), ResultState.Success, 0 }; - } - } - - [Test] - [TestCaseSource("TestCases")] - public void RunTests(MethodInfo method, ResultState resultState, int assertionCount) - { - var test = _builder.BuildFrom(method); - var result = TestBuilder.RunTest(test, _testObject); - - Assert.That(result.ResultState, Is.EqualTo(resultState), "Wrong result state"); - Assert.That(result.AssertCount, Is.EqualTo(assertionCount), "Wrong assertion count"); - } - - [Test] - public void SynchronizationContextSwitching() - { - var context = new CustomSynchronizationContext(); - - SynchronizationContext.SetSynchronizationContext(context); - - var test = _builder.BuildFrom(Method("AsyncVoidAssertSynchronizationContext")); - var result = TestBuilder.RunTest(test, _testObject); - - Assert.AreSame(context, SynchronizationContext.Current); - Assert.That(result.ResultState, Is.EqualTo(ResultState.Success), "Wrong result state"); - Assert.That(result.AssertCount, Is.EqualTo(0), "Wrong assertion count"); - } - - private static MethodInfo Method(string name) - { - return typeof (AsyncRealFixture).GetMethod(name); - } - - public class CustomSynchronizationContext : SynchronizationContext - { - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Internal/CultureSettingAndDetectionTests.cs b/test/NUnitLite/src/tests/Internal/CultureSettingAndDetectionTests.cs deleted file mode 100644 index 7b507293a..000000000 --- a/test/NUnitLite/src/tests/Internal/CultureSettingAndDetectionTests.cs +++ /dev/null @@ -1,181 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Threading; -using System.Globalization; -using NUnit.Framework.Api; -using NUnit.TestData.CultureAttributeData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Internal -{ - /// - /// Summary description for CultureDetectionTests. - /// - [TestFixture] - public class CultureSettingAndDetectionTests - { - private NUnit.Framework.Internal.CultureDetector detector = new NUnit.Framework.Internal.CultureDetector("fr-FR"); - - private void ExpectMatch( string culture ) - { - if ( !detector.IsCultureSupported( culture ) ) - Assert.Fail( string.Format( "Failed to match \"{0}\"" , culture ) ); - } - - private void ExpectMatch( CultureAttribute attr ) - { - if ( !detector.IsCultureSupported( attr ) ) - Assert.Fail( string.Format( "Failed to match attribute with Include=\"{0}\",Exclude=\"{1}\"", attr.Include, attr.Exclude ) ); - } - - private void ExpectFailure( string culture ) - { - if ( detector.IsCultureSupported( culture ) ) - Assert.Fail( string.Format( "Should not match \"{0}\"" , culture ) ); - Assert.AreEqual( "Only supported under culture " + culture, detector.Reason ); - } - - private void ExpectFailure( CultureAttribute attr, string msg ) - { - if ( detector.IsCultureSupported( attr ) ) - Assert.Fail( string.Format( "Should not match attribute with Include=\"{0}\",Exclude=\"{1}\"", - attr.Include, attr.Exclude ) ); - Assert.AreEqual( msg, detector.Reason ); - } - - [Test] - public void CanMatchStrings() - { - ExpectMatch( "fr-FR" ); - ExpectMatch( "fr" ); - ExpectMatch( "fr-FR,fr-BE,fr-CA" ); - ExpectMatch( "en,de,fr,it" ); - ExpectFailure( "en-GB" ); - ExpectFailure( "en" ); - ExpectFailure( "fr-CA" ); - ExpectFailure( "fr-BE,fr-CA" ); - ExpectFailure( "en,de,it" ); - } - - [Test] - public void CanMatchAttributeWithInclude() - { - ExpectMatch( new CultureAttribute( "fr-FR" ) ); - ExpectMatch( new CultureAttribute( "fr-FR,fr-BE,fr-CA" ) ); - ExpectFailure( new CultureAttribute( "en" ), "Only supported under culture en" ); - ExpectFailure( new CultureAttribute( "en,de,it" ), "Only supported under culture en,de,it" ); - } - - [Test] - public void CanMatchAttributeWithExclude() - { - CultureAttribute attr = new CultureAttribute(); - attr.Exclude = "en"; - ExpectMatch( attr ); - attr.Exclude = "en,de,it"; - ExpectMatch( attr ); - attr.Exclude = "fr"; - ExpectFailure( attr, "Not supported under culture fr"); - attr.Exclude = "fr-FR,fr-BE,fr-CA"; - ExpectFailure( attr, "Not supported under culture fr-FR,fr-BE,fr-CA" ); - } - - [Test] - public void CanMatchAttributeWithIncludeAndExclude() - { - CultureAttribute attr = new CultureAttribute( "en,fr,de,it" ); - attr.Exclude="fr-CA,fr-BE"; - ExpectMatch( attr ); - attr.Exclude = "fr-FR"; - ExpectFailure( attr, "Not supported under culture fr-FR" ); - } - -#if !NETCF - [Test,SetCulture("fr-FR")] - public void LoadWithFrenchCulture() - { - Assert.AreEqual( "fr-FR", CultureInfo.CurrentCulture.Name, "Culture not set correctly" ); - TestSuite fixture = TestBuilder.MakeFixture( typeof( FixtureWithCultureAttribute ) ); - Assert.AreEqual( RunState.Runnable, fixture.RunState, "Fixture" ); - foreach( Test test in fixture.Tests ) - { - RunState expected = test.Name == "FrenchTest" ? RunState.Runnable : RunState.Skipped; - Assert.AreEqual( expected, test.RunState, test.Name ); - } - } - - [Test,SetCulture("fr-CA")] - public void LoadWithFrenchCanadianCulture() - { - Assert.AreEqual( "fr-CA", CultureInfo.CurrentCulture.Name, "Culture not set correctly" ); - TestSuite fixture = TestBuilder.MakeFixture( typeof( FixtureWithCultureAttribute ) ); - Assert.AreEqual( RunState.Runnable, fixture.RunState, "Fixture" ); - foreach( Test test in fixture.Tests ) - { - RunState expected = test.Name.StartsWith( "French" ) ? RunState.Runnable : RunState.Skipped; - Assert.AreEqual( expected, test.RunState, test.Name ); - } - } - - [Test,SetCulture("ru-RU")] - public void LoadWithRussianCulture() - { - Assert.AreEqual( "ru-RU", CultureInfo.CurrentCulture.Name, "Culture not set correctly" ); - TestSuite fixture = TestBuilder.MakeFixture( typeof( FixtureWithCultureAttribute ) ); - Assert.AreEqual( RunState.Skipped, fixture.RunState, "Fixture" ); - foreach( Test test in fixture.Tests ) - Assert.AreEqual( RunState.Skipped, test.RunState, test.Name ); - } - - [Test] - public void SettingInvalidCultureOnFixtureGivesError() - { - ITestResult result = TestBuilder.RunTestFixture(typeof(FixtureWithInvalidSetCultureAttribute)); - Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.That(result.Message, Is.StringStarting("System.ArgumentException").Or.StringStarting("System.Globalization.CultureNotFoundException")); - Assert.That(result.Message, Is.StringContaining("xx-XX").IgnoreCase); - } - - [Test] - public void SettingInvalidCultureOnTestGivesError() - { - ITestResult result = TestBuilder.RunTestCase(typeof(FixtureWithInvalidSetCultureAttributeOnTest), "InvalidCultureSet"); - Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.That(result.Message, Is.StringStarting("System.ArgumentException").Or.StringStarting("System.Globalization.CultureNotFoundException")); - Assert.That(result.Message, Is.StringContaining("xx-XX").IgnoreCase); - } - - [TestFixture, SetCulture("en-GB")] - public class NestedFixture - { - [Test] - public void CanSetCultureOnFixture() - { - Assert.AreEqual( "en-GB", CultureInfo.CurrentCulture.Name ); - } - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Internal/DeduceTypeArgsFromArgs.cs b/test/NUnitLite/src/tests/Internal/DeduceTypeArgsFromArgs.cs deleted file mode 100644 index a495f8320..000000000 --- a/test/NUnitLite/src/tests/Internal/DeduceTypeArgsFromArgs.cs +++ /dev/null @@ -1,51 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if (CLR_2_0 || CLR_4_0) && !NETCF -using System; - -namespace NUnit.Framework.Internal -{ - [Category("Generics")] - [TestFixture(100.0, 42)] - [TestFixture(42, 100.0)] - public class DeduceTypeArgsFromArgs - { - T1 t1; - T2 t2; - - public DeduceTypeArgsFromArgs(T1 t1, T2 t2) - { - this.t1 = t1; - this.t2 = t2; - } - - [TestCase(5, 7)] - public void TestMyArgTypes(T1 t1, T2 t2) - { - Assert.That(t1, Is.TypeOf()); - Assert.That(t2, Is.TypeOf()); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Internal/GenericTestFixtureTests.cs b/test/NUnitLite/src/tests/Internal/GenericTestFixtureTests.cs deleted file mode 100644 index ddce40d78..000000000 --- a/test/NUnitLite/src/tests/Internal/GenericTestFixtureTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if CLR_2_0 || CLR_4_0 -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Internal -{ - [TestFixture(typeof(List))] - [TestFixture(TypeArgs = new Type[] { typeof(List) })] -#if !SILVERLIGHT - [TestFixture(typeof(ArrayList))] -#endif - // TODO: Why doesn't this work? - //[TestFixture(TypeArgs = new Type[] { typeof(SimpleObjectList) })] - public class GenericTestFixture_IList where T : IList, new() - { - [Test] - public void TestCollectionCount() - { - IList list = new T(); - list.Add(1); - list.Add(2); - list.Add(3); - Assert.AreEqual(3, list.Count); - } - } - - [TestFixture(typeof(double))] - public class GenericTestFixture_Numeric - { - [TestCase(5)] - [TestCase(1.23)] - public void TestMyArgType(T x) - { - Assert.That(x, Is.TypeOf(typeof(T))); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Internal/GenericTestMethodTests.cs b/test/NUnitLite/src/tests/Internal/GenericTestMethodTests.cs deleted file mode 100644 index 70d8097ec..000000000 --- a/test/NUnitLite/src/tests/Internal/GenericTestMethodTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if (CLR_2_0 || CLR_4_0) && !NETCF -using System; -using System.Collections.Generic; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - class GenericTestMethodTests - { - [TestCase(5, 2, "ABC")] - [TestCase(5.0, 2.0, "ABC")] - [TestCase(5, 2.0, "ABC")] - [TestCase(5.0, 2L, "ABC")] - public void GenericTestMethodWithOneTypeParameter(T x, T y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - - [TestCase(5, 2, "ABC")] - [TestCase(5.0, 2.0, "ABC")] - [TestCase(5, 2.0, "ABC")] - [TestCase(5.0, 2L, "ABC")] - public void GenericTestMethodWithTwoTypeParameters(T1 x, T2 y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - - [TestCase(5, 2, "ABC")] - [TestCase(5.0, 2.0, "ABC")] - [TestCase(5, 2.0, "ABC")] - [TestCase(5.0, 2L, "ABC")] - public void GenericTestMethodWithTwoTypeParameters_Reversed(T2 x, T1 y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Internal/NUnitTestCaseBuilderTests.cs b/test/NUnitLite/src/tests/Internal/NUnitTestCaseBuilderTests.cs deleted file mode 100644 index 01ed8f0b1..000000000 --- a/test/NUnitLite/src/tests/Internal/NUnitTestCaseBuilderTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -#if NET_4_5 -using System.Reflection; -using NUnit.Framework.Api; -using NUnit.Framework.Builders; -using NUnit.TestData; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class NUnitTestCaseBuilderTests - { - private static readonly System.Type fixtureType = typeof(AsyncDummyFixture); - - [TestCase("AsyncVoid", RunState.Runnable)] - [TestCase("AsyncTask", RunState.Runnable)] - [TestCase("AsyncGenericTask", RunState.NotRunnable)] - [TestCase("NonAsyncTask", RunState.NotRunnable)] - [TestCase("NonAsyncGenericTask", RunState.NotRunnable)] - public void AsyncTests(string methodName, RunState expectedState) - { - var test = TestBuilder.MakeTestCase(fixtureType, methodName); - Assert.That(test.RunState, Is.EqualTo(expectedState)); - } - - [TestCase("AsyncVoidTestCase", RunState.Runnable)] - [TestCase("AsyncVoidTestCaseWithExpectedResult", RunState.NotRunnable)] - [TestCase("AsyncTaskTestCase", RunState.Runnable)] - [TestCase("AsyncTaskTestCaseWithExpectedResult", RunState.NotRunnable)] - [TestCase("AsyncGenericTaskTestCase", RunState.NotRunnable)] - [TestCase("AsyncGenericTaskTestCaseWithExpectedResult", RunState.Runnable)] - [TestCase("AsyncGenericTaskTestCaseWithExpectedException", RunState.Runnable)] - public void AsyncTestCases(string methodName, RunState expectedState) - { - var suite = TestBuilder.MakeTestCase(fixtureType, methodName); - var testCase = (Test)suite.Tests[0]; - Assert.That(testCase.RunState, Is.EqualTo(expectedState)); - } - } -} -#endif \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Internal/PlatformDetectionTests.cs b/test/NUnitLite/src/tests/Internal/PlatformDetectionTests.cs deleted file mode 100644 index 0d0668a48..000000000 --- a/test/NUnitLite/src/tests/Internal/PlatformDetectionTests.cs +++ /dev/null @@ -1,443 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Internal -{ - /// - /// Summary description for PlatformHelperTests. - /// - [TestFixture] - public class PlatformDetectionTests - { - private static readonly PlatformHelper win95Helper = new PlatformHelper( - new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ), - new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) ); - - private static readonly PlatformHelper winXPHelper = new PlatformHelper( - new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ), - new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) ); - - private void CheckOSPlatforms( OSPlatform os, - string expectedPlatforms ) - { - CheckPlatforms( - new PlatformHelper( os, RuntimeFramework.CurrentFramework ), - expectedPlatforms, - PlatformHelper.OSPlatforms ); - } - - private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework, - string expectedPlatforms ) - { - CheckPlatforms( - new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ), - expectedPlatforms, - PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH,SL-3.0,SL-4.0,SL-5.0" ); - } - - private void CheckPlatforms( PlatformHelper helper, - string expectedPlatforms, string checkPlatforms ) - { - string[] expected = expectedPlatforms.Split( new char[] { ',' } ); - string[] check = checkPlatforms.Split( new char[] { ',' } ); - - //foreach (string platform in expected) - //{ - // bool isValid = false; - - // foreach (string testPlatform in check) - // if (isValid = platform.ToLower() == testPlatform.ToLower()) - // break; - - // if (!isValid) - // Assert.Fail("Invalid platform: {0}", platform); - //} - - foreach( string testPlatform in check ) - { - bool shouldPass = false; - - foreach( string platform in expected ) - if ( shouldPass = platform.ToLower() == testPlatform.ToLower() ) - break; - - bool didPass = helper.IsPlatformSupported( testPlatform ); - - if ( shouldPass && !didPass ) - Assert.Fail( "Failed to detect {0}", testPlatform ); - else if ( didPass && !shouldPass ) - Assert.Fail( "False positive on {0}", testPlatform ); - else if ( !shouldPass && !didPass ) - Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason ); - } - } - - [Test] - public void DetectWin95() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ), - "Win95,Win32Windows,Win32,Win" ); - } - - [Test] - public void DetectWin98() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ), - "Win98,Win32Windows,Win32,Win" ); - } - - [Test] - public void DetectWinMe() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ), - "WinMe,Win32Windows,Win32,Win" ); - } - - // WinCE isn't defined in .NET 1.0. - [Test, Platform(Exclude="Net-1.0")] - public void DetectWinCE() - { - PlatformID winCE = (PlatformID)Enum.Parse(typeof(PlatformID), "WinCE", false); - CheckOSPlatforms( - new OSPlatform(winCE, new Version(1, 0)), - "WinCE,Win32,Win" ); - } - - [Test] - public void DetectNT3() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ), - "NT3,Win32NT,Win32,Win" ); - } - - [Test] - public void DetectNT4() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ), - "NT4,Win32NT,Win32,Win,Win-4.0" ); - } - - [Test] - public void DetectWin2K() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ), - "Win2K,NT5,Win32NT,Win32,Win,Win-5.0" ); - } - - [Test] - public void DetectWinXP() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ), - "WinXP,NT5,Win32NT,Win32,Win,Win-5.1" ); - } - - [Test] - public void DetectWinXPProfessionalX64() - { - CheckOSPlatforms( - new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ), - "WinXP,NT5,Win32NT,Win32,Win,Win-5.1" ); - } - - [Test] - public void DetectWin2003Server() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server), - "Win2003Server,NT5,Win32NT,Win32,Win,Win-5.2"); - } - - [Test] - public void DetectVista() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation), - "Vista,NT6,Win32NT,Win32,Win,Win-6.0"); - } - - [Test] - public void DetectWin2008ServerOriginal() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server), - "Win2008Server,NT6,Win32NT,Win32,Win,Win-6.0"); - } - - [Test] - public void DetectWin2008ServerR2() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server), - "Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win,Win-6.0"); - } - - [Test] - public void DetectWindows7() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation), - "Windows7,NT6,Win32NT,Win32,Win,Win-6.1"); - } - - [Test] - public void DetectUnixUnderMicrosoftDotNet() - { - CheckOSPlatforms( - new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)), - "UNIX,Linux"); - } - - // This throws under Microsoft .Net due to the invlaid enumeration value of 128 - [Test] - public void DetectUnixUnderMono() - { - CheckOSPlatforms( - new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)), - "UNIX,Linux"); - } - -#if (CLR_2_0 || CLR_4_0) && !NETCF - [Test] - public void DetectXbox() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.Xbox, new Version(0,0)), - "Xbox"); - } - - [Test] - public void DetectMacOSX() - { - CheckOSPlatforms( - new OSPlatform(PlatformID.MacOSX, new Version(0, 0)), - "MacOSX"); - } -#endif - - [Test] - public void DetectNet10() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ), - "NET,NET-1.0" ); - } - - [Test] - public void DetectNet11() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ), - "NET,NET-1.1" ); - } - - [Test] - public void DetectNet20() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 50727, 0 ) ), - "Net,Net-2.0" ); - } - - [Test] - public void DetectNet30() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Net, new Version(3, 0)), - "Net,Net-2.0,Net-3.0"); - } - - [Test] - public void DetectNet35() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Net, new Version(3, 5)), - "Net,Net-2.0,Net-3.0,Net-3.5"); - } - - [Test] - public void DetectNet40() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)), - "Net,Net-4.0"); - } - - [Test] - public void DetectNetCF() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.NetCF, new Version( 1, 1, 4322, 0 ) ), - "NetCF" ); - } - - [Test] - public void DetectSSCLI() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ), - "SSCLI,Rotor" ); - } - - [Test] - public void DetectMono10() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ), - "Mono,Mono-1.0" ); - } - - [Test] - public void DetectMono20() - { - CheckRuntimePlatforms( - new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ), - "Mono,Mono-2.0" ); - } - - [Test] - public void DetectMono30() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)), - "Mono,Mono-2.0,Mono-3.0"); - } - - [Test] - public void DetectMono35() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)), - "Mono,Mono-2.0,Mono-3.0,Mono-3.5"); - } - - [Test] - public void DetectMono40() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)), - "Mono,Mono-4.0"); - } - - [Test] - public void DetectMonoTouch() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)), - "MonoTouch"); - } - - [Test] - public void DetectSilverlight30() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Silverlight, new Version(3, 0)), - "Silverlight,SL-3.0"); - } - - [Test] - public void DetectSilverlight40() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Silverlight, new Version(4, 0)), - "Silverlight,SL-4.0"); - } - - [Test] - public void DetectSilverlight50() - { - CheckRuntimePlatforms( - new RuntimeFramework(RuntimeType.Silverlight, new Version(5, 0)), - "Silverlight,SL-5.0"); - } - - [Test] - public void DetectExactVersion() - { - Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) ); - Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) ); - Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) ); - Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) ); - } - - [Test] - public void ArrayOfPlatforms() - { - string[] platforms = new string[] { "NT4", "Win2K", "WinXP" }; - Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) ); - Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) ); - } - - [Test] - public void PlatformAttribute_Include() - { - PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" ); - Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) ); - Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); - Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason); - } - - [Test] - public void PlatformAttribute_Exclude() - { - PlatformAttribute attr = new PlatformAttribute(); - attr.Exclude = "Win2K,WinXP,NT4"; - Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); - Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason ); - Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) ); - } - - [Test] - public void PlatformAttribute_IncludeAndExclude() - { - PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" ); - attr.Exclude = "Mono"; - Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); - Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason ); - Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) ); - attr.Exclude = "Net"; - Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) ); - Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason ); - Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); - Assert.AreEqual( "Not supported on Net", winXPHelper.Reason ); - } - - [Test] - public void PlatformAttribute_InvalidPlatform() - { - PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" ); - Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) ); - Assert.That( winXPHelper.Reason, Is.StringStarting("Invalid platform name")); - Assert.That( winXPHelper.Reason, Is.StringContaining("Net11")); - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/PropertyBagTests.cs b/test/NUnitLite/src/tests/Internal/PropertyBagTests.cs deleted file mode 100644 index 0595454a1..000000000 --- a/test/NUnitLite/src/tests/Internal/PropertyBagTests.cs +++ /dev/null @@ -1,184 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class PropertyBagTests - { - PropertyBag bag; - - [SetUp] - public void SetUp() - { - bag = new PropertyBag(); - bag.Add("Answer", 42); - bag.Add("Tag", "bug"); - bag.Add("Tag", "easy"); - } - - [Test] - public void CountReflectsNumberOfPairs() - { - Assert.That(bag.Count, Is.EqualTo(3)); - } - - [Test] - public void IndexGetsListOfValues() - { - Assert.That(bag["Answer"].Count, Is.EqualTo(1)); - Assert.That(bag["Answer"], Contains.Item(42)); - - Assert.That(bag["Tag"].Count, Is.EqualTo(2)); - Assert.That(bag["Tag"], Contains.Item("bug")); - Assert.That(bag["Tag"], Contains.Item("easy")); - } - - [Test] - public void IndexGetsEmptyListIfNameIsNotPresent() - { - Assert.That(bag["Level"].Count, Is.EqualTo(0)); - } - - [Test] - public void IndexSetsListOfValues() - { - bag["Zip"] = new string[] {"junk", "more junk"}; - Assert.That(bag["Zip"].Count, Is.EqualTo(2)); - Assert.That(bag["Zip"], Contains.Item("junk")); - Assert.That(bag["Zip"], Contains.Item("more junk")); - } - - [Test] - public void CanClearTheBag() - { - bag.Clear(); - Assert.That(bag.Keys.Count, Is.EqualTo(0)); - Assert.That(bag.Count, Is.EqualTo(0)); - } - - [Test] - public void AllKeysAreListed() - { - Assert.That(bag.Keys.Count, Is.EqualTo(2)); - Assert.That(bag.Keys, Has.Member("Answer")); - Assert.That(bag.Keys, Has.Member("Tag")); - } - - [Test] - public void ContainsKey() - { - Assert.That(bag.ContainsKey("Answer")); - Assert.That(bag.ContainsKey("Tag")); - Assert.False(bag.ContainsKey("Target")); - } - - [Test] - public void ContainsKeyAndValue() - { - Assert.That(bag.Contains("Answer", 42)); - } - - [Test] - public void ContainsPropertyEntry() - { - Assert.That(bag.Contains(new PropertyEntry("Answer", 42))); - } - - [Test] - public void CanRemoveKey() - { - bag.Remove("Tag"); - Assert.That(bag.Keys.Count, Is.EqualTo(1)); - Assert.That(bag.Count, Is.EqualTo(1)); - Assert.That(bag.Keys, Has.No.Member("Tag")); - } - - [Test] - public void CanRemoveMissingKeyWithoutError() - { - bag.Remove("Zip"); - } - - [Test] - public void CanRemoveNameAndValue() - { - bag.Remove("Tag", "easy"); - Assert.That(bag["Tag"].Contains("bug")); - Assert.False(bag["Tag"].Contains("easy")); - Assert.That(bag.Count, Is.EqualTo(2)); - } - - [Test] - public void CanRemoveNameAndMissingValueWithoutError() - { - bag.Remove("Tag", "wishlist"); - } - - [Test] - public void CanRemovePropertyEntry() - { - bag.Remove(new PropertyEntry("Tag", "easy")); - Assert.That(bag["Tag"].Contains("bug")); - Assert.False(bag["Tag"].Contains("easy")); - Assert.That(bag.Count, Is.EqualTo(2)); - } - - [Test] - public void GetReturnsSingleValue() - { - Assert.That(bag.Get("Answer"), Is.EqualTo(42)); - Assert.That(bag.Get("Tag"), Is.EqualTo("bug")); - } - - [Test] - public void SetAddsNewSingleValue() - { - bag.Set("Zip", "ZAP"); - Assert.That(bag["Zip"].Count, Is.EqualTo(1)); - Assert.That(bag["Zip"], Has.Member("ZAP")); - Assert.That(bag.Get("Zip"), Is.EqualTo("ZAP")); - } - - [Test] - public void SetReplacesOldValues() - { - bag.Set("Tag", "ZAPPED"); - Assert.That(bag["Tag"].Count, Is.EqualTo(1)); - Assert.That(bag.Get("Tag"), Is.EqualTo("ZAPPED")); - } - - [Test] - public void EnumeratorReturnsAllEntries() - { - int count = 0; - // NOTE: Ignore unsuppressed warning about entry in .NET 1.1 build - foreach (PropertyEntry entry in bag) - ++count; - Assert.That(count, Is.EqualTo(3)); - - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/RandomGeneratorTests.cs b/test/NUnitLite/src/tests/Internal/RandomGeneratorTests.cs deleted file mode 100644 index dca3f55d4..000000000 --- a/test/NUnitLite/src/tests/Internal/RandomGeneratorTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections; -using NUnit.Framework; -using NUnit.Framework.Internal; -using NUnit.TestUtilities; - -namespace NUnitLite.Tests.Internal -{ - public class RandomGeneratorTests - { - #region Properties & Constructor - public RandomGeneratorTests() - { - } - #endregion - - #region Ints - [Test] - public static void RandomIntsAreUnique() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - int[] values = new int[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetInt(); - - UniqueValues.Check(values, 8); // Heuristic - } - [TestCase(-300,300)] - public static void RandomIntsAreUnique(int min, int max) - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - int[] values = new int[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetInt(min,max); - - UniqueValues.Check(values, 8); // Heuristic - } - #endregion - - #region Shorts - [Test] - public static void RandomShortsAreUnique() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - short[] values = new short[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetShort(); - - UniqueValues.Check(values, 8); // Heuristic - } - [TestCase(-300, 300)] - public static void RandomShortsAreUnique(short min, short max) - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - short[] values = new short[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetShort(min, max); - - UniqueValues.Check(values, 8); // Heuristic - } - #endregion - - #region Btyes - [Test] - public static void RandomBytesAreUnique() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - byte[] values = new byte[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetByte(); - - UniqueValues.Check(values, 8); // Heuristic - } - - [TestCase(12, 212)] - public static void RandomBytesAreUnique(byte min, byte max) - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - byte[] values = new byte[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetByte(min, max); - - UniqueValues.Check(values, 8); // Heuristic - } - #endregion - - #region Bool - [Test] - public static void CanGetRandomBool() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - bool[] values = new bool[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetBool(); - Assert.That(values, Contains.Item(true)); - Assert.That(values, Contains.Item(false)); - } - - public static void CanGetRandomBoolWithProbability() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - for (int i = 0; i < 10; i++) - { - Assert.True(r.GetBool(.0)); - Assert.False(r.GetBool(1.0)); - } - } - #endregion - - #region Doubles & Floats - [Test] - public static void RandomDoublesAreUnique() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - double[] values = new double[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetDouble(); - - UniqueValues.Check(values, 8); // Heuristic - } - - [Test] - public static void RandomFloatsAreUnique() - { - RandomGenerator r = new RandomGenerator(new Random().Next()); - double[] values = new double[10]; - for (int i = 0; i < 10; i++) - values[i] = r.GetFloat(); - - UniqueValues.Check(values, 8); // Heuristic - } - #endregion - } -} diff --git a/test/NUnitLite/src/tests/Internal/RandomizerTests.cs b/test/NUnitLite/src/tests/Internal/RandomizerTests.cs deleted file mode 100644 index 8dcef7d46..000000000 --- a/test/NUnitLite/src/tests/Internal/RandomizerTests.cs +++ /dev/null @@ -1,169 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Internal -{ - public class RandomizerTests - { - [Test] - public void RandomizersAreUnique() - { - int[] values = new int[10]; - for (int i = 0; i < 10; i++) - values[i] = Randomizer.CreateRandomizer().Next(); - - Assert.That(values, Is.Unique); - } - - [Test] - public void RandomIntsAreUnique() - { - Randomizer r = Randomizer.CreateRandomizer(); - - int[] values = new int[10]; - for (int i = 0; i < 10; i++) - values[i] = r.Next(); - - Assert.That(values, Is.Unique); - } - - [Test] - public void RandomDoublesAreUnique() - { - Randomizer r = Randomizer.CreateRandomizer(); - - double[] values = new double[10]; - for (int i = 0; i < 10; i++) - values[i] = r.NextDouble(); - - Assert.That(values, Is.Unique); - } - - [Test] - public void CanGetArrayOfRandomInts() - { - Randomizer r = Randomizer.CreateRandomizer(); - - int[] ints = r.GetInts(1, 100, 10); - Assert.That(ints.Length, Is.EqualTo(10)); - foreach (int i in ints) - Assert.That(i, Is.InRange(1, 100)); - } - - [Test] - public void CanGetArrayOfRandomDoubles() - { - Randomizer r = Randomizer.CreateRandomizer(); - - double[] doubles = r.GetDoubles(0.5, 1.5, 10); - Assert.That(doubles.Length, Is.EqualTo(10)); - foreach (double d in doubles) - Assert.That(d, Is.InRange(0.5, 1.5)); - - // Heuristic: Could fail occasionally - Assert.That(doubles, Is.Unique); - } - - [Test] - public void CanGetArrayOfRandomEnums() - { - Randomizer r = Randomizer.CreateRandomizer(); - - object[] enums = r.GetEnums(10, typeof(AttributeTargets)); - Assert.That(enums.Length, Is.EqualTo(10)); - foreach (object e in enums) - Assert.That(e, Is.TypeOf(typeof(AttributeTargets))); - } - - [Test] - public void RandomizersWithSameSeedsReturnSameValues() - { - Randomizer r1 = new Randomizer(1234); - Randomizer r2 = new Randomizer(1234); - - for (int i = 0; i < 10; i++) - Assert.That(r1.NextDouble(), Is.EqualTo(r2.NextDouble())); - } - - [Test] - public void RandomizersWithDifferentSeedsReturnDifferentValues() - { - Randomizer r1 = new Randomizer(1234); - Randomizer r2 = new Randomizer(4321); - - for (int i = 0; i < 10; i++) - Assert.That(r1.NextDouble(), Is.Not.EqualTo(r2.NextDouble())); - } - - [Test] - public void ReturnsSameRandomizerForSameParameter() - { - ParameterInfo p = testMethod1.GetParameters()[0]; - Randomizer r1 = Randomizer.GetRandomizer(p); - Randomizer r2 = Randomizer.GetRandomizer(p); - Assert.That(r1, Is.SameAs(r2)); - } - - [Test] - public void ReturnsSameRandomizerForDifferentParametersOfSameMethod() - { - ParameterInfo p1 = testMethod1.GetParameters()[0]; - ParameterInfo p2 = testMethod1.GetParameters()[1]; - Randomizer r1 = Randomizer.GetRandomizer(p1); - Randomizer r2 = Randomizer.GetRandomizer(p2); - Assert.That(r1, Is.SameAs(r2)); - } - - [Test] - public void ReturnsSameRandomizerForSameMethod() - { - Randomizer r1 = Randomizer.GetRandomizer(testMethod1); - Randomizer r2 = Randomizer.GetRandomizer(testMethod1); - Assert.That(r1, Is.SameAs(r2)); - } - - [Test] - public void ReturnsDifferentRandomizersForDifferentMethods() - { - Randomizer r1 = Randomizer.GetRandomizer(testMethod1); - Randomizer r2 = Randomizer.GetRandomizer(testMethod2); - Assert.That(r1, Is.Not.SameAs(r2)); - } - - static readonly MethodInfo testMethod1 = - typeof(RandomizerTests).GetMethod("TestMethod1", BindingFlags.NonPublic | BindingFlags.Instance); - private void TestMethod1(int x, int y) - { - } - - static readonly MethodInfo testMethod2 = - typeof(RandomizerTests).GetMethod("TestMethod2", BindingFlags.NonPublic | BindingFlags.Instance); - private void TestMethod2(int x, int y) - { - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/RuntimeFrameworkTests.cs b/test/NUnitLite/src/tests/Internal/RuntimeFrameworkTests.cs deleted file mode 100644 index 8e4889822..000000000 --- a/test/NUnitLite/src/tests/Internal/RuntimeFrameworkTests.cs +++ /dev/null @@ -1,287 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using Microsoft.Win32; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class RuntimeFrameworkTests - { - [Test] - public void CanGetCurrentFramework() - { - Version expectedClrVersion = Environment.Version; - Version expectedFrameworkVersion = new Version(expectedClrVersion.Major, expectedClrVersion.Minor); - -#if SILVERLIGHT - RuntimeType expectedRuntime = RuntimeType.Silverlight; - expectedClrVersion = new RuntimeFramework(expectedRuntime, expectedFrameworkVersion).ClrVersion; -#else - RuntimeType expectedRuntime = Type.GetType("Mono.Runtime", false) != null - ? RuntimeType.Mono - : Environment.OSVersion.Platform == PlatformID.WinCE - ? RuntimeType.NetCF - : RuntimeType.Net; - - // TODO: Remove duplication of RuntimeFramework code - switch (expectedRuntime) - { - case RuntimeType.Mono: - if (expectedFrameworkVersion.Major == 1) - expectedFrameworkVersion = new Version(1,0); - else if (expectedFrameworkVersion.Major == 2) - expectedFrameworkVersion = new Version(3,5); - break; - - case RuntimeType.Net: - case RuntimeType.NetCF: - if (expectedFrameworkVersion.Major == 2) - { - RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"); - if (key != null) - { - string installRoot = key.GetValue("InstallRoot") as string; - if (installRoot != null) - { - if (Directory.Exists(Path.Combine(installRoot, "v3.5"))) - expectedFrameworkVersion = new Version(3,5); - else if (Directory.Exists(Path.Combine(installRoot, "v3.0"))) - expectedFrameworkVersion = new Version(3,0); - } - } - } - break; - } -#endif - - RuntimeFramework framework = RuntimeFramework.CurrentFramework; - - Assert.That(framework.Runtime, Is.EqualTo(expectedRuntime)); - Assert.That(framework.ClrVersion, Is.EqualTo(expectedClrVersion)); - Assert.That(framework.FrameworkVersion, Is.EqualTo(expectedFrameworkVersion)); - } - - [Test] - public void CurrentFrameworkHasBuildSpecified() - { - Assert.That(RuntimeFramework.CurrentFramework.ClrVersion.Build, Is.GreaterThan(0)); - } - -#if !NUNITLITE - [Test, Platform(Exclude="NETCF", Reason="NYI")] - public void CurrentFrameworkMustBeAvailable() - { - Assert.That(RuntimeFramework.CurrentFramework.IsAvailable); - } - - [Test, Platform(Exclude="NETCF", Reason="NYI")] - public void CanListAvailableFrameworks() - { - RuntimeFramework[] available = RuntimeFramework.AvailableFrameworks; - Assert.That(available, Has.Length.GreaterThan(0) ); - bool foundCurrent = false; - foreach (RuntimeFramework framework in available) - { - Console.WriteLine("Available: {0}", framework.DisplayName); - foundCurrent |= RuntimeFramework.CurrentFramework.Supports(framework); - } - Assert.That(foundCurrent, "CurrentFramework not listed"); - } -#endif - - [TestCaseSource("frameworkData")] - public void CanCreateUsingFrameworkVersion(FrameworkData data) - { - RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); - Assert.AreEqual(data.runtime, framework.Runtime); - Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion); - Assert.AreEqual(data.clrVersion, framework.ClrVersion); - } - - [TestCaseSource("frameworkData")] - public void CanCreateUsingClrVersion(FrameworkData data) - { - Assume.That(data.frameworkVersion.Major != 3); - - RuntimeFramework framework = new RuntimeFramework(data.runtime, data.clrVersion); - Assert.AreEqual(data.runtime, framework.Runtime); - Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion); - Assert.AreEqual(data.clrVersion, framework.ClrVersion); - } - - [TestCaseSource("frameworkData")] - public void CanParseRuntimeFramework(FrameworkData data) - { - RuntimeFramework framework = RuntimeFramework.Parse(data.representation); - Assert.AreEqual(data.runtime, framework.Runtime); - Assert.AreEqual(data.clrVersion, framework.ClrVersion); - } - - [TestCaseSource("frameworkData")] - public void CanDisplayFrameworkAsString(FrameworkData data) - { - RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); - Assert.AreEqual(data.representation, framework.ToString()); - Assert.AreEqual(data.displayName, framework.DisplayName); - } - - [TestCaseSource("matchData")] - public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2) - { - return f1.Supports(f2); - } - - internal static TestCaseData[] matchData = new TestCaseData[] { - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(3,5)), - new RuntimeFramework(RuntimeType.Net, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Net, new Version(3,5))) - .Returns(false), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(3,5)), - new RuntimeFramework(RuntimeType.Net, new Version(3,5))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Net, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), - new RuntimeFramework(RuntimeType.Net, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), - new RuntimeFramework(RuntimeType.Net, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Mono, new Version(2,0))) - .Returns(false), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Net, new Version(1,1))) - .Returns(false), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), - new RuntimeFramework(RuntimeType.Net, new Version(2,0,40607))) - .Returns(false), - new TestCaseData( - new RuntimeFramework(RuntimeType.Mono, new Version(1,1)), // non-existent version but it works - new RuntimeFramework(RuntimeType.Mono, new Version(1,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Mono, new Version(2,0)), - new RuntimeFramework(RuntimeType.Any, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Any, new Version(2,0)), - new RuntimeFramework(RuntimeType.Mono, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Any, new Version(2,0)), - new RuntimeFramework(RuntimeType.Any, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Any, new Version(2,0)), - new RuntimeFramework(RuntimeType.Any, new Version(4,0))) - .Returns(false), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion), - new RuntimeFramework(RuntimeType.Net, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion)) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion), - new RuntimeFramework(RuntimeType.Net, new Version(2,0))) - .Returns(true), - new TestCaseData( - new RuntimeFramework(RuntimeType.Net, new Version(2,0)), - new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion)) - .Returns(true) - }; - - public struct FrameworkData - { - public RuntimeType runtime; - public Version frameworkVersion; - public Version clrVersion; - public string representation; - public string displayName; - - public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion, - string representation, string displayName) - { - this.runtime = runtime; - this.frameworkVersion = frameworkVersion; - this.clrVersion = clrVersion; - this.representation = representation; - this.displayName = displayName; - } - - public override string ToString() - { - return string.Format("<{0},{1},{2}>", this.runtime, this.frameworkVersion, this.clrVersion); - } - } - - internal FrameworkData[] frameworkData = new FrameworkData[] { - new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0", "Net 1.0"), - //new FrameworkData(RuntimeType.Net, new Version(1,0,3705), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"), - //new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"), - new FrameworkData(RuntimeType.Net, new Version(1,1), new Version(1,1,4322), "net-1.1", "Net 1.1"), - //new FrameworkData(RuntimeType.Net, new Version(1,1,4322), new Version(1,1,4322), "net-1.1.4322", "Net 1.1.4322"), - new FrameworkData(RuntimeType.Net, new Version(2,0), new Version(2,0,50727), "net-2.0", "Net 2.0"), - //new FrameworkData(RuntimeType.Net, new Version(2,0,40607), new Version(2,0,40607), "net-2.0.40607", "Net 2.0.40607"), - //new FrameworkData(RuntimeType.Net, new Version(2,0,50727), new Version(2,0,50727), "net-2.0.50727", "Net 2.0.50727"), - new FrameworkData(RuntimeType.Net, new Version(3,0), new Version(2,0,50727), "net-3.0", "Net 3.0"), - new FrameworkData(RuntimeType.Net, new Version(3,5), new Version(2,0,50727), "net-3.5", "Net 3.5"), - new FrameworkData(RuntimeType.Net, new Version(4,0), new Version(4,0,30319), "net-4.0", "Net 4.0"), - new FrameworkData(RuntimeType.Net, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "net", "Net"), - new FrameworkData(RuntimeType.Mono, new Version(1,0), new Version(1,1,4322), "mono-1.0", "Mono 1.0"), - new FrameworkData(RuntimeType.Mono, new Version(2,0), new Version(2,0,50727), "mono-2.0", "Mono 2.0"), - //new FrameworkData(RuntimeType.Mono, new Version(2,0,50727), new Version(2,0,50727), "mono-2.0.50727", "Mono 2.0.50727"), - new FrameworkData(RuntimeType.Mono, new Version(3,5), new Version(2,0,50727), "mono-3.5", "Mono 3.5"), - new FrameworkData(RuntimeType.Mono, new Version(4,0), new Version(4,0,30319), "mono-4.0", "Mono 4.0"), - new FrameworkData(RuntimeType.Mono, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "mono", "Mono"), - new FrameworkData(RuntimeType.Any, new Version(1,1), new Version(1,1,4322), "v1.1", "v1.1"), - new FrameworkData(RuntimeType.Any, new Version(2,0), new Version(2,0,50727), "v2.0", "v2.0"), - //new FrameworkData(RuntimeType.Any, new Version(2,0,50727), new Version(2,0,50727), "v2.0.50727", "v2.0.50727"), - new FrameworkData(RuntimeType.Any, new Version(3,5), new Version(2,0,50727), "v3.5", "v3.5"), - new FrameworkData(RuntimeType.Any, new Version(4,0), new Version(4,0,30319), "v4.0", "v4.0"), - new FrameworkData(RuntimeType.Any, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "any", "Any") - }; - } -} diff --git a/test/NUnitLite/src/tests/Internal/SetUpTest.cs b/test/NUnitLite/src/tests/Internal/SetUpTest.cs deleted file mode 100644 index 30285e81e..000000000 --- a/test/NUnitLite/src/tests/Internal/SetUpTest.cs +++ /dev/null @@ -1,161 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.TestUtilities; -using NUnit.TestData.SetUpData; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class SetUpTest - { - [Test] - public void SetUpAndTearDownCounter() - { - SetUpAndTearDownCounterFixture fixture = new SetUpAndTearDownCounterFixture(); - TestBuilder.RunTestFixture( fixture ); - - Assert.AreEqual(3, fixture.setUpCounter); - Assert.AreEqual(3, fixture.tearDownCounter); - } - - - [Test] - public void MakeSureSetUpAndTearDownAreCalled() - { - SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture(); - TestBuilder.RunTestFixture( fixture ); - - Assert.IsTrue(fixture.wasSetUpCalled); - Assert.IsTrue(fixture.wasTearDownCalled); - } - - [Test] - public void CheckInheritedSetUpAndTearDownAreCalled() - { - InheritSetUpAndTearDown fixture = new InheritSetUpAndTearDown(); - TestBuilder.RunTestFixture( fixture ); - - Assert.IsTrue(fixture.wasSetUpCalled); - Assert.IsTrue(fixture.wasTearDownCalled); - } - - [Test] - public void CheckOverriddenSetUpAndTearDownAreNotCalled() - { - DefineInheritSetUpAndTearDown fixture = new DefineInheritSetUpAndTearDown(); - TestBuilder.RunTestFixture( fixture ); - - Assert.IsFalse(fixture.wasSetUpCalled); - Assert.IsFalse(fixture.wasTearDownCalled); - Assert.IsTrue(fixture.derivedSetUpCalled); - Assert.IsTrue(fixture.derivedTearDownCalled); - } - - [Test] - public void MultipleSetUpAndTearDownMethodsAreCalled() - { - MultipleSetUpTearDownFixture fixture = new MultipleSetUpTearDownFixture(); - TestBuilder.RunTestFixture(fixture); - - Assert.IsTrue(fixture.wasSetUp1Called, "SetUp1"); - Assert.IsTrue(fixture.wasSetUp2Called, "SetUp2"); - Assert.IsTrue(fixture.wasSetUp3Called, "SetUp3"); - Assert.IsTrue(fixture.wasTearDown1Called, "TearDown1"); - Assert.IsTrue(fixture.wasTearDown2Called, "TearDown2"); - } - - [Test] - public void BaseSetUpIsCalledFirstTearDownLast() - { - DerivedClassWithSeparateSetUp fixture = new DerivedClassWithSeparateSetUp(); - TestBuilder.RunTestFixture(fixture); - - Assert.IsTrue(fixture.wasSetUpCalled, "Base SetUp Called"); - Assert.IsTrue(fixture.wasTearDownCalled, "Base TearDown Called"); - Assert.IsTrue(fixture.wasDerivedSetUpCalled, "Derived SetUp Called"); - Assert.IsTrue(fixture.wasDerivedTearDownCalled, "Derived TearDown Called"); - Assert.IsTrue(fixture.wasBaseSetUpCalledFirst, "SetUp Order"); - Assert.IsTrue(fixture.wasBaseTearDownCalledLast, "TearDown Order"); - } - - [Test] - public void SetupRecordsOriginalExceptionThownByTestCase() - { - Exception e = new Exception("Test message for exception thrown from setup"); - SetupAndTearDownExceptionFixture fixture = new SetupAndTearDownExceptionFixture(); - fixture.setupException = e; - TestResult suiteResult = TestBuilder.RunTestFixture(fixture); - Assert.IsTrue(suiteResult.HasChildren, "Fixture test should have child result."); - TestResult result = (TestResult)suiteResult.Children[0]; - Assert.AreEqual(result.ResultState, ResultState.Error, "Test should be in error state"); - string expected = string.Format("{0} : {1}", e.GetType().FullName, e.Message); - Assert.AreEqual(expected, result.Message); - } - - [Test] - public void TearDownRecordsOriginalExceptionThownByTestCase() - { - Exception e = new Exception("Test message for exception thrown from tear down"); - SetupAndTearDownExceptionFixture fixture = new SetupAndTearDownExceptionFixture(); - fixture.tearDownException = e; - TestResult suiteResult = TestBuilder.RunTestFixture(fixture); - Assert.That(suiteResult.HasChildren, "Fixture test should have child result."); - TestResult result = (TestResult)suiteResult.Children[0]; - Assert.AreEqual(result.ResultState, ResultState.Error, "Test should be in error state"); - string expected = string.Format("TearDown : {0} : {1}", e.GetType().FullName, e.Message); - Assert.AreEqual(expected, result.Message); - } - - public class SetupCallBase - { - protected int setupCount = 0; - public virtual void Init() - { - setupCount++; - } - public virtual void AssertCount() - { - } - } - - [TestFixture] - // Test for bug 441022 - public class SetupCallDerived : SetupCallBase - { - [SetUp] - public override void Init() - { - setupCount++; - base.Init(); - } - [Test] - public override void AssertCount() - { - Assert.AreEqual(2, setupCount); - } - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/SimpleGenericMethods.cs b/test/NUnitLite/src/tests/Internal/SimpleGenericMethods.cs deleted file mode 100644 index 86f92136b..000000000 --- a/test/NUnitLite/src/tests/Internal/SimpleGenericMethods.cs +++ /dev/null @@ -1,67 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if (CLR_2_0 || CLR_4_0) && !NETCF -using System; -using System.Collections.Generic; - -namespace NUnit.Framework.Internal -{ - [TestFixture,Category("Generics")] - class SimpleGenericMethods - { - [TestCase(5, 2, "ABC")] - [TestCase(5.0, 2.0, "ABC")] - [TestCase(5, 2.0, "ABC")] - [TestCase(5.0, 2L, "ABC")] - public void GenericTestMethodWithOneTypeParameter(T x, T y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - - [TestCase(5, 2, "ABC")] - [TestCase(5.0, 2.0, "ABC")] - [TestCase(5, 2.0, "ABC")] - [TestCase(5.0, 2L, "ABC")] - public void GenericTestMethodWithTwoTypeParameters(T1 x, T2 y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - - [TestCase(5, 2, "ABC")] - [TestCase(5.0, 2.0, "ABC")] - [TestCase(5, 2.0, "ABC")] - [TestCase(5.0, 2L, "ABC")] - public void GenericTestMethodWithTwoTypeParameters_Reversed(T2 x, T1 y, string label) - { - Assert.AreEqual(5, x); - Assert.AreEqual(2, y); - Assert.AreEqual("ABC", label); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Internal/TestExecutionContextTests.cs b/test/NUnitLite/src/tests/Internal/TestExecutionContextTests.cs deleted file mode 100644 index 9f8cac77d..000000000 --- a/test/NUnitLite/src/tests/Internal/TestExecutionContextTests.cs +++ /dev/null @@ -1,242 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Threading; -using System.Globalization; -using NUnit.Framework; -#if !NETCF && !SILVERLIGHT -using System.Security.Principal; -#endif -#if !NUNITLITE -using NUnit.TestData.TestContextData; -using NUnit.TestUtilities; -#endif - -namespace NUnit.Framework.Internal -{ - /// - /// Summary description for TestExecutionContextTests. - /// - [TestFixture][Property("Question", "Why?")] - public class TestExecutionContextTests - { - TestExecutionContext fixtureContext; - TestExecutionContext setupContext; - -#if !NETCF - CultureInfo currentCulture; - CultureInfo currentUICulture; -#endif - -#if !NETCF && !SILVERLIGHT - string currentDirectory; - IPrincipal currentPrincipal; -#endif - - [TestFixtureSetUp] - public void OneTimeSetUp() - { - fixtureContext = TestExecutionContext.CurrentContext; - } - - [TestFixtureTearDown] - public void OneTimeTearDown() - { - // TODO: We put some tests in one time teardown to verify that - // the context is still valid. It would be better if these tests - // were placed in a second-level test, invoked from this test class. - TestExecutionContext ec = TestExecutionContext.CurrentContext; - Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); - Assert.That(ec.CurrentTest.FullName, - Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); - Assert.That(fixtureContext.CurrentTest.Id, Is.GreaterThan(0)); - Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); - } - - /// - /// Since we are testing the mechanism that saves and - /// restores contexts, we save manually here - /// - [SetUp] - public void Initialize() - { - setupContext = new TestExecutionContext(TestExecutionContext.CurrentContext); -#if !NETCF - currentCulture = CultureInfo.CurrentCulture; - currentUICulture = CultureInfo.CurrentUICulture; -#endif - -#if !NETCF && !SILVERLIGHT - currentDirectory = Environment.CurrentDirectory; - currentPrincipal = Thread.CurrentPrincipal; -#endif - } - - [TearDown] - public void Cleanup() - { -#if !NETCF - Thread.CurrentThread.CurrentCulture = currentCulture; - Thread.CurrentThread.CurrentUICulture = currentUICulture; -#endif - -#if !NETCF && !SILVERLIGHT - Environment.CurrentDirectory = currentDirectory; - Thread.CurrentPrincipal = currentPrincipal; -#endif - - Assert.That( - TestExecutionContext.CurrentContext.CurrentTest.FullName, - Is.EqualTo(setupContext.CurrentTest.FullName), - "Context at TearDown failed to match that saved from SetUp"); - } - - [Test] - public void FixtureSetUpCanAccessFixtureName() - { - Assert.That(fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); - } - - [Test] - public void FixtureSetUpCanAccessFixtureFullName() - { - Assert.That(fixtureContext.CurrentTest.FullName, - Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); - } - - [Test] - public void FixtureSetUpCanAccessFixtureId() - { - Assert.That(fixtureContext.CurrentTest.Id, Is.GreaterThan(0)); - } - - [Test] - public void FixtureSetUpCanAccessFixtureProperties() - { - Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); - } - - [Test] - public void SetUpCanAccessTestName() - { - Assert.That(setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName")); - } - - [Test] - public void SetUpCanAccessTestFullName() - { - Assert.That(setupContext.CurrentTest.FullName, - Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName")); - } - - [Test] - public void SetUpCanAccessTestId() - { - Assert.That(setupContext.CurrentTest.Id, Is.GreaterThan(0)); - } - - [Test] - [Property("Answer", 42)] - public void SetUpCanAccessTestProperties() - { - Assert.That(setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); - } - - [Test] - public void TestCanAccessItsOwnName() - { - Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName")); - } - - [Test] - public void TestCanAccessItsOwnFullName() - { - Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, - Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName")); - } - - [Test] - public void TestCanAccessItsOwnId() - { - Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.GreaterThan(0)); - } - - [Test] - [Property("Answer", 42)] - public void TestCanAccessItsOwnProperties() - { - Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); - } - -#if !NETCF - [Test] - public void SetAndRestoreCurrentCulture() - { - Assert.AreEqual(setupContext.CurrentCulture, CultureInfo.CurrentCulture, "Culture not in initial context"); - - TestExecutionContext context = setupContext.Save(); - - try - { - CultureInfo otherCulture = - new CultureInfo(currentCulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); - context.CurrentCulture = otherCulture; - Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set"); - Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context"); - } - finally - { - context = context.Restore(); - } - - Assert.AreEqual(currentCulture, CultureInfo.CurrentCulture, "Culture was not restored"); - Assert.AreEqual(currentCulture, context.CurrentCulture, "Culture not in final context"); - } - - [Test] - public void SetAndRestoreCurrentUICulture() - { - Assert.AreEqual(currentUICulture, setupContext.CurrentUICulture, "UICulture not in initial context"); - - TestExecutionContext context = setupContext.Save(); - - try - { - CultureInfo otherCulture = - new CultureInfo(currentUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); - context.CurrentUICulture = otherCulture; - Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set"); - Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context"); - } - finally - { - context = context.Restore(); - } - - Assert.AreEqual(currentUICulture, CultureInfo.CurrentUICulture, "UICulture was not restored"); - Assert.AreEqual(currentUICulture, context.CurrentUICulture, "UICulture not in final context"); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Internal/TestFixtureTests.cs b/test/NUnitLite/src/tests/Internal/TestFixtureTests.cs deleted file mode 100644 index 5e1364a41..000000000 --- a/test/NUnitLite/src/tests/Internal/TestFixtureTests.cs +++ /dev/null @@ -1,406 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Api; -using NUnit.TestData.FixtureSetUpTearDownData; -using NUnit.TestUtilities; -using NUnit.TestData.TestFixtureData; -using IgnoredFixture = NUnit.TestData.TestFixtureData.IgnoredFixture; - -namespace NUnit.Framework.Internal -{ - /// - /// Tests of the NUnitTestFixture class - /// - [TestFixture] - public class TestFixtureTests - { - private static void CanConstructFrom(Type fixtureType) - { - CanConstructFrom(fixtureType, fixtureType.Name); - } - - private static void CanConstructFrom(Type fixtureType, string expectedName) - { - TestSuite fixture = TestBuilder.MakeFixture(fixtureType); - Assert.AreEqual(expectedName, fixture.Name); - Assert.AreEqual(fixtureType.FullName, fixture.FullName); - } - - [Test] - public void ConstructFromType() - { - CanConstructFrom(typeof(FixtureWithTestFixtureAttribute)); - } - - [Test] - public void ConstructFromNestedType() - { - CanConstructFrom(typeof(OuterClass.NestedTestFixture), "OuterClass+NestedTestFixture"); - } - - [Test] - public void ConstructFromDoublyNestedType() - { - CanConstructFrom(typeof(OuterClass.NestedTestFixture.DoublyNestedTestFixture), - "OuterClass+NestedTestFixture+DoublyNestedTestFixture"); - } - - public void ConstructFromTypeWithoutTestFixtureAttributeContainingTest() - { - CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTest)); - } - - [Test] - public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCase() - { - CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCase)); - } - - [Test] - public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCaseSource() - { - CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCaseSource)); - } - -#if !NUNITLITE - [Test] - public void ConstructFromTypeWithoutTestFixtureAttributeContainingTheory() - { - CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTheory)); - } -#endif - - [Test] - public void CannotRunConstructorWithArgsNotSupplied() - { - TestAssert.IsNotRunnable(typeof(NoDefaultCtorFixture)); - } - - [Test] - public void CanRunConstructorWithArgsSupplied() - { - TestAssert.IsRunnable(typeof(FixtureWithArgsSupplied), ResultState.Success); - } - - [Test] - public void CannotRunBadConstructor() - { - TestAssert.IsNotRunnable(typeof(BadCtorFixture)); - } - - [Test] - public void CanRunMultipleSetUp() - { - TestAssert.IsRunnable(typeof(MultipleSetUpAttributes), ResultState.Success); - } - - [Test] - public void CanRunMultipleTearDown() - { - TestAssert.IsRunnable(typeof(MultipleTearDownAttributes), ResultState.Success); - } - - [Test] - public void CannotRunIgnoredFixture() - { - TestSuite suite = TestBuilder.MakeFixture( typeof( IgnoredFixture ) ); - Assert.AreEqual( RunState.Ignored, suite.RunState ); - Assert.AreEqual( "testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason) ); - } - -// [Test] -// public void CannotRunAbstractFixture() -// { -// TestAssert.IsNotRunnable(typeof(AbstractTestFixture)); -// } - - [Test] - public void CanRunFixtureDerivedFromAbstractTestFixture() - { - TestAssert.IsRunnable(typeof(DerivedFromAbstractTestFixture), ResultState.Success); - } - - [Test] - public void CanRunFixtureDerivedFromAbstractDerivedTestFixture() - { - TestAssert.IsRunnable(typeof(DerivedFromAbstractDerivedTestFixture), ResultState.Success); - } - -// [Test] -// public void CannotRunAbstractDerivedFixture() -// { -// TestAssert.IsNotRunnable(typeof(AbstractDerivedTestFixture)); -// } - - [Test] - public void FixtureInheritingTwoTestFixtureAttributesIsLoadedOnlyOnce() - { - TestSuite suite = TestBuilder.MakeFixture(typeof(DoubleDerivedClassWithTwoInheritedAttributes)); - Assert.That(suite, Is.TypeOf(typeof(TestFixture))); - Assert.That(suite.Tests.Count, Is.EqualTo(0)); - } - - [Test] - public void CanRunMultipleTestFixtureSetUp() - { - TestAssert.IsRunnable(typeof(MultipleFixtureSetUpAttributes), ResultState.Success); - } - - [Test] - public void CanRunMultipleTestFixtureTearDown() - { - TestAssert.IsRunnable(typeof(MultipleFixtureTearDownAttributes), ResultState.Success); - } - - [Test] - public void CanRunTestFixtureWithNoTests() - { - TestAssert.IsRunnable(typeof(FixtureWithNoTests), ResultState.Success); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void ConstructFromStaticTypeWithoutTestFixtureAttribute() - { - CanConstructFrom(typeof(StaticFixtureWithoutTestFixtureAttribute)); - } - - [Test] - public void CanRunStaticFixture() - { - TestAssert.IsRunnable(typeof(StaticFixtureWithoutTestFixtureAttribute), ResultState.Success); - } - -#if !NETCF - [Test, Platform(Exclude = "NETCF", Reason = "NYI")] - public void CanRunGenericFixtureWithProperArgsProvided() - { - TestSuite suite = TestBuilder.MakeFixture( - typeof(NUnit.TestData.TestFixtureData.GenericFixtureWithProperArgsProvided<>)); - Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable)); - Assert.That(suite is ParameterizedFixtureSuite); - Assert.That(suite.Tests.Count, Is.EqualTo(2)); - } - -// [Test] -// public void CannotRunGenericFixtureWithNoTestFixtureAttribute() -// { -// TestSuite suite = TestBuilder.MakeFixture( -// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoTestFixtureAttribute`1")); -// -// Assert.That(suite.RunState, Is.EqualTo(RunState.NotRunnable)); -// Assert.That(suite.Properties.Get(PropertyNames.SkipReason), -// Is.StringStarting("Fixture type contains generic parameters")); -// } - - [Test, Platform(Exclude = "NETCF", Reason = "NYI")] - public void CannotRunGenericFixtureWithNoArgsProvided() - { - TestSuite suite = TestBuilder.MakeFixture( - typeof(NUnit.TestData.TestFixtureData.GenericFixtureWithNoArgsProvided<>)); - - Test fixture = (Test)suite.Tests[0]; - Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable)); - Assert.That((string)fixture.Properties.Get(PropertyNames.SkipReason), Is.StringStarting("Fixture type contains generic parameters")); - } - - [Test, Platform(Exclude = "NETCF", Reason = "NYI")] - public void CannotRunGenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided() - { - TestSuite suite = TestBuilder.MakeFixture( - typeof(NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<>)); - TestAssert.IsNotRunnable((Test)suite.Tests[0]); - } - - [Test, Platform(Exclude = "NETCF", Reason = "NYI")] - public void CanRunGenericFixtureDerivedFromAbstractFixtureWithArgsProvided() - { - TestSuite suite = TestBuilder.MakeFixture( - typeof(NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<>)); - Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable)); - Assert.That(suite is ParameterizedFixtureSuite); - Assert.That(suite.Tests.Count, Is.EqualTo(2)); - } -#endif -#endif - - #region SetUp Signature - [Test] - public void CannotRunPrivateSetUp() - { - TestAssert.IsNotRunnable(typeof(PrivateSetUp)); - } - -#if !SILVERLIGHT - [Test] - public void CanRunProtectedSetUp() - { - TestAssert.IsRunnable(typeof(ProtectedSetUp), ResultState.Success); - } -#endif - - /// - /// Determines whether this instance [can run static set up]. - /// - [Test] - public void CanRunStaticSetUp() - { - TestAssert.IsRunnable(typeof(StaticSetUp), ResultState.Success); - } - - [Test] - public void CannotRunSetupWithReturnValue() - { - TestAssert.IsNotRunnable(typeof(SetUpWithReturnValue)); - } - - [Test] - public void CannotRunSetupWithParameters() - { - TestAssert.IsNotRunnable(typeof(SetUpWithParameters)); - } - #endregion - - #region TearDown Signature - [Test] - public void CannotRunPrivateTearDown() - { - TestAssert.IsNotRunnable(typeof(PrivateTearDown)); - } - -#if !SILVERLIGHT - [Test] - public void CanRunProtectedTearDown() - { - TestAssert.IsRunnable(typeof(ProtectedTearDown), ResultState.Success); - } -#endif - - [Test] - public void CanRunStaticTearDown() - { - TestAssert.IsRunnable(typeof(StaticTearDown), ResultState.Success); - } - - [Test] - public void CannotRunTearDownWithReturnValue() - { - TestAssert.IsNotRunnable(typeof(TearDownWithReturnValue)); - } - - [Test] - public void CannotRunTearDownWithParameters() - { - TestAssert.IsNotRunnable(typeof(TearDownWithParameters)); - } - #endregion - - #region TestFixtureSetUp Signature - [Test] - public void CannotRunPrivateFixtureSetUp() - { - TestAssert.IsNotRunnable(typeof(PrivateFixtureSetUp)); - } - -#if !SILVERLIGHT - [Test] - public void CanRunProtectedFixtureSetUp() - { - TestAssert.IsRunnable(typeof(ProtectedFixtureSetUp), ResultState.Success); - } -#endif - - [Test] - public void CanRunStaticFixtureSetUp() - { - TestAssert.IsRunnable(typeof(StaticFixtureSetUp), ResultState.Success); - } - - [Test] - public void CannotRunFixtureSetupWithReturnValue() - { - TestAssert.IsNotRunnable(typeof(FixtureSetUpWithReturnValue)); - } - - [Test] - public void CannotRunFixtureSetupWithParameters() - { - TestAssert.IsNotRunnable(typeof(FixtureSetUpWithParameters)); - } - #endregion - - #region TestFixtureTearDown Signature - - [Test] - public void CannotRunPrivateFixtureTearDown() - { - TestAssert.IsNotRunnable(typeof(PrivateFixtureTearDown)); - } - -#if !SILVERLIGHT - [Test] - public void CanRunProtectedFixtureTearDown() - { - TestAssert.IsRunnable(typeof(ProtectedFixtureTearDown), ResultState.Success); - } -#endif - - [Test] - public void CanRunStaticFixtureTearDown() - { - TestAssert.IsRunnable(typeof(StaticFixtureTearDown), ResultState.Success); - } - -// [TestFixture] -// [Category("fixture category")] -// [Category("second")] -// private class HasCategories -// { -// [Test] public void OneTest() -// {} -// } -// -// [Test] -// public void LoadCategories() -// { -// TestSuite fixture = LoadFixture("NUnit.Core.Tests.TestFixtureBuilderTests+HasCategories"); -// Assert.IsNotNull(fixture); -// Assert.AreEqual(2, fixture.Categories.Count); -// } - - [Test] - public void CannotRunFixtureTearDownWithReturnValue() - { - TestAssert.IsNotRunnable(typeof(FixtureTearDownWithReturnValue)); - } - - [Test] - public void CannotRunFixtureTearDownWithParameters() - { - TestAssert.IsNotRunnable(typeof(FixtureTearDownWithParameters)); - } - #endregion - } -} diff --git a/test/NUnitLite/src/tests/Internal/TestMethodSignatureTests.cs b/test/NUnitLite/src/tests/Internal/TestMethodSignatureTests.cs deleted file mode 100644 index 125f4beb9..000000000 --- a/test/NUnitLite/src/tests/Internal/TestMethodSignatureTests.cs +++ /dev/null @@ -1,198 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.Framework.Api; -using NUnit.TestData.TestMethodSignatureFixture; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class TestMethodSignatureTests - { - private static Type fixtureType = typeof(TestMethodSignatureFixture); - - [Test] - public void InstanceTestMethodIsRunnable() - { - TestAssert.IsRunnable(fixtureType, "InstanceTestMethod", ResultState.Success); - } - - [Test] - public void StaticTestMethodIsRunnable() - { - TestAssert.IsRunnable(fixtureType, "StaticTestMethod", ResultState.Success); - } - - [Test] - public void TestMethodWithoutParametersWithArgumentsProvidedIsNotRunnable() - { - TestAssert.FirstChildIsNotRunnable(fixtureType, "TestMethodWithoutParametersWithArgumentsProvided"); - } - - [Test] - public void TestMethodWithArgumentsNotProvidedIsNotRunnable() - { - TestAssert.IsNotRunnable(fixtureType, "TestMethodWithArgumentsNotProvided"); - } - - [Test] - public void TestMethodWithArgumentsProvidedIsRunnable() - { - TestAssert.IsRunnable(fixtureType, "TestMethodWithArgumentsProvided", ResultState.Success); - } - - [Test] - public void TestMethodWithWrongNumberOfArgumentsProvidedIsNotRunnable() - { - TestAssert.FirstChildIsNotRunnable(fixtureType, "TestMethodWithWrongNumberOfArgumentsProvided"); - } - - [Test] - public void TestMethodWithWrongArgumentTypesProvidedGivesError() - { - TestAssert.IsRunnable(fixtureType, "TestMethodWithWrongArgumentTypesProvided", ResultState.Error); - } - - [Test] - public void StaticTestMethodWithArgumentsNotProvidedIsNotRunnable() - { - TestAssert.IsNotRunnable(fixtureType, "StaticTestMethodWithArgumentsNotProvided"); - } - - [Test] - public void StaticTestMethodWithArgumentsProvidedIsRunnable() - { - TestAssert.IsRunnable(fixtureType, "StaticTestMethodWithArgumentsProvided", ResultState.Success); - } - - [Test] - public void StaticTestMethodWithWrongNumberOfArgumentsProvidedIsNotRunnable() - { - TestAssert.FirstChildIsNotRunnable(fixtureType, "StaticTestMethodWithWrongNumberOfArgumentsProvided"); - } - - [Test] - public void StaticTestMethodWithWrongArgumentTypesProvidedGivesError() - { - TestAssert.IsRunnable(fixtureType, "StaticTestMethodWithWrongArgumentTypesProvided", ResultState.Error); - } - - [Test] - public void TestMethodWithConvertibleArgumentsIsRunnable() - { - TestAssert.IsRunnable(fixtureType, "TestMethodWithConvertibleArguments", ResultState.Success); - } - - [Test] - public void TestMethodWithNonConvertibleArgumentsGivesError() - { - TestAssert.IsRunnable(fixtureType, "TestMethodWithNonConvertibleArguments", ResultState.Error); - } - - [Test] - public void ProtectedTestMethodIsNotRunnable() - { - TestAssert.IsNotRunnable( fixtureType, "ProtectedTestMethod" ); - } - - [Test] - public void PrivateTestMethodIsNotRunnable() - { - TestAssert.IsNotRunnable( fixtureType, "PrivateTestMethod" ); - } - - [Test] - public void TestMethodWithReturnTypeIsNotRunnable() - { - TestAssert.IsNotRunnable( fixtureType, "TestMethodWithReturnType" ); - } - - [Test] - public void TestMethodWithMultipleTestCasesExecutesMultipleTimes() - { - ITestResult result = TestBuilder.RunTestCase(fixtureType, "TestMethodWithMultipleTestCases"); - - Assert.That( result.ResultState, Is.EqualTo(ResultState.Success) ); - ResultSummary summary = new ResultSummary(result); - Assert.That(summary.TestsRun, Is.EqualTo(3)); - } - - [Test] - public void TestMethodWithMultipleTestCasesUsesCorrectNames() - { - string name = "TestMethodWithMultipleTestCases"; - string fullName = typeof (TestMethodSignatureFixture).FullName + "." + name; - - TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(fixtureType, name); - Assert.That(suite.TestCaseCount, Is.EqualTo(3)); - - string[] names = new string[suite.Tests.Count]; - string[] fullNames = new string[suite.Tests.Count]; - - int index = 0; - foreach (Test test in suite.Tests) - { - names[index] = test.Name; - fullNames[index] = test.FullName; - index++; - } - - Assert.That(names, Has.Member(name + "(12,3,4)")); - Assert.That(names, Has.Member(name + "(12,2,6)")); - Assert.That(names, Has.Member(name + "(12,4,3)")); - - Assert.That(fullNames, Has.Member(fullName + "(12,3,4)")); - Assert.That(fullNames, Has.Member(fullName + "(12,2,6)")); - Assert.That(fullNames, Has.Member(fullName + "(12,4,3)")); - } - - [Test] - public void RunningTestsThroughFixtureGivesCorrectResults() - { - ITestResult result = TestBuilder.RunTestFixture(fixtureType); - ResultSummary summary = new ResultSummary(result); - - Assert.That( - summary.ResultCount, - Is.EqualTo(TestMethodSignatureFixture.Tests)); - Assert.That( - summary.TestsRun, - Is.EqualTo(TestMethodSignatureFixture.Runnable)); - //Assert.That( - // summary.NotRunnable, - // Is.EqualTo(TestMethodSignatureFixture.NotRunnable)); - //Assert.That( - // summary.Errors, - // Is.EqualTo(TestMethodSignatureFixture.Errors)); - Assert.That( - summary.Failures, - Is.EqualTo(TestMethodSignatureFixture.Failures + TestMethodSignatureFixture.Errors)); - Assert.That( - summary.TestsNotRun, - Is.EqualTo(TestMethodSignatureFixture.NotRunnable)); - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/TestResultTests.cs b/test/NUnitLite/src/tests/Internal/TestResultTests.cs deleted file mode 100644 index 2fd51067b..000000000 --- a/test/NUnitLite/src/tests/Internal/TestResultTests.cs +++ /dev/null @@ -1,683 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2010 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System.IO; -using System.Text; -using NUnit.Framework.Api; -using NUnit.TestUtilities; -using System; - -namespace NUnit.Framework.Internal -{ - /// - /// Summary description for TestResultTests. - /// - [TestFixture] - public abstract class TestResultTests - { - protected TestResult testResult; - protected TestResult suiteResult; - protected TestMethod test; - - protected string ignoredChildMessage = "One or more child tests were ignored"; - protected string failingChildMessage = "One or more child tests had errors"; - - [SetUp] - public void SetUp() - { - TestSuite suite = new TestSuite(typeof(DummySuite)); - suite.Properties.Set(PropertyNames.Description, "Suite description"); - suite.Properties.Add(PropertyNames.Category, "Fast"); - suite.Properties.Add("Value", 3); - suiteResult = suite.MakeTestResult(); - - test = new TestMethod(typeof(DummySuite).GetMethod("DummyMethod"), suite); - test.Properties.Set(PropertyNames.Description, "Test description"); - test.Properties.Add(PropertyNames.Category, "Dubious"); - test.Properties.Set("Priority", "low"); - testResult = test.MakeTestResult(); - - SimulateTestRun(); - } - - [Test] - public void TestResultBasicInfo() - { - Assert.AreEqual("DummyMethod", testResult.Name); - Assert.AreEqual("NUnit.Framework.Internal.TestResultTests+DummySuite.DummyMethod", testResult.FullName); - } - - [Test] - public void SuiteResultBasicInfo() - { - Assert.AreEqual("TestResultTests+DummySuite", suiteResult.Name); - Assert.AreEqual("NUnit.Framework.Internal.TestResultTests+DummySuite", suiteResult.FullName); - } - - [Test] - public void TestResultBasicInfo_XmlNode() - { - XmlNode testNode = testResult.ToXml(true); - - //Assert.True(testNode is XmlElement); - Assert.NotNull(testNode.Attributes["id"]); - Assert.AreEqual("test-case", testNode.Name); - Assert.AreEqual("DummyMethod", testNode.Attributes["name"]); - Assert.AreEqual("NUnit.Framework.Internal.TestResultTests+DummySuite.DummyMethod", testNode.Attributes["fullname"]); - - Assert.AreEqual("Test description", testNode.FindDescendant("properties/property[@name='Description']").Attributes["value"]); - Assert.AreEqual("Dubious", testNode.FindDescendant("properties/property[@name='Category']").Attributes["value"]); - Assert.AreEqual("low", testNode.FindDescendant("properties/property[@name='Priority']").Attributes["value"]); - - Assert.AreEqual(0, testNode.FindDescendants("test-case").Count); - } - - [Test] - public void TestResultBasicInfo_WriteXml() - { - XmlNode testNode = testResult.ToXml(true); - - string expected = GenerateExpectedXml(testResult); - - StringBuilder actual = new StringBuilder(); - StringWriter sw = new StringWriter(actual); -#if CLR_2_0 || CLR_4_0 - System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); - settings.CloseOutput = true; - settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment; - System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings); -#else - System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw); -#endif - testNode.WriteTo(writer); - writer.Close(); - - Assert.That(actual.ToString(), Is.EqualTo(expected)); - } - - [Test] - public void SuiteResultBasicInfo_XmlNode() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - //Assert.True(suiteNode is XmlElement); - Assert.NotNull(suiteNode.Attributes["id"]); - Assert.AreEqual("test-suite", suiteNode.Name); - Assert.AreEqual("TestResultTests+DummySuite", suiteNode.Attributes["name"]); - Assert.AreEqual("NUnit.Framework.Internal.TestResultTests+DummySuite", suiteNode.Attributes["fullname"]); - - Assert.AreEqual("Suite description", suiteNode.FindDescendant("properties/property[@name='Description']").Attributes["value"]); - Assert.AreEqual("Fast", suiteNode.FindDescendant("properties/property[@name='Category']").Attributes["value"]); - Assert.AreEqual("3", suiteNode.FindDescendant("properties/property[@name='Value']").Attributes["value"]); - } - - [Test] - public void SuiteResultBasicInfo_WriteXml() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - string expected = GenerateExpectedXml(suiteResult); - - StringBuilder actual = new StringBuilder(); - StringWriter sw = new StringWriter(actual); -#if CLR_2_0 || CLR_4_0 - System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); - settings.CloseOutput = true; - settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment; - System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings); -#else - System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(sw); -#endif - suiteNode.WriteTo(writer); - writer.Close(); - - Assert.That(actual.ToString(), Is.EqualTo(expected)); - } - - protected abstract void SimulateTestRun(); - - private static string GenerateExpectedXml(TestResult result) - { - StringBuilder expected = new StringBuilder(); - TestSuiteResult suiteResult = result as TestSuiteResult; - - if(suiteResult != null) - expected.Append(""); - - if (result.Test.Properties.Count > 0) - { - expected.Append(""); - foreach (string key in result.Test.Properties.Keys) - foreach (object value in result.Test.Properties[key]) - expected.Append(""); - expected.Append(""); - } - - if (result.ResultState.Status == TestStatus.Failed) - { - expected.Append(""); - if (result.Message != null) - expected.Append("" + Escape(result.Message) + ""); - - if (result.StackTrace != null) - expected.Append("" + Escape(result.StackTrace) + ""); - - expected.Append(""); - } - else if (result.Message != null) - { - expected.Append("" + Escape(result.Message) + ""); - } - - if (suiteResult != null) - { - foreach (TestResult childResult in suiteResult.Children) - expected.Append(GenerateExpectedXml(childResult)); - - expected.Append(""); - } - else - expected.Append(""); - - return expected.ToString(); - } - - private static string Quoted(object o) - { - return "\"" + o.ToString() + "\""; - } - - private static string Escape(string s) - { - return s - .Replace("&", "&") - .Replace(">", ">") - .Replace("<", "<") - .Replace("\"", """) - .Replace("'", "'"); - } - - public class DummySuite - { - public void DummyMethod() { } - } - } - - public class DefaultResultTests : TestResultTests - { - protected override void SimulateTestRun() - { - suiteResult.AddResult(testResult); - } - - [Test] - public void TestResultIsInconclusive() - { - Assert.AreEqual(ResultState.Inconclusive, testResult.ResultState); - Assert.AreEqual(TestStatus.Inconclusive, testResult.ResultState.Status); - Assert.That(testResult.ResultState.Label, Is.Empty); - Assert.That(testResult.Duration, Is.EqualTo(TimeSpan.Zero)); - } - - [Test] - public void SuiteResultIsInconclusive() - { - Assert.AreEqual(ResultState.Inconclusive, suiteResult.ResultState); - Assert.AreEqual(0, suiteResult.AssertCount); - } - - [Test] - public void TestResultXmlNodeIsInconclusive() - { - XmlNode testNode = testResult.ToXml(true); - - Assert.AreEqual("Inconclusive", testNode.Attributes["result"]); - } - - [Test] - public void SuiteResultXmlNodeIsInconclusive() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual("Inconclusive", suiteNode.Attributes["result"]); - Assert.AreEqual("0", suiteNode.Attributes["passed"]); - Assert.AreEqual("0", suiteNode.Attributes["failed"]); - Assert.AreEqual("0", suiteNode.Attributes["skipped"]); - Assert.AreEqual("1", suiteNode.Attributes["inconclusive"]); - Assert.AreEqual("0", suiteNode.Attributes["asserts"]); - } - - [Test] - public void SuiteResultXmlNodeHasOneChildTest() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual(1, suiteNode.FindDescendants("test-case").Count); - } - } - - public class SuccessResultTests : TestResultTests - { - protected override void SimulateTestRun() - { - testResult.SetResult(ResultState.Success, "Test passed!"); - testResult.Duration = TimeSpan.FromSeconds(0.125); - suiteResult.Duration = TimeSpan.FromSeconds(0.125); - testResult.AssertCount = 2; - suiteResult.AddResult(testResult); - } - - [Test] - public void TestResultIsSuccess() - { - Assert.True(testResult.ResultState == ResultState.Success); - Assert.AreEqual(TestStatus.Passed, testResult.ResultState.Status); - Assert.That(testResult.ResultState.Label, Is.Empty); - Assert.AreEqual("Test passed!", testResult.Message); - Assert.That(testResult.Duration.TotalSeconds, Is.EqualTo(0.125)); - } - - [Test] - public void SuiteResultIsSuccess() - { - Assert.True(suiteResult.ResultState == ResultState.Success); - Assert.AreEqual(TestStatus.Passed, suiteResult.ResultState.Status); - Assert.That(suiteResult.ResultState.Label, Is.Empty); - - Assert.AreEqual(1, suiteResult.PassCount); - Assert.AreEqual(0, suiteResult.FailCount); - Assert.AreEqual(0, suiteResult.SkipCount); - Assert.AreEqual(0, suiteResult.InconclusiveCount); - Assert.AreEqual(2, suiteResult.AssertCount); - } - - [Test] - public void TestResultXmlNodeIsSuccess() - { - XmlNode testNode = testResult.ToXml(true); - - Assert.AreEqual("Passed", testNode.Attributes["result"]); - Assert.AreEqual("00:00:00.1250000", testNode.Attributes["time"]); - Assert.AreEqual("2", testNode.Attributes["asserts"]); - - XmlNode reason = testNode.FindDescendant("reason"); - Assert.NotNull(reason); - Assert.NotNull(reason.FindDescendant("message")); - Assert.AreEqual("Test passed!", reason.FindDescendant("message").TextContent); - Assert.AreEqual("Test passed!", reason.FindDescendant("message").EscapedTextContent); - Assert.Null(reason.FindDescendant("stack-trace")); - } - - [Test] - public void SuiteResultXmlNodeIsSuccess() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual("Passed", suiteNode.Attributes["result"]); - Assert.AreEqual("00:00:00.1250000", suiteNode.Attributes["time"]); - Assert.AreEqual("1", suiteNode.Attributes["passed"]); - Assert.AreEqual("0", suiteNode.Attributes["failed"]); - Assert.AreEqual("0", suiteNode.Attributes["skipped"]); - Assert.AreEqual("0", suiteNode.Attributes["inconclusive"]); - Assert.AreEqual("2", suiteNode.Attributes["asserts"]); - } - - [Test] - public void SuiteResultXmlNodeHasOneChildTest() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual(1, suiteNode.FindDescendants("test-case").Count); - } - } - - public class IgnoredResultTests : TestResultTests - { - protected override void SimulateTestRun() - { - testResult.SetResult(ResultState.Ignored, "because"); - suiteResult.AddResult(testResult); - } - - [Test] - public void TestResultIsIgnored() - { - Assert.AreEqual(ResultState.Ignored, testResult.ResultState); - Assert.AreEqual(TestStatus.Skipped, testResult.ResultState.Status); - Assert.AreEqual("Ignored", testResult.ResultState.Label); - Assert.AreEqual("because", testResult.Message); - } - - [Test] - public void SuiteResultIsIgnored() - { - Assert.AreEqual(ResultState.Ignored, suiteResult.ResultState); - Assert.AreEqual(TestStatus.Skipped, suiteResult.ResultState.Status); - Assert.AreEqual(ignoredChildMessage, suiteResult.Message); - - Assert.AreEqual(0, suiteResult.PassCount); - Assert.AreEqual(0, suiteResult.FailCount); - Assert.AreEqual(1, suiteResult.SkipCount); - Assert.AreEqual(0, suiteResult.InconclusiveCount); - Assert.AreEqual(0, suiteResult.AssertCount); - } - - [Test] - public void TestResultXmlNodeIsIgnored() - { - XmlNode testNode = testResult.ToXml(true); - - Assert.AreEqual("Skipped", testNode.Attributes["result"]); - Assert.AreEqual("Ignored", testNode.Attributes["label"]); - XmlNode reason = testNode.FindDescendant("reason"); - Assert.NotNull(reason); - Assert.NotNull(reason.FindDescendant("message")); - Assert.AreEqual("because", reason.FindDescendant("message").TextContent); - Assert.AreEqual("because", reason.FindDescendant("message").EscapedTextContent); - Assert.Null(reason.FindDescendant("stack-trace")); - } - - [Test] - public void SuiteResultXmlNodeIsIgnored() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual("Skipped", suiteNode.Attributes["result"]); - Assert.AreEqual("Ignored", suiteNode.Attributes["label"]); - Assert.AreEqual("0", suiteNode.Attributes["passed"]); - Assert.AreEqual("0", suiteNode.Attributes["failed"]); - Assert.AreEqual("1", suiteNode.Attributes["skipped"]); - Assert.AreEqual("0", suiteNode.Attributes["inconclusive"]); - Assert.AreEqual("0", suiteNode.Attributes["asserts"]); - } - - [Test] - public void SuiteResultXmlNodeHasOneChildTest() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual(1, suiteNode.FindDescendants("test-case").Count); - } - } - - public class FailedResultTests : TestResultTests - { - protected override void SimulateTestRun() - { - testResult.SetResult(ResultState.Failure, "message with & straight text", "stack trace"); - testResult.Duration = TimeSpan.FromSeconds(0.125); - suiteResult.Duration = TimeSpan.FromSeconds(0.125); - testResult.AssertCount = 3; - suiteResult.AddResult(testResult); - } - - [Test] - public void TestResultIsFailure() - { - Assert.AreEqual(ResultState.Failure, testResult.ResultState); - Assert.AreEqual(TestStatus.Failed, testResult.ResultState.Status); - Assert.AreEqual("message with & straight text", testResult.Message); - Assert.AreEqual("stack trace", testResult.StackTrace); - Assert.AreEqual(0.125, testResult.Duration.TotalSeconds); - } - - [Test] - public void SuiteResultIsFailure() - { - Assert.AreEqual(ResultState.Failure, suiteResult.ResultState); - Assert.AreEqual(TestStatus.Failed, suiteResult.ResultState.Status); - Assert.AreEqual(failingChildMessage, suiteResult.Message); - Assert.Null(suiteResult.StackTrace); - - Assert.AreEqual(0, suiteResult.PassCount); - Assert.AreEqual(1, suiteResult.FailCount); - Assert.AreEqual(0, suiteResult.SkipCount); - Assert.AreEqual(0, suiteResult.InconclusiveCount); - Assert.AreEqual(3, suiteResult.AssertCount); - } - - [Test] - public void TestResultXmlNodeIsFailure() - { - XmlNode testNode = testResult.ToXml(true); - - Assert.AreEqual("Failed", testNode.Attributes["result"]); - Assert.AreEqual("00:00:00.1250000", testNode.Attributes["time"]); - - XmlNode failureNode = testNode.FindDescendant("failure"); - Assert.NotNull(failureNode, "No element found"); - - XmlNode messageNode = failureNode.FindDescendant("message"); - Assert.NotNull(messageNode, "No element found"); - Assert.AreEqual("message with & straight text", messageNode.TextContent); - Assert.AreEqual("message with <xml> & straight text", messageNode.EscapedTextContent); - - XmlNode stacktraceNode = failureNode.FindDescendant("stack-trace"); - Assert.NotNull(stacktraceNode, "No element found"); - Assert.AreEqual("stack trace", stacktraceNode.TextContent); - Assert.AreEqual("stack trace", stacktraceNode.EscapedTextContent); - } - - [Test] - public void SuiteResultXmlNodeIsFailure() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual("Failed", suiteNode.Attributes["result"]); - Assert.AreEqual("00:00:00.1250000", suiteNode.Attributes["time"]); - - XmlNode failureNode = suiteNode.FindDescendant("failure"); - Assert.NotNull(failureNode, "No element found"); - - XmlNode messageNode = failureNode.FindDescendant("message"); - Assert.NotNull(messageNode, "No element found"); - Assert.AreEqual(failingChildMessage, messageNode.TextContent); - Assert.AreEqual(failingChildMessage, messageNode.EscapedTextContent); - - XmlNode stacktraceNode = failureNode.FindDescendant("stacktrace"); - Assert.Null(stacktraceNode, "Unexpected element found"); - - Assert.AreEqual("0", suiteNode.Attributes["passed"]); - Assert.AreEqual("1", suiteNode.Attributes["failed"]); - Assert.AreEqual("0", suiteNode.Attributes["skipped"]); - Assert.AreEqual("0", suiteNode.Attributes["inconclusive"]); - Assert.AreEqual("3", suiteNode.Attributes["asserts"]); - } - - [Test] - public void SuiteResultXmlNodeHasOneChildTest() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual(1, suiteNode.FindDescendants("test-case").Count); - } - } - - public class InconclusiveResultTests : TestResultTests - { - protected override void SimulateTestRun() - { - testResult.SetResult(ResultState.Inconclusive, "because"); - suiteResult.AddResult(testResult); - } - - [Test] - public void TestResultIsInconclusive() - { - Assert.AreEqual(ResultState.Inconclusive, testResult.ResultState); - Assert.AreEqual(TestStatus.Inconclusive, testResult.ResultState.Status); - Assert.That(testResult.ResultState.Label, Is.Empty); - Assert.AreEqual("because", testResult.Message); - } - - [Test] - public void SuiteResultIsInconclusive() - { - Assert.AreEqual(ResultState.Inconclusive, suiteResult.ResultState); - Assert.AreEqual(TestStatus.Inconclusive, suiteResult.ResultState.Status); - Assert.Null(suiteResult.Message); - - Assert.AreEqual(0, suiteResult.PassCount); - Assert.AreEqual(0, suiteResult.FailCount); - Assert.AreEqual(0, suiteResult.SkipCount); - Assert.AreEqual(1, suiteResult.InconclusiveCount); - Assert.AreEqual(0, suiteResult.AssertCount); - } - - [Test] - public void TestResultXmlNodeIsInconclusive() - { - XmlNode testNode = testResult.ToXml(true); - - Assert.AreEqual("Inconclusive", testNode.Attributes["result"]); - Assert.That(!testNode.Attributes.ContainsKey("label"), "Unexpected attribute 'label' found"); - XmlNode reason = testNode.FindDescendant("reason"); - Assert.NotNull(reason); - Assert.NotNull(reason.FindDescendant("message")); - Assert.AreEqual("because", reason.FindDescendant("message").TextContent); - Assert.AreEqual("because", reason.FindDescendant("message").EscapedTextContent); - Assert.Null(reason.FindDescendant("stack-trace")); - } - - [Test] - public void SuiteResultXmlNodeIsInconclusive() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual("Inconclusive", suiteNode.Attributes["result"]); - Assert.That(!suiteNode.Attributes.ContainsKey("label"), "Unexpected 'label' attribute found"); - Assert.AreEqual("0", suiteNode.Attributes["passed"]); - Assert.AreEqual("0", suiteNode.Attributes["failed"]); - Assert.AreEqual("0", suiteNode.Attributes["skipped"]); - Assert.AreEqual("1", suiteNode.Attributes["inconclusive"]); - Assert.AreEqual("0", suiteNode.Attributes["asserts"]); - } - - [Test] - public void SuiteResultXmlNodeHasOneChildTest() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual(1, suiteNode.FindDescendants("test-case").Count); - } - } - - public class MixedResultTests : TestResultTests - { - protected override void SimulateTestRun() - { - testResult.SetResult(ResultState.Success); - testResult.AssertCount = 2; - suiteResult.AddResult(testResult); - - testResult.SetResult(ResultState.Failure, "message", "stack trace"); - testResult.AssertCount = 1; - suiteResult.AddResult(testResult); - - testResult.SetResult(ResultState.Success); - testResult.AssertCount = 3; - suiteResult.AddResult(testResult); - - testResult.SetResult(ResultState.Inconclusive, "inconclusive reason", "stacktrace"); - testResult.AssertCount = 0; - suiteResult.AddResult(testResult); - } - - [Test] - public void SuiteResultIsFailure() - { - Assert.AreEqual(ResultState.Failure, suiteResult.ResultState); - Assert.AreEqual(TestStatus.Failed, suiteResult.ResultState.Status); - Assert.AreEqual(failingChildMessage, suiteResult.Message); - Assert.Null(suiteResult.StackTrace, "There should be no stacktrace"); - - Assert.AreEqual(2, suiteResult.PassCount); - Assert.AreEqual(1, suiteResult.FailCount); - Assert.AreEqual(0, suiteResult.SkipCount); - Assert.AreEqual(1, suiteResult.InconclusiveCount); - Assert.AreEqual(6, suiteResult.AssertCount); - } - - [Test] - public void SuiteResultXmlNodeIsFailure() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual("Failed", suiteNode.Attributes["result"]); - XmlNode failureNode = suiteNode.FindDescendant("failure"); - Assert.NotNull(failureNode, "No failure element found"); - - XmlNode messageNode = failureNode.FindDescendant("message"); - Assert.NotNull(messageNode, "No message element found"); - Assert.AreEqual(failingChildMessage, messageNode.TextContent); - Assert.AreEqual(failingChildMessage, messageNode.EscapedTextContent); - - XmlNode stacktraceNode = failureNode.FindDescendant("stacktrace"); - Assert.Null(stacktraceNode, "There should be no stacktrace"); - - Assert.AreEqual("2", suiteNode.Attributes["passed"]); - Assert.AreEqual("1", suiteNode.Attributes["failed"]); - Assert.AreEqual("0", suiteNode.Attributes["skipped"]); - Assert.AreEqual("1", suiteNode.Attributes["inconclusive"]); - Assert.AreEqual("6", suiteNode.Attributes["asserts"]); - } - - [Test] - public void SuiteResultXmlNodeHasFourChildTests() - { - XmlNode suiteNode = suiteResult.ToXml(true); - - Assert.AreEqual(4, suiteNode.FindDescendants("test-case").Count); - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/TestXmlTests.cs b/test/NUnitLite/src/tests/Internal/TestXmlTests.cs deleted file mode 100644 index 8b042f4eb..000000000 --- a/test/NUnitLite/src/tests/Internal/TestXmlTests.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System; -using NUnit.Framework.Api; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class TestXmlTests - { - private TestSuite testSuite; - private TestFixture testFixture; - private TestMethod testMethod; - - [SetUp] - public void SetUp() - { - testFixture = new TestFixture(typeof(DummyFixture)); - testFixture.Properties.Set(PropertyNames.Description, "Fixture description"); - testFixture.Properties.Add(PropertyNames.Category, "Fast"); - testFixture.Properties.Add("Value", 3); - - testMethod = new TestMethod(typeof(DummyFixture).GetMethod("DummyMethod"), testFixture); - testMethod.Properties.Set(PropertyNames.Description, "Test description"); - testMethod.Properties.Add(PropertyNames.Category, "Dubious"); - testMethod.Properties.Set("Priority", "low"); - - testFixture.Tests.Add(testMethod); - - testSuite = new TestSuite(typeof(DummyFixture)); - testSuite.Properties.Set(PropertyNames.Description, "Suite description"); - } - - [Test] - public void TestTypeTests() - { - Assert.That(testMethod.TestType, - Is.EqualTo("TestMethod")); - Assert.That(testFixture.TestType, - Is.EqualTo("TestFixture")); - Assert.That(testSuite.TestType, - Is.EqualTo("TestSuite")); - Assert.That(new TestAssembly(System.Reflection.Assembly.GetExecutingAssembly(), "junk").TestType, - Is.EqualTo("Assembly")); - Assert.That(new ParameterizedMethodSuite(typeof(DummyFixture).GetMethod("ParameterizedMethod")).TestType, - Is.EqualTo("ParameterizedMethod")); - Assert.That(new ParameterizedFixtureSuite(typeof(DummyFixture)).TestType, - Is.EqualTo("ParameterizedFixture")); -#if CLR_2_0 || CLR_4_0 - Assert.That(new ParameterizedMethodSuite(typeof(DummyFixture).GetMethod("GenericMethod")).TestType, - Is.EqualTo("GenericMethod")); - Type genericType = typeof(DummyGenericFixture).GetGenericTypeDefinition(); - Assert.That(new ParameterizedFixtureSuite(genericType).TestType, - Is.EqualTo("GenericFixture")); -#endif - } - - [Test] - public void TestMethodToXml() - { - CheckXmlForTest(testMethod, false); - } - - [Test] - public void TestFixtureToXml() - { - CheckXmlForTest(testFixture, false); - } - - [Test] - public void TestFixtureToXml_Recursive() - { - CheckXmlForTest(testFixture, true); - } - - [Test] - public void TestSuiteToXml() - { - CheckXmlForTest(testSuite, false); - } - - [Test] - public void TestSuiteToXml_Recursive() - { - CheckXmlForTest(testSuite, true); - } - - #region Helper Methods For Checking XML - - private void CheckXmlForTest(Test test, bool recursive) - { - XmlNode topNode = test.ToXml(true); - CheckXmlForTest(test, topNode, recursive); - } - - private void CheckXmlForTest(Test test, XmlNode topNode, bool recursive) - { - Assert.NotNull(topNode); - - //if (test is TestSuite) - //{ - // Assert.That(topNode.Name, Is.EqualTo("test-suite")); - // Assert.That(topNode.Attributes["type"].Value, Is.EqualTo(test.XmlElementName)); - //} - //else - //{ - // Assert.That(topNode.Name, Is.EqualTo("test-case")); - //} - - Assert.That(topNode.Name, Is.EqualTo(test.XmlElementName)); - Assert.That(topNode.Attributes["id"], Is.EqualTo(test.Id.ToString())); - Assert.That(topNode.Attributes["name"], Is.EqualTo(test.Name)); - Assert.That(topNode.Attributes["fullname"], Is.EqualTo(test.FullName)); - - int expectedCount = test.Properties.Count; - if (expectedCount > 0) - { - string[] expectedProps = new string[expectedCount]; - int count = 0; - foreach (PropertyEntry entry in test.Properties) - expectedProps[count++] = entry.ToString(); - - XmlNode propsNode = topNode.FindDescendant("properties"); - Assert.NotNull(propsNode); - - int actualCount = propsNode.ChildNodes.Count; - string[] actualProps = new string[actualCount]; - for (int i = 0; i < actualCount; i++) - { - XmlNode node = propsNode.ChildNodes[i] as XmlNode; - string name = node.Attributes["name"]; - string value = node.Attributes["value"]; - actualProps[i] = name + "=" + value.ToString(); - } - - Assert.That(actualProps, Is.EquivalentTo(expectedProps)); - } - - if (recursive) - { - TestSuite suite = test as TestSuite; - if (suite != null) - { - foreach (Test child in suite.Tests) - { - string xpathQuery = string.Format("{0}[@id={1}]", child.XmlElementName, child.Id); - XmlNode childNode = topNode.FindDescendant(xpathQuery); - Assert.NotNull(childNode, "Expected node for test with ID={0}, Name={1}", child.Id, child.Name); - - CheckXmlForTest(child, childNode, recursive); - } - } - } - } - - #endregion - - public class DummyFixture - { - public void DummyMethod() { } - public void ParameterizedMethod(int x) { } -#if CLR_2_0 || CLR_4_0 - public void GenericMethod(T x) { } -#endif - } - -#if CLR_2_0 || CLR_4_0 - public class DummyGenericFixture - { - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Internal/TextMessageWriterTests.cs b/test/NUnitLite/src/tests/Internal/TextMessageWriterTests.cs deleted file mode 100644 index 993eb7408..000000000 --- a/test/NUnitLite/src/tests/Internal/TextMessageWriterTests.cs +++ /dev/null @@ -1,164 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Threading; -using System.Globalization; - -namespace NUnit.Framework.Internal -{ - [TestFixture] - public class TextMessageWriterTests : AssertionHelper - { - private static readonly string NL = NUnit.Env.NewLine; - - private TextMessageWriter writer; - - [SetUp] - public void SetUp() - { - writer = new TextMessageWriter(); - } - - [Test] - public void ConnectorIsWrittenWithSurroundingSpaces() - { - writer.WriteConnector("and"); - Expect(writer.ToString(), EqualTo(" and ")); - } - - [Test] - public void PredicateIsWrittenWithTrailingSpace() - { - writer.WritePredicate("contains"); - Expect(writer.ToString(), EqualTo("contains ")); - } - - [Test] - public void IntegerIsWrittenAsIs() - { - writer.WriteValue(42); - Expect(writer.ToString(), EqualTo("42")); - } - - [Test] - public void StringIsWrittenWithQuotes() - { - writer.WriteValue("Hello"); - Expect(writer.ToString(), EqualTo("\"Hello\"")); - } - - // This test currently fails because control character replacement is - // done at a higher level... - // TODO: See if we should do it at a lower level -// [Test] -// public void ControlCharactersInStringsAreEscaped() -// { -// WriteValue("Best Wishes,\r\n\tCharlie\r\n"); -// Assert.That(writer.ToString(), Is.EqualTo("\"Best Wishes,\\r\\n\\tCharlie\\r\\n\"")); -// } - - [Test] - public void FloatIsWrittenWithTrailingF() - { - writer.WriteValue(0.5f); - Expect(writer.ToString(), EqualTo("0.5f")); - } - - [Test] - public void FloatIsWrittenToNineDigits() - { - writer.WriteValue(0.33333333333333f); - int digits = writer.ToString().Length - 3; // 0.dddddddddf - Expect(digits, EqualTo(9)); - Expect(writer.ToString().Length, EqualTo(12)); - } - - [Test] - public void DoubleIsWrittenWithTrailingD() - { - writer.WriteValue(0.5d); - Expect(writer.ToString(), EqualTo("0.5d")); - } - - [Test] - public void DoubleIsWrittenToSeventeenDigits() - { - writer.WriteValue(0.33333333333333333333333333333333333333333333d); - Expect(writer.ToString().Length, EqualTo(20)); // add 3 for leading 0, decimal and trailing d - } - - [Test] - public void DecimalIsWrittenWithTrailingM() - { - writer.WriteValue(0.5m); - Expect(writer.ToString(), EqualTo("0.5m")); - } - - [Test] - public void DecimalIsWrittenToTwentyNineDigits() - { - writer.WriteValue(12345678901234567890123456789m); - Expect(writer.ToString(), EqualTo("12345678901234567890123456789m")); - } - - [Test] - public void DateTimeTest() - { - writer.WriteValue(new DateTime(2007, 7, 4, 9, 15, 30, 123)); - Expect(writer.ToString(), EqualTo("2007-07-04 09:15:30.123")); - } - - [Test] - public void DisplayStringDifferences() - { - string s72 = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - string exp = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXY..."; - - writer.DisplayStringDifferences(s72, "abcde", 5, false, true); - string message = writer.ToString(); - Expect(message, EqualTo( - TextMessageWriter.Pfx_Expected + Q(exp) + NL + - TextMessageWriter.Pfx_Actual + Q("abcde") + NL + - " ----------------^" + NL)); - } - - [Test] - public void DisplayStringDifferences_NoClipping() - { - string s72 = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - - writer.DisplayStringDifferences(s72, "abcde", 5, false, false); - string message = writer.ToString(); - Expect(message, EqualTo( - TextMessageWriter.Pfx_Expected + Q(s72) + NL + - TextMessageWriter.Pfx_Actual + Q("abcde") + NL + - " ----------------^" + NL)); - } - - private string Q(string s) - { - return "\"" + s + "\""; - } - } -} diff --git a/test/NUnitLite/src/tests/Internal/TypeParameterUsedWithTestMethod.cs b/test/NUnitLite/src/tests/Internal/TypeParameterUsedWithTestMethod.cs deleted file mode 100644 index baf7c3d63..000000000 --- a/test/NUnitLite/src/tests/Internal/TypeParameterUsedWithTestMethod.cs +++ /dev/null @@ -1,41 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -#if CLR_2_0 || CLR_4_0 -using System; - -namespace NUnit.Framework.Internal -{ - [Category("Generics")] - [TestFixture(typeof(double))] - public class TypeParameterUsedWithTestMethod - { - [TestCase(5)] - [TestCase(1.23)] - public void TestMyArgType(T x) - { - Assert.That(x, Is.TypeOf(typeof(T))); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/Program.cs b/test/NUnitLite/src/tests/Program.cs deleted file mode 100644 index 22c28a038..000000000 --- a/test/NUnitLite/src/tests/Program.cs +++ /dev/null @@ -1,81 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; -using NUnitLite.Runner; -using NUnit.Framework.Internal; - -namespace NUnitLite.Tests -{ - public class Program - { - // The main program executes the tests. Output may be routed to - // various locations, depending on the arguments passed. - // - // Arguments: - // - // Arguments may be names of assemblies or options prefixed with '/' - // or '-'. Normally, no assemblies are passed and the calling - // assembly (the one containing this Main) is used. The following - // options are accepted: - // - // -test: Provides the name of a test to be exected. - // May be repeated. If this option is not used, - // all tests are run. - // - // -out:PATH Path to a file to which output is written. - // If omitted, Console is used, which means the - // output is lost on a platform with no Console. - // - // -full Print full report of all tests. - // - // -result:PATH Path to a file to which the XML test result is written. - // - // -explore[:Path] If specified, list tests rather than executing them. If a - // path is given, an XML file representing the tests is written - // to that location. If not, output is written to tests.xml. - // - // -noheader,noh Suppress display of the initial message. - // - // -wait Wait for a keypress before exiting. - // - // -include:categorylist - // If specified, nunitlite will only run the tests with a category - // that is in the comma separated list of category names. - // Example usage: -include:category1,category2 this command can be used - // in combination with the -exclude option also note that exlude takes priority - // over all includes. - // - // -exclude:categorylist - // If specified, nunitlite will not run any of the tests with a category - // that is in the comma separated list of category names. - // Example usage: -exclude:category1,category2 this command can be used - // in combination with the -include option also note that exclude takes priority - // over all includes - public static void Main(string[] args) - { - new TextUI().Execute(args); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/RecordingTestListener.cs b/test/NUnitLite/src/tests/RecordingTestListener.cs deleted file mode 100644 index 63e2f27ca..000000000 --- a/test/NUnitLite/src/tests/RecordingTestListener.cs +++ /dev/null @@ -1,29 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Api; - -namespace NUnitLite.Tests -{ - public class RecordingTestListener : ITestListener - { - public string Events = string.Empty; - - public void TestStarted(ITest test) - { - Events += string.Format("<{0}:", test.Name); - } - - public void TestFinished(ITestResult result) - { - Events += string.Format(":{0}>", result.ResultState); - } - - public void TestOutput(TestOutput output) { } - } -} diff --git a/test/NUnitLite/src/tests/Runner/CommandLineOptionTests.cs b/test/NUnitLite/src/tests/Runner/CommandLineOptionTests.cs deleted file mode 100644 index f8f037c3e..000000000 --- a/test/NUnitLite/src/tests/Runner/CommandLineOptionTests.cs +++ /dev/null @@ -1,275 +0,0 @@ -// ***************************************************** -// Copyright 2007, Charlie Poole -// -// Licensed under the Open Software License version 3.0 -// ***************************************************** - -using System; -using System.IO; -using NUnit.Framework; -using Env = NUnit.Env; - -namespace NUnitLite.Runner.Tests -{ - [TestFixture] - class CommandLineOptionTests - { - private CommandLineOptions options; - - [SetUp] - public void CreateOptions() - { - options = new CommandLineOptions("-"); - } - - [Test] - public void TestWaitOption() - { - options.Parse( "-wait" ); - Assert.That(options.Error, Is.False); - Assert.That(options.Wait, Is.True); - } - - [Test] - public void TestNoheaderOption() - { - options.Parse("-noheader"); - Assert.That(options.Error, Is.False); - Assert.That(options.NoHeader, Is.True); - } - - [Test] - public void TestHelpOption() - { - options.Parse("-help"); - Assert.That(options.Error, Is.False); - Assert.That(options.ShowHelp, Is.True); - } - - [Test] - public void TestFullOption() - { - options.Parse("-full"); - Assert.That(options.Error, Is.False); - Assert.That(options.Full, Is.True); - } - -#if !SILVERLIGHT && !NETCF - [Test] - public void TestExploreOptionWithNoFileName() - { - options.Parse("-explore"); - Assert.That(options.Error, Is.False); - Assert.That(options.Explore, Is.True); - Assert.That(options.ExploreFile, Is.EqualTo(Path.GetFullPath("tests.xml"))); - } - - [Test] - public void TestExploreOptionWithGoodFileName() - { - options.Parse("-explore=MyFile.xml"); - Assert.That(options.Error, Is.False); - Assert.That(options.Explore, Is.True); - Assert.That(options.ExploreFile, Is.EqualTo(Path.GetFullPath("MyFile.xml"))); - } - - [Test] - public void TestExploreOptionWithBadFileName() - { - options.Parse("-explore=MyFile*.xml"); - Assert.That(options.Error, Is.True); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -explore=MyFile*.xml" + Env.NewLine)); - } - - [Test] - public void TestResultOptionWithNoFileName() - { - options.Parse("-result"); - Assert.That(options.Error, Is.False); - Assert.That(options.ResultFile, Is.EqualTo(Path.GetFullPath("TestResult.xml"))); - } - - [Test] - public void TestResultOptionWithGoodFileName() - { - options.Parse("-result=MyResult.xml"); - Assert.That(options.Error, Is.False); - Assert.That(options.ResultFile, Is.EqualTo(Path.GetFullPath("MyResult.xml"))); - } - - [Test] - public void TestResultOptionWithBadFileName() - { - options.Parse("-result=MyResult*.xml"); - Assert.That(options.Error, Is.True); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -result=MyResult*.xml" + Env.NewLine)); - } -#endif - - [Test] - public void TestNUnit2FormatOption() - { - options.Parse("-format=nunit2"); - Assert.That(options.Error, Is.False); - Assert.That(options.ResultFormat, Is.EqualTo("nunit2")); - } - - [Test] - public void TestNUnit3FormatOption() - { - options.Parse("-format=nunit3"); - Assert.That(options.Error, Is.False); - Assert.That(options.ResultFormat, Is.EqualTo("nunit3")); - } - - [Test] - public void TestBadFormatOption() - { - options.Parse("-format=xyz"); - Assert.That(options.Error, Is.True); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -format=xyz" + Env.NewLine)); - } - - [Test] - public void TestMissingFormatOption() - { - options.Parse("-format"); - Assert.That(options.Error, Is.True); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -format" + Env.NewLine)); - } - -#if !SILVERLIGHT && !NETCF - [Test] - public void TestOutOptionWithGoodFileName() - { - options.Parse("-out=myfile.txt"); - Assert.False(options.Error); - Assert.That(options.OutFile, Is.EqualTo(Path.GetFullPath("myfile.txt"))); - } - - [Test] - public void TestOutOptionWithNoFileName() - { - options.Parse("-out="); - Assert.True(options.Error); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -out=" + Env.NewLine)); - } - - [Test] - public void TestOutOptionWithBadFileName() - { - options.Parse("-out=my*file.txt"); - Assert.True(options.Error); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -out=my*file.txt" + Env.NewLine)); - } -#endif - - [Test] - public void TestLabelsOption() - { - options.Parse("-labels"); - Assert.That(options.Error, Is.False); - Assert.That(options.LabelTestsInOutput, Is.True); - } - - [Test] - public void TestSeedOption() - { - options.Parse("-seed=123456789"); - Assert.False(options.Error); - Assert.That(options.InitialSeed, Is.EqualTo(123456789)); - } - - [Test] - public void OptionNotRecognizedUnlessPrecededByOptionChar() - { - options.Parse( "/wait" ); - Assert.That(options.Error, Is.False); - Assert.That(options.Wait, Is.False); - Assert.That(options.Parameters, Contains.Item("/wait")); - } - - [Test] - public void InvalidOptionProducesError() - { - options.Parse( "-junk" ); - Assert.That(options.Error); - Assert.That(options.ErrorMessage, Is.EqualTo("Invalid option: -junk" + Env.NewLine)); - } - - [Test] - public void MultipleInvalidOptionsAreListedInErrorMessage() - { - options.Parse( "-junk", "-trash", "something", "-garbage" ); - Assert.That(options.Error); - Assert.That(options.ErrorMessage, Is.EqualTo( - "Invalid option: -junk" + Env.NewLine + - "Invalid option: -trash" + Env.NewLine + - "Invalid option: -garbage" + Env.NewLine)); - } - - [Test] - public void SingleParameterIsSaved() - { - options.Parse("myassembly.dll"); - Assert.That(options.Error, Is.False); - Assert.That(options.Parameters.Length, Is.EqualTo(1)); - Assert.That(options.Parameters[0], Is.EqualTo("myassembly.dll")); - } - - [Test] - public void MultipleParametersAreSaved() - { - options.Parse("assembly1.dll", "-wait", "assembly2.dll", "assembly3.dll"); - Assert.That(options.Error, Is.False); - Assert.That(options.Parameters.Length, Is.EqualTo(3)); - Assert.That(options.Parameters[0], Is.EqualTo("assembly1.dll")); - Assert.That(options.Parameters[1], Is.EqualTo("assembly2.dll")); - Assert.That(options.Parameters[2], Is.EqualTo("assembly3.dll")); - } - - [Test] - public void TestOptionIsRecognized() - { - options.Parse("-test:Some.Class.Name"); - Assert.That(options.Error, Is.False); - Assert.That(options.Tests.Length, Is.EqualTo(1)); - Assert.That(options.Tests[0], Is.EqualTo("Some.Class.Name")); - } - - [Test] - public void MultipleTestOptionsAreRecognized() - { - options.Parse("-test:Class1", "-test=Class2", "-test:Class3"); - Assert.That(options.Error, Is.False); - Assert.That(options.Tests.Length, Is.EqualTo(3)); - Assert.That(options.Tests[0], Is.EqualTo("Class1")); - Assert.That(options.Tests[1], Is.EqualTo("Class2")); - Assert.That(options.Tests[2], Is.EqualTo("Class3")); - } -#if !SILVERLIGHT - [Test] - public void TestIncludeOption() - { - options.Parse("-include:1,2"); - Assert.That(options.Error, Is.False); - Assert.That(options.Include == "1,2"); - } - [Test] - public void TestExcludeOption() - { - options.Parse("-exclude:1,2"); - Assert.That(options.Error, Is.False); - Assert.That(options.Exclude == "1,2"); - } - [Test] - public void TestIncludeExcludeOption() - { - options.Parse("-include:3,4", "-exclude:1,2"); - Assert.That(options.Error, Is.False); - Assert.That(options.Exclude == "1,2"); - Assert.That(options.Include == "3,4"); - } -#endif - } -} diff --git a/test/NUnitLite/src/tests/Runner/NUnit2XmlOutputWriterTests.cs b/test/NUnitLite/src/tests/Runner/NUnit2XmlOutputWriterTests.cs deleted file mode 100644 index 00c266f8a..000000000 --- a/test/NUnitLite/src/tests/Runner/NUnit2XmlOutputWriterTests.cs +++ /dev/null @@ -1,217 +0,0 @@ -#if !SILVERLIGHT -using System; -using System.IO; -using System.Text; -using System.Xml; -using NUnit.Framework; -using NUnit.Framework.Internal; -using NUnit.Tests.Assemblies; - -namespace NUnitLite.Runner.Tests -{ - public class NUnit2XmlOutputWriterTests - { - private XmlDocument doc; - private XmlNode topNode; - private XmlNode envNode; - private XmlNode cultureNode; - private XmlNode suiteNode; - - [TestFixtureSetUp] - public void RunMockAssemblyTests() - { - TestResult result = NUnit.TestUtilities.TestBuilder.RunTestFixture(typeof(MockTestFixture)); - Assert.NotNull(result); - - StringBuilder sb = new StringBuilder(); - StringWriter writer = new StringWriter(sb); - new NUnit2XmlOutputWriter(DateTime.Now).WriteResultFile(result, writer); - writer.Close(); - -#if DEBUG - StreamWriter sw = new StreamWriter("MockAssemblyResult.xml"); - sw.WriteLine(sb.ToString()); - sw.Close(); -#endif - - doc = new XmlDocument(); - doc.LoadXml(sb.ToString()); - - topNode = doc.SelectSingleNode("/test-results"); - if (topNode != null) - { - envNode = topNode.SelectSingleNode("environment"); - cultureNode = topNode.SelectSingleNode("culture-info"); - suiteNode = topNode.SelectSingleNode("test-suite"); - } - } - - [Test] - public void Document_HasThreeChildren() - { - Assert.That(doc.ChildNodes.Count, Is.EqualTo(3)); - } - - [Test] - public void Document_FirstChildIsXmlDeclaration() - { - Assume.That(doc.FirstChild != null); - Assert.That(doc.FirstChild.NodeType, Is.EqualTo(XmlNodeType.XmlDeclaration)); - Assert.That(doc.FirstChild.Name, Is.EqualTo("xml")); - } - - [Test] - public void Document_SecondChildIsComment() - { - Assume.That(doc.ChildNodes.Count >= 2); - Assert.That(doc.ChildNodes[1].Name, Is.EqualTo("#comment")); - } - - [Test] - public void Document_ThirdChildIsTestResults() - { - Assume.That(doc.ChildNodes.Count >= 3); - Assert.That(doc.ChildNodes[2].Name, Is.EqualTo("test-results")); - } - - [Test] - public void Document_HasTestResults() - { - Assert.That(topNode, Is.Not.Null); - Assert.That(topNode.Name, Is.EqualTo("test-results")); - } - - [Test] - public void TestResults_AssemblyPathIsCorrect() - { - Assert.That(RequiredAttribute(topNode, "name"), Is.EqualTo("NUnit.Tests.Assemblies.MockTestFixture")); - } - - [TestCase("total", MockTestFixture.Tests-MockTestFixture.Explicit)] - [TestCase("errors", MockTestFixture.Errors)] - [TestCase("failures", MockTestFixture.Failures)] - [TestCase("inconclusive", MockTestFixture.Inconclusive)] - [TestCase("not-run", MockTestFixture.NotRun-MockTestFixture.Explicit)] - [TestCase("ignored", MockTestFixture.Ignored)] - [TestCase("skipped", MockTestFixture.NotRun-MockTestFixture.Ignored-MockTestFixture.NotRunnable-MockTestFixture.Explicit)] - [TestCase("invalid", MockTestFixture.NotRunnable)] - public void TestResults_CounterIsCorrect(string name, int count) - { - Assert.That(RequiredAttribute(topNode, name), Is.EqualTo(count.ToString())); - } - - [Test] - public void TestResults_HasValidDateAttribute() - { - string dateString = RequiredAttribute(topNode, "date"); -#if (CLR_2_0 || CLR_4_0) && !NETCF - DateTime date; - Assert.That(DateTime.TryParse(dateString, out date), "Invalid date attribute: {0}", dateString); -#endif - } - - [Test] - public void TestResults_HasValidTimeAttribute() - { - string timeString = RequiredAttribute(topNode, "time"); -#if (CLR_2_0 || CLR_4_0) && !NETCF - DateTime time; - Assert.That(DateTime.TryParse(timeString, out time), "Invalid time attribute: {0}", timeString); -#endif - } - - [Test] - public void Environment_HasEnvironmentElement() - { - Assert.That(envNode, Is.Not.Null, "Missing environment element"); - } - - [TestCase("nunit-version")] - [TestCase("clr-version")] - [TestCase("os-version")] - [TestCase("platform")] -#if !NETCF - [TestCase("cwd")] - [TestCase("machine-name")] - [TestCase("user")] - [TestCase("user-domain")] -#endif - public void Environment_HasRequiredAttribute(string name) - { - RequiredAttribute(envNode, name); - } - - [Test] - public void CultureInfo_HasCultureInfoElement() - { - Assert.That(cultureNode, Is.Not.Null, "Missing culture-info element"); - } - - [TestCase("current-culture")] - [TestCase("current-uiculture")] - public void CultureInfo_HasRequiredAttribute(string name) - { - string cultureName = RequiredAttribute(cultureNode, name); - System.Globalization.CultureInfo culture = null; - - try - { - culture = System.Globalization.CultureInfo.CreateSpecificCulture(cultureName); - } - catch(ArgumentException) - { - // Do nothing - culture will be null - } - - Assert.That(culture, Is.Not.Null, "Invalid value for {0}: {1}", name, cultureName); - } - - [Test] - public void TestSuite_HasTestSuiteElement() - { - Assert.That(suiteNode, Is.Not.Null, "Missing test-suite element"); - } - - [TestCase("type", "TestFixture")] - [TestCase("name", "MockTestFixture")] - [TestCase("description", "Fake Test Fixture")] - [TestCase("executed", "True")] - [TestCase("result", "Failure")] - [TestCase("success", "False")] - [TestCase("asserts", "0")] - public void TestSuite_ExpectedAttribute(string name, string value) - { - Assert.That(RequiredAttribute(suiteNode, name), Is.EqualTo(value)); - } - - [Test] - public void TestSuite_HasValidTimeAttribute() - { -#if NETCF - RequiredAttribute(suiteNode, "time"); -#else - double time; - // NOTE: We use the TryParse overload with 4 args because it's supported in .NET 1.1 - Assert.That(double.TryParse(RequiredAttribute(suiteNode, "time"),System.Globalization.NumberStyles.Float,null, out time), "Invalid value for time"); -#endif - } - - [Test] - public void TestSuite_ResultIsFailure() - { - } - - #region Helper Methods - - private string RequiredAttribute(XmlNode node, string name) - { - XmlAttribute attr = node.Attributes[name]; - Assert.That(attr, Is.Not.Null, "Missing attribute {0} on element {1}", name, node.Name); - - return attr.Value; - } - - #endregion - } -} -#endif diff --git a/test/NUnitLite/src/tests/Syntax/AfterTests.cs b/test/NUnitLite/src/tests/Syntax/AfterTests.cs deleted file mode 100644 index 15ea89b7c..000000000 --- a/test/NUnitLite/src/tests/Syntax/AfterTests.cs +++ /dev/null @@ -1,188 +0,0 @@ -// **************************************************************** -// Copyright 2008, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** - -using System; -using System.Threading; -using System.Collections; - -namespace NUnit.Framework.Syntax -{ - public class AfterTest_SimpleConstraint : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Is.EqualTo(10).After(1000); - inheritedSyntax = Helper().EqualTo(10).After(1000); - builderSyntax = Builder().EqualTo(10).After(1000); - } - } - - public class AfterTest_ProperyTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">>"; - staticSyntax = Has.Property("X").EqualTo(10).After(1000); - inheritedSyntax = Helper().Property("X").EqualTo(10).After(1000); - builderSyntax = Builder().Property("X").EqualTo(10).After(1000); - } - } - - public class AfterTest_AndOperator : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >>"; - staticSyntax = Is.GreaterThan(0).And.LessThan(10).After(1000); - inheritedSyntax = Helper().GreaterThan(0).And.LessThan(10).After(1000); - builderSyntax = Builder().GreaterThan(0).And.LessThan(10).After(1000); - } - } - -#if CLR_2_0 || CLR_4_0 - public abstract class AfterSyntaxTests - { - protected bool flag; - protected int num; - protected object ob1, ob2, ob3; - protected ArrayList list; - protected string greeting; - - [SetUp] - public void InitializeValues() - { - this.flag = false; - this.num = 0; - this.ob1 = new object(); - this.ob2 = new object(); - this.ob3 = new object(); - this.list = new ArrayList(); - this.list.Add(1); - this.list.Add(2); - this.list.Add(3); - this.greeting = "hello"; - - new Thread(ModifyValuesAfterDelay).Start(); - } - - private void ModifyValuesAfterDelay() - { - Thread.Sleep(100); - - this.flag = true; - this.num = 1; - this.ob1 = ob2; - this.ob3 = null; - this.list.Add(4); - this.greeting += "world"; - } - } - -#if !NETCF_2_0 - // This compiles under VS2008 but not using NAnt - // TODO: Make Nant script use the highest level of msbuild available - public class AfterSyntaxUsingAnonymousDelegates : AfterSyntaxTests - { - [Test] - public void TrueTest() - { - Assert.That(delegate { return flag; }, Is.True.After(5000, 200)); - } - - [Test] - public void EqualToTest() - { - Assert.That(delegate { return num; }, Is.EqualTo(1).After(5000, 200)); - } - - [Test] - public void SameAsTest() - { - Assert.That(delegate { return ob1; }, Is.SameAs(ob2).After(5000, 200)); - } - - [Test] - public void GreaterTest() - { - Assert.That(delegate { return num; }, Is.GreaterThan(0).After(5000,200)); - } - - [Test] - public void HasMemberTest() - { - Assert.That(delegate { return list; }, Has.Member(4).After(5000, 200)); - } - - [Test] - public void NullTest() - { - Assert.That(delegate { return ob3; }, Is.Null.After(5000, 200)); - } - - [Test] - public void TextTest() - { - Assert.That(delegate { return greeting; }, Is.StringEnding("world").After(5000, 200)); - } - - [Test] - public void ThrowsTest() - { - Assert.That(delegate { throw new Exception(); }, Throws.TypeOf().After(100)); - } - } -#endif - - public class AfterSyntaxUsingActualPassedByRef : AfterSyntaxTests - { - [Test] - public void TrueTest() - { - Assert.That(ref flag, Is.True.After(5000, 200)); - } - - [Test] - public void EqualToTest() - { - Assert.That(ref num, Is.EqualTo(1).After(5000, 200)); - } - - [Test] - public void SameAsTest() - { - Assert.That(ref ob1, Is.SameAs(ob2).After(5000, 200)); - } - - [Test] - public void GreaterTest() - { - Assert.That(ref num, Is.GreaterThan(0).After(5000, 200)); - } - - [Test] - public void HasMemberTest() - { - Assert.That(ref list, Has.Member(4).After(5000, 200)); - } - - [Test] - public void NullTest() - { - Assert.That(ref ob3, Is.Null.After(5000, 200)); - } - - [Test] - public void TextTest() - { - Assert.That(ref greeting, Is.StringEnding("world").After(5000, 200)); - } - } -#endif -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Syntax/ArbitraryConstraintMatching.cs b/test/NUnitLite/src/tests/Syntax/ArbitraryConstraintMatching.cs deleted file mode 100644 index ccba9acfe..000000000 --- a/test/NUnitLite/src/tests/Syntax/ArbitraryConstraintMatching.cs +++ /dev/null @@ -1,82 +0,0 @@ -// **************************************************************** -// Copyright 2012, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** - -using System; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Syntax -{ - [TestFixture] - public class ArbitraryConstraintMatching - { - Constraint custom = new CustomConstraint(); - Constraint another = new AnotherConstraint(); - - [Test] - public void CanMatchCustomConstraint() - { - IResolveConstraint constraint = new ConstraintExpression().Matches(custom); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo("")); - } - - [Test] - public void CanMatchCustomConstraintAfterPrefix() - { - IResolveConstraint constraint = Is.All.Matches(custom); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo(">")); - } - - [Test] - public void CanMatchCustomConstraintsUnderAndOperator() - { - IResolveConstraint constraint = Is.All.Matches(custom).And.Matches(another); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo(" >>")); - } - -#if CLR_2_0 || CLR_4_0 - [Test] - public void CanMatchPredicate() - { - IResolveConstraint constraint = new ConstraintExpression().Matches(new Predicate(IsEven)); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo("")); - Assert.That(42, constraint); - } - - bool IsEven(int num) - { - return (num & 1) == 0; - } - -#if !NETCF_2_0 - // OK when compiled with VS2008, but not under NAnt - [Test] - public void CanMatchLambda() - { - IResolveConstraint constraint = new ConstraintExpression().Matches( (x) => (x & 1) == 0); - Assert.That(constraint.Resolve().ToString(), Is.EqualTo("")); - Assert.That(42, constraint); - } -#endif -#endif - - class CustomConstraint : Constraint - { - public override bool Matches(object actual) - { - throw new NotImplementedException(); - } - - public override void WriteDescriptionTo(MessageWriter writer) - { - throw new NotImplementedException(); - } - } - - class AnotherConstraint : CustomConstraint - { - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/CollectionTests.cs b/test/NUnitLite/src/tests/Syntax/CollectionTests.cs deleted file mode 100644 index a59f6cae8..000000000 --- a/test/NUnitLite/src/tests/Syntax/CollectionTests.cs +++ /dev/null @@ -1,275 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Syntax -{ - public class UniqueTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Unique; - inheritedSyntax = Helper().Unique; - builderSyntax = Builder().Unique; - } - } - - public class CollectionOrderedTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Ordered; - inheritedSyntax = Helper().Ordered; - builderSyntax = Builder().Ordered; - } - } - - public class CollectionOrderedTest_Descending : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Ordered.Descending; - inheritedSyntax = Helper().Ordered.Descending; - builderSyntax = Builder().Ordered.Descending; - } - } - - public class CollectionOrderedTest_Comparer : SyntaxTest - { - [SetUp] - public void SetUp() - { - IComparer comparer = new SimpleObjectComparer(); - parseTree = ""; - staticSyntax = Is.Ordered.Using(comparer); - inheritedSyntax = Helper().Ordered.Using(comparer); - builderSyntax = Builder().Ordered.Using(comparer); - } - } - - public class CollectionOrderedTest_Comparer_Descending : SyntaxTest - { - [SetUp] - public void SetUp() - { - IComparer comparer = new SimpleObjectComparer(); - parseTree = ""; - staticSyntax = Is.Ordered.Using(comparer).Descending; - inheritedSyntax = Helper().Ordered.Using(comparer).Descending; - builderSyntax = Builder().Ordered.Using(comparer).Descending; - } - } - - public class CollectionOrderedByTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName"); - inheritedSyntax = Helper().Ordered.By("SomePropertyName"); - builderSyntax = Builder().Ordered.By("SomePropertyName"); - } - } - - public class CollectionOrderedByTest_Descending : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName").Descending; - inheritedSyntax = Helper().Ordered.By("SomePropertyName").Descending; - builderSyntax = Builder().Ordered.By("SomePropertyName").Descending; - } - } - - public class CollectionOrderedByTest_Comparer : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName").Using(new SimpleObjectComparer()); - inheritedSyntax = Helper().Ordered.By("SomePropertyName").Using(new SimpleObjectComparer()); - builderSyntax = Builder().Ordered.By("SomePropertyName").Using(new SimpleObjectComparer()); - } - } - - public class CollectionOrderedByTest_Comparer_Descending : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName").Using(new SimpleObjectComparer()).Descending; - inheritedSyntax = Helper().Ordered.By("SomePropertyName").Using(new SimpleObjectComparer()).Descending; - builderSyntax = Builder().Ordered.By("SomePropertyName").Using(new SimpleObjectComparer()).Descending; - } - } - - public class CollectionContainsTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Contains.Item(42); - inheritedSyntax = Helper().Contains(42); - builderSyntax = Builder().Contains(42); - } - } - - public class CollectionContainsTest_String : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Contains.Item("abc"); - inheritedSyntax = Helper().Contains("abc"); - builderSyntax = Builder().Contains("abc"); - } - } - -#if !SILVERLIGHT - public class CollectionContainsTest_Comparer : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Contains.Item(42).Using(Comparer.Default); - inheritedSyntax = Helper().Contains(42).Using(Comparer.Default); - builderSyntax = Builder().Contains(42).Using(Comparer.Default); - } - - [Test] - public void ComparerIsCalled() - { - TestComparer comparer = new TestComparer(); - Assert.That(new int[] { 1, 2, 3 }, - Contains.Item(2).Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - [Test] - public void ComparerIsCalledInExpression() - { - TestComparer comparer = new TestComparer(); - Assert.That(new int[] { 1, 2, 3 }, - Has.Length.EqualTo(3).And.Contains(2).Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - } - - public class CollectionContainsTest_Comparer_String : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Contains.Item("abc").Using(Comparer.Default); - inheritedSyntax = Helper().Contains("abc").Using(Comparer.Default); - builderSyntax = Builder().Contains("abc").Using(Comparer.Default); - } - - [Test] - public void ComparerIsCalled() - { - TestComparer comparer = new TestComparer(); - Assert.That(new string[] { "Hello", "World" }, - Contains.Item("World").Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - - [Test] - public void ComparerIsCalledInExpression() - { - TestComparer comparer = new TestComparer(); - Assert.That(new string[] { "Hello", "World" }, - Has.Length.EqualTo(2).And.Contains("World").Using(comparer)); - Assert.That(comparer.Called, "Comparer was not called"); - } - } - - public class CollectionMemberTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Has.Member(42); - inheritedSyntax = Helper().Contains(42); - builderSyntax = Builder().Contains(42); - } - } - - public class CollectionMemberTest_Comparer : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Has.Member(42).Using(Comparer.Default); - inheritedSyntax = Helper().Contains(42).Using(Comparer.Default); - builderSyntax = Builder().Contains(42).Using(Comparer.Default); - } - } -#endif - - public class CollectionSubsetTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - int[] ints = new int[] { 1, 2, 3 }; - parseTree = ""; - staticSyntax = Is.SubsetOf(ints); - inheritedSyntax = Helper().SubsetOf(ints); - builderSyntax = Builder().SubsetOf(ints); - } - } - - public class CollectionEquivalentTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - int[] ints = new int[] { 1, 2, 3 }; - parseTree = ""; - staticSyntax = Is.EquivalentTo(ints); - inheritedSyntax = Helper().EquivalentTo(ints); - builderSyntax = Builder().EquivalentTo(ints); - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/ComparisonTests.cs b/test/NUnitLite/src/tests/Syntax/ComparisonTests.cs deleted file mode 100644 index 36ab321fb..000000000 --- a/test/NUnitLite/src/tests/Syntax/ComparisonTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Syntax -{ - public class GreaterThanTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.GreaterThan(7); - inheritedSyntax = Helper().GreaterThan(7); - builderSyntax = Builder().GreaterThan(7); - } - } - - public class GreaterThanOrEqualTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.GreaterThanOrEqualTo(7); - inheritedSyntax = Helper().GreaterThanOrEqualTo(7); - builderSyntax = Builder().GreaterThanOrEqualTo(7); - } - } - - public class AtLeastTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.AtLeast(7); - inheritedSyntax = Helper().AtLeast(7); - builderSyntax = Builder().AtLeast(7); - } - } - - public class LessThanTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.LessThan(7); - inheritedSyntax = Helper().LessThan(7); - builderSyntax = Builder().LessThan(7); - } - } - - public class LessThanOrEqualTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.LessThanOrEqualTo(7); - inheritedSyntax = Helper().LessThanOrEqualTo(7); - builderSyntax = Builder().LessThanOrEqualTo(7); - } - } - - public class AtMostTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.AtMost(7); - inheritedSyntax = Helper().AtMost(7); - builderSyntax = Builder().AtMost(7); - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/EqualityTests.cs b/test/NUnitLite/src/tests/Syntax/EqualityTests.cs deleted file mode 100644 index cf043176e..000000000 --- a/test/NUnitLite/src/tests/Syntax/EqualityTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Syntax -{ - public class EqualToTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.EqualTo(999); - inheritedSyntax = Helper().EqualTo(999); - builderSyntax = Builder().EqualTo(999); - } - } - - public class EqualToTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.EqualTo("X").IgnoreCase; - inheritedSyntax = Helper().EqualTo("X").IgnoreCase; - builderSyntax = Builder().EqualTo("X").IgnoreCase; - } - } - - public class EqualToTest_WithinTolerance : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.EqualTo(0.7).Within(.005); - inheritedSyntax = Helper().EqualTo(0.7).Within(.005); - builderSyntax = Builder().EqualTo(0.7).Within(.005); - } - } - - - public class EqualityTests - { - [Test] - public void SimpleEqualityTests() - { - int[] i3 = new int[] { 1, 2, 3 }; - double[] d3 = new double[] { 1.0, 2.0, 3.0 }; - int[] iunequal = new int[] { 1, 3, 2 }; - - Assert.That(2 + 2, Is.EqualTo(4)); - Assert.That(2 + 2 == 4); - Assert.That(i3, Is.EqualTo(d3)); - Assert.That(2 + 2, Is.Not.EqualTo(5)); - Assert.That(i3, Is.Not.EqualTo(iunequal)); -#if CLR_2_0 || CLR_4_0 - List list = new List(); - list.Add("foo"); - list.Add("bar"); - Assert.That(list, Is.EqualTo(new string[] { "foo", "bar" })); -#endif - } - - [Test] - public void EqualityTestsWithTolerance() - { - Assert.That(4.99d, Is.EqualTo(5.0d).Within(0.05d)); - Assert.That(4.0d, Is.Not.EqualTo(5.0d).Within(0.5d)); - Assert.That(4.99f, Is.EqualTo(5.0f).Within(0.05f)); - Assert.That(4.99m, Is.EqualTo(5.0m).Within(0.05m)); - Assert.That(3999999999u, Is.EqualTo(4000000000u).Within(5u)); - Assert.That(499, Is.EqualTo(500).Within(5)); - Assert.That(4999999999L, Is.EqualTo(5000000000L).Within(5L)); - Assert.That(5999999999ul, Is.EqualTo(6000000000ul).Within(5ul)); - } - - [Test] - public void EqualityTestsWithTolerance_MixedFloatAndDouble() - { - // Bug Fix 1743844 - Assert.That(2.20492d, Is.EqualTo(2.2d).Within(0.01f), - "Double actual, Double expected, Single tolerance"); - Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01d), - "Double actual, Single expected, Double tolerance"); - Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01f), - "Double actual, Single expected, Single tolerance"); - Assert.That(2.20492f, Is.EqualTo(2.2f).Within(0.01d), - "Single actual, Single expected, Double tolerance"); - Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01d), - "Single actual, Double expected, Double tolerance"); - Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01f), - "Single actual, Double expected, Single tolerance"); - } - - [Test] - public void EqualityTestsWithTolerance_MixingTypesGenerally() - { - // Extending tolerance to all numeric types - Assert.That(202d, Is.EqualTo(200d).Within(2), - "Double actual, Double expected, int tolerance"); - Assert.That(4.87m, Is.EqualTo(5).Within(.25), - "Decimal actual, int expected, Double tolerance"); - Assert.That(4.87m, Is.EqualTo(5ul).Within(1), - "Decimal actual, ulong expected, int tolerance"); - Assert.That(487, Is.EqualTo(500).Within(25), - "int actual, int expected, int tolerance"); - Assert.That(487u, Is.EqualTo(500).Within(25), - "uint actual, int expected, int tolerance"); - Assert.That(487L, Is.EqualTo(500).Within(25), - "long actual, int expected, int tolerance"); - Assert.That(487ul, Is.EqualTo(500).Within(25), - "ulong actual, int expected, int tolerance"); - } - - [Test] - public void EqualityTestsUsingDefaultFloatingPointTolerance() - { - GlobalSettings.DefaultFloatingPointTolerance = 0.05d; - - try - { - Assert.That(4.99d, Is.EqualTo(5.0d)); - Assert.That(4.0d, Is.Not.EqualTo(5.0d)); - Assert.That(4.99f, Is.EqualTo(5.0f)); - } - finally - { - GlobalSettings.DefaultFloatingPointTolerance = 0.0d; - } - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/InvalidCodeTests.cs b/test/NUnitLite/src/tests/Syntax/InvalidCodeTests.cs deleted file mode 100644 index f79ce6b3f..000000000 --- a/test/NUnitLite/src/tests/Syntax/InvalidCodeTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -// **************************************************************** -// Copyright 2007, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org. -// **************************************************************** - -using System; -using System.Collections; -using System.CodeDom.Compiler; -using NUnit.Framework.Constraints; -#if CLR_2_0 || CLR_4_0 -using System.Collections.Generic; -#endif - -namespace NUnit.Framework.Syntax -{ - [TestFixture] - public class InvalidCodeTests : AssertionHelper - { - static readonly string template1 = -@"using System; -using NUnit.Framework; -using NUnit.Framework.Constraints; - -class SomeClass -{ - void SomeMethod() - { - object c = $FRAGMENT$; - } -}"; - - [TestCase("Is.Null.Not")] - [TestCase("Is.Not.Null.GreaterThan(10))")] - [TestCase("Is.Null.All")] - [TestCase("Is.And")] - [TestCase("Is.All.And.And")] - [TestCase("Is.Null.And.Throws")] - public void CodeShouldNotCompile(string fragment) - { - string code = template1.Replace("$FRAGMENT$", fragment); - TestCompiler compiler = new TestCompiler( - new string[] { "system.dll", "nunit.framework.dll" }, - "test.dll"); - CompilerResults results = compiler.CompileCode(code); - if (results.NativeCompilerReturnValue == 0) - Assert.Fail("Code fragment \"" + fragment + "\" should not compile but it did"); - } - - static readonly string template2 = -@"using System; -using NUnit.Framework; -using NUnit.Framework.Constraints; - -class SomeClass -{ - void SomeMethod() - { - Assert.That(42, $FRAGMENT$); - } -}"; - - [TestCase("Is.Not")] - [TestCase("Is.All")] - [TestCase("Is.Not.All")] - [TestCase("Is.All.Not")] - public void CodeShouldNotCompileAsFinishedConstraint(string fragment) - { - string code = template2.Replace("$FRAGMENT$", fragment); - TestCompiler compiler = new TestCompiler( - new string[] { "system.dll", "nunit.framework.dll" }, - "test.dll"); - CompilerResults results = compiler.CompileCode(code); - if (results.NativeCompilerReturnValue == 0) - Assert.Fail("Code fragment \"" + fragment + "\" should not compile as a finished constraint but it did"); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Syntax/OperatorOverrides.cs b/test/NUnitLite/src/tests/Syntax/OperatorOverrides.cs deleted file mode 100644 index e7d275c88..000000000 --- a/test/NUnitLite/src/tests/Syntax/OperatorOverrides.cs +++ /dev/null @@ -1,128 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Syntax -{ - public class NotOperatorOverride : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = !Is.Null; - inheritedSyntax = !Helper().Null; - builderSyntax = !Builder().Null; - } - - [Test] - public void NotOperatorCanApplyToResolvableConstraintExpression() - { - Assert.That(GetType(), !Has.Attribute(typeof(DescriptionAttribute))); - } - } - - [TestFixture, Description("Test")] - public class AndOperatorOverride : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >"; - staticSyntax = Is.GreaterThan(5) & Is.LessThan(10); - inheritedSyntax = Helper().GreaterThan(5) & Is.LessThan(10); - builderSyntax = Builder().GreaterThan(5) & Builder().LessThan(10); - } - - [Test] - public void AndOperatorCanCombineTwoResolvableConstraintExpressions() - { - Assert.That(GetType(), Has.Attribute(typeof(TestFixtureAttribute)) & Has.Attribute(typeof(DescriptionAttribute))); - } - - [Test] - public void AndOperatorCanCombineConstraintAndResolvableConstraintExpression() - { - Assert.That(GetType(), Is.EqualTo(typeof(AndOperatorOverride)) & Has.Attribute(typeof(DescriptionAttribute))); - } - - [Test] - public void AndOperatorCanCombineResolvableConstraintExpressionAndConstraint() - { - Assert.That(GetType(), Has.Attribute(typeof(DescriptionAttribute)) & Is.EqualTo(typeof(AndOperatorOverride))); - } - } - - [TestFixture] - public class OrOperatorOverride : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >"; - staticSyntax = Is.LessThan(5) | Is.GreaterThan(10); - inheritedSyntax = Helper().LessThan(5) | Is.GreaterThan(10); - builderSyntax = Builder().LessThan(5) | Is.GreaterThan(10); - } - - [Test] - public void OrOperatorCanCombineTwoResolvableConstraintExpressions() - { - Assert.That(GetType(), Has.Attribute(typeof(TestFixtureAttribute)) | Has.Attribute(typeof(TestCaseAttribute))); - } - - [Test] - public void OrOperatorCanCombineResolvableConstraintExpressionAndConstraint() - { - Assert.That(GetType(), Has.Attribute(typeof(TestFixtureAttribute)) | Is.EqualTo(7)); - } - - [Test] - public void OrOperatorCanCombineConstraintAndResolvableConstraintExpression() - { - Assert.That(GetType(), Is.EqualTo(7) | Has.Attribute(typeof(TestFixtureAttribute))); - } - } - - public class MixedOperatorOverrides - { - [Test] - public void ComplexTests() - { - string expected = "> >> >>"; - - Constraint c = - Is.Not.Null & Is.Not.LessThan(5) & Is.Not.GreaterThan(10); - Assert.That(c.ToString(), Is.EqualTo(expected).NoClip); - - c = !Is.Null & !Is.LessThan(5) & !Is.GreaterThan(10); - Assert.That(c.ToString(), Is.EqualTo(expected).NoClip); - - Constraint x = null; - c = !x & !Is.LessThan(5) & !Is.GreaterThan(10); - Assert.That(c.ToString(), Is.EqualTo(expected).NoClip); - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/OperatorTests.cs b/test/NUnitLite/src/tests/Syntax/OperatorTests.cs deleted file mode 100644 index f1bb1c141..000000000 --- a/test/NUnitLite/src/tests/Syntax/OperatorTests.cs +++ /dev/null @@ -1,271 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Syntax -{ - #region Not - public class NotTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Is.Not.Null; - inheritedSyntax = Helper().Not.Null; - builderSyntax = Builder().Not.Null; - } - } - - public class NotTest_Cascaded : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">>>"; - staticSyntax = Is.Not.Not.Not.Null; - inheritedSyntax = Helper().Not.Not.Not.Null; - builderSyntax = Builder().Not.Not.Not.Null; - } - } - #endregion - - #region All - public class AllTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Is.All.GreaterThan(0); - inheritedSyntax = Helper().All.GreaterThan(0); - builderSyntax = Builder().All.GreaterThan(0); - } - } - #endregion - - #region Some - public class SomeTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Has.Some.EqualTo(3); - inheritedSyntax = Helper().Some.EqualTo(3); - builderSyntax = Builder().Some.EqualTo(3); - } - } - - public class SomeTest_BeforeBinaryOperators : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " > >>"; - staticSyntax = Has.Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); - inheritedSyntax = Helper().Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); - builderSyntax = Builder().Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); - } - } - - public class SomeTest_NestedSome : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">>"; - staticSyntax = Has.Some.With.Some.LessThan(100); - inheritedSyntax = Helper().Some.With.Some.LessThan(100); - builderSyntax = Builder().Some.With.Some.LessThan(100); - } - - } - - public class SomeTest_UseOfAndSome : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = "> >>"; - staticSyntax = Has.Some.GreaterThan(0).And.Some.LessThan(100); - inheritedSyntax = Helper().Some.GreaterThan(0).And.Some.LessThan(100); - builderSyntax = Builder().Some.GreaterThan(0).And.Some.LessThan(100); - } - } - #endregion - - #region None - public class NoneTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Has.None.LessThan(0); - inheritedSyntax = Helper().None.LessThan(0); - builderSyntax = Builder().None.LessThan(0); - } - } - #endregion - - #region And - public class AndTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >"; - staticSyntax = Is.GreaterThan(5).And.LessThan(10); - inheritedSyntax = Helper().GreaterThan(5).And.LessThan(10); - builderSyntax = Builder().GreaterThan(5).And.LessThan(10); - } - } - - public class AndTest_ThreeAndsWithNot : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = "> > >>>"; - staticSyntax = Is.Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); - inheritedSyntax = Helper().Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); - builderSyntax = Builder().Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); - } - } - #endregion - - #region Or - public class OrTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >"; - staticSyntax = Is.LessThan(5).Or.GreaterThan(10); - inheritedSyntax = Helper().LessThan(5).Or.GreaterThan(10); - builderSyntax = Builder().LessThan(5).Or.GreaterThan(10); - } - } - - public class OrTest_ThreeOrs : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >>"; - staticSyntax = Is.LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); - inheritedSyntax = Helper().LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); - builderSyntax = Builder().LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); - } - } - #endregion - - #region Binary Operator Precedence - public class AndIsEvaluatedBeforeFollowingOr : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " > >"; - staticSyntax = Is.LessThan(100).And.GreaterThan(0).Or.EqualTo(999); - inheritedSyntax = Helper().LessThan(100).And.GreaterThan(0).Or.EqualTo(999); - builderSyntax = Builder().LessThan(100).And.GreaterThan(0).Or.EqualTo(999); - } - } - - public class AndIsEvaluatedBeforePrecedingOr : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >>"; - staticSyntax = Is.EqualTo(999).Or.GreaterThan(0).And.LessThan(100); - inheritedSyntax = Helper().EqualTo(999).Or.GreaterThan(0).And.LessThan(100); - builderSyntax = Builder().EqualTo(999).Or.GreaterThan(0).And.LessThan(100); - } - } - #endregion - - public class OperatorPrecedenceTests - { - public class A - { - public B B - { - get { return new B(); } - } - - public string X - { - get { return "X in A"; } - } - - public string Y - { - get { return "Y in A"; } - } - } - - public class B - { - public string X - { - get { return "X in B"; } - } - - public string Y - { - get { return "Y in B"; } - } - } - - [Test] - public void WithTests() - { - A a = new A(); - Assert.That(a, Has.Property("X").EqualTo("X in A") - .And.Property("Y").EqualTo("Y in A")); - Assert.That(a, Has.Property("X").EqualTo("X in A") - .And.Property("B").Property("X").EqualTo("X in B")); - Assert.That(a, Has.Property("X").EqualTo("X in A") - .And.Property("B").With.Property("X").EqualTo("X in B")); - Assert.That(a, Has.Property("B").Property("X").EqualTo("X in B") - .And.Property("B").Property("Y").EqualTo("Y in B")); - Assert.That(a, Has.Property("B").Property("X").EqualTo("X in B") - .And.Property("B").With.Property("Y").EqualTo("Y in B")); - Assert.That(a, Has.Property("B").With.Property("X").EqualTo("X in B") - .And.Property("Y").EqualTo("Y in B")); - } - - [Test] - public void SomeTests() - { - string[] array = new string[] { "a", "aa", "x", "xy", "xyz" }; - //Assert.That(array, Has.Some.StartsWith("a").And.Some.Length.EqualTo(3)); - Assert.That(array, Has.None.StartsWith("a").And.Length.EqualTo(3)); - Assert.That(array, Has.Some.StartsWith("x").And.Length.EqualTo(3)); - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/PathConstraintTests.cs b/test/NUnitLite/src/tests/Syntax/PathConstraintTests.cs deleted file mode 100644 index 1f9dca67f..000000000 --- a/test/NUnitLite/src/tests/Syntax/PathConstraintTests.cs +++ /dev/null @@ -1,172 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.IO; - -namespace NUnit.Framework.Syntax -{ - public class SamePathTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - string defaultCaseSensitivity = Path.DirectorySeparatorChar == '\\' - ? "ignorecase" : "respectcase"; - - parseTree = string.Format(@"", path, defaultCaseSensitivity); - staticSyntax = Is.SamePath(path); - inheritedSyntax = Helper().SamePath(path); - builderSyntax = Builder().SamePath(path); - } - } - - public class SamePathTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePath(path).IgnoreCase; - inheritedSyntax = Helper().SamePath(path).IgnoreCase; - builderSyntax = Builder().SamePath(path).IgnoreCase; - } - } - - public class NotSamePathTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePath(path).IgnoreCase; - inheritedSyntax = Helper().Not.SamePath(path).IgnoreCase; - builderSyntax = Builder().Not.SamePath(path).IgnoreCase; - } - } - - public class SamePathTest_RespectCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePath(path).RespectCase; - inheritedSyntax = Helper().SamePath(path).RespectCase; - builderSyntax = Builder().SamePath(path).RespectCase; - } - } - - public class NotSamePathTest_RespectCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePath(path).RespectCase; - inheritedSyntax = Helper().Not.SamePath(path).RespectCase; - builderSyntax = Builder().Not.SamePath(path).RespectCase; - } - } - - public class SamePathOrUnderTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - string defaultCaseSensitivity = Path.DirectorySeparatorChar == '\\' - ? "ignorecase" : "respectcase"; - - parseTree = string.Format(@"", path, defaultCaseSensitivity); - staticSyntax = Is.SamePathOrUnder(path); - inheritedSyntax = Helper().SamePathOrUnder(path); - builderSyntax = Builder().SamePathOrUnder(path); - } - } - - public class SamePathOrUnderTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePathOrUnder(path).IgnoreCase; - inheritedSyntax = Helper().SamePathOrUnder(path).IgnoreCase; - builderSyntax = Builder().SamePathOrUnder(path).IgnoreCase; - } - } - - public class NotSamePathOrUnderTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePathOrUnder(path).IgnoreCase; - inheritedSyntax = Helper().Not.SamePathOrUnder(path).IgnoreCase; - builderSyntax = Builder().Not.SamePathOrUnder(path).IgnoreCase; - } - } - - public class SamePathOrUnderTest_RespectCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePathOrUnder(path).RespectCase; - inheritedSyntax = Helper().SamePathOrUnder(path).RespectCase; - builderSyntax = Builder().SamePathOrUnder(path).RespectCase; - } - } - - public class NotSamePathOrUnderTest_RespectCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - string path = "/path/to/match"; - - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePathOrUnder(path).RespectCase; - inheritedSyntax = Helper().Not.SamePathOrUnder(path).RespectCase; - builderSyntax = Builder().Not.SamePathOrUnder(path).RespectCase; - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/PropertyTests.cs b/test/NUnitLite/src/tests/Syntax/PropertyTests.cs deleted file mode 100644 index 1f3440c9f..000000000 --- a/test/NUnitLite/src/tests/Syntax/PropertyTests.cs +++ /dev/null @@ -1,131 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.Framework.Syntax -{ - public class PropertyExistsTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Has.Property("X"); - inheritedSyntax = Helper().Property("X"); - builderSyntax = Builder().Property("X"); - } - } - - public class PropertyExistsTest_AndFollows : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = " >"; - staticSyntax = Has.Property("X").And.EqualTo(7); - inheritedSyntax = Helper().Property("X").And.EqualTo(7); - builderSyntax = Builder().Property("X").And.EqualTo(7); - } - } - - public class PropertyTest_ConstraintFollows : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Has.Property("X").GreaterThan(5); - inheritedSyntax = Helper().Property("X").GreaterThan(5); - builderSyntax = Builder().Property("X").GreaterThan(5); - } - } - - public class PropertyTest_NotFollows : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">>"; - staticSyntax = Has.Property("X").Not.GreaterThan(5); - inheritedSyntax = Helper().Property("X").Not.GreaterThan(5); - builderSyntax = Builder().Property("X").Not.GreaterThan(5); - } - } - - public class LengthTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Has.Length.GreaterThan(5); - inheritedSyntax = Helper().Length.GreaterThan(5); - builderSyntax = Builder().Length.GreaterThan(5); - } - } - - public class CountTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ">"; - staticSyntax = Has.Count.EqualTo(5); - inheritedSyntax = Helper().Count.EqualTo(5); - builderSyntax = Builder().Count.EqualTo(5); - } - } - - public class MessageTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @">"; - staticSyntax = Has.Message.StartsWith("Expected"); - inheritedSyntax = Helper().Message.StartsWith("Expected"); - builderSyntax = Builder().Message.StartsWith("Expected"); - } - } - - public class PropertySyntaxVariations - { - private readonly int[] ints = new int[] { 1, 2, 3 }; - - [Test] - public void ExistenceTest() - { - Assert.That(ints, Has.Property("Length")); - Assert.That(ints, Has.Length); - } - - [Test] - public void SeparateConstraintTest() - { - Assert.That(ints, Has.Property("Length").EqualTo(3)); - Assert.That(ints, Has.Length.EqualTo(3)); - } - } -} \ No newline at end of file diff --git a/test/NUnitLite/src/tests/Syntax/SerializableConstraints.cs b/test/NUnitLite/src/tests/Syntax/SerializableConstraints.cs deleted file mode 100644 index 0bee44e61..000000000 --- a/test/NUnitLite/src/tests/Syntax/SerializableConstraints.cs +++ /dev/null @@ -1,55 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -namespace NUnit.Framework.Syntax -{ -#if !NETCF && !SILVERLIGHT - [TestFixture] - public class BinarySerializableTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.BinarySerializable; - inheritedSyntax = Helper().BinarySerializable; - builderSyntax = Builder().BinarySerializable; - } - } -#endif - -#if !SILVERLIGHT - [TestFixture] - public class XmlSerializableTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.XmlSerializable; - inheritedSyntax = Helper().XmlSerializable; - builderSyntax = Builder().XmlSerializable; - } - } -#endif -} diff --git a/test/NUnitLite/src/tests/Syntax/SimpleConstraints.cs b/test/NUnitLite/src/tests/Syntax/SimpleConstraints.cs deleted file mode 100644 index c9dcf37cc..000000000 --- a/test/NUnitLite/src/tests/Syntax/SimpleConstraints.cs +++ /dev/null @@ -1,111 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Syntax -{ - public class NullTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Null; - inheritedSyntax = Helper().Null; - builderSyntax = Builder().Null; - } - } - - public class TrueTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.True; - inheritedSyntax = Helper().True; - builderSyntax = Builder().True; - } - } - - public class FalseTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.False; - inheritedSyntax = Helper().False; - builderSyntax = Builder().False; - } - } - - public class NaNTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.NaN; - inheritedSyntax = Helper().NaN; - builderSyntax = Builder().NaN; - } - } - - public class PositiveTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Positive; - inheritedSyntax = Helper().Positive; - builderSyntax = Builder().Positive; - } - } - - public class NegativeTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Negative; - inheritedSyntax = Helper().Negative; - builderSyntax = Builder().Negative; - } - } - - public class EmptyTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.Empty; - inheritedSyntax = Helper().Empty; - builderSyntax = Builder().Empty; - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/StringConstraints.cs b/test/NUnitLite/src/tests/Syntax/StringConstraints.cs deleted file mode 100644 index 46de9c686..000000000 --- a/test/NUnitLite/src/tests/Syntax/StringConstraints.cs +++ /dev/null @@ -1,137 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Syntax -{ - public class SubstringTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringContaining("X"); - inheritedSyntax = Helper().ContainsSubstring("X"); - builderSyntax = Builder().ContainsSubstring("X"); - } - } - - public class ContainsSubstringTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Contains.Substring("X"); - inheritedSyntax = Helper().ContainsSubstring("X"); - builderSyntax = Builder().ContainsSubstring("X"); - } - } - - public class SubstringTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringContaining("X").IgnoreCase; - inheritedSyntax = Helper().ContainsSubstring("X").IgnoreCase; - builderSyntax = Builder().ContainsSubstring("X").IgnoreCase; - } - } - - public class StartsWithTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringStarting("X"); - inheritedSyntax = Helper().StartsWith("X"); - builderSyntax = Builder().StartsWith("X"); - } - } - - public class StartsWithTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringStarting("X").IgnoreCase; - inheritedSyntax = Helper().StartsWith("X").IgnoreCase; - builderSyntax = Builder().StartsWith("X").IgnoreCase; - } - } - - public class EndsWithTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringEnding("X"); - inheritedSyntax = Helper().EndsWith("X"); - builderSyntax = Builder().EndsWith("X"); - } - } - - public class EndsWithTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringEnding("X").IgnoreCase; - inheritedSyntax = Helper().EndsWith("X").IgnoreCase; - builderSyntax = Builder().EndsWith("X").IgnoreCase; - } - } - -#if !NETCF - public class RegexTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringMatching("X"); - inheritedSyntax = Helper().Matches("X"); - builderSyntax = Builder().Matches("X"); - } - } - - public class RegexTest_IgnoreCase : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @""; - staticSyntax = Is.StringMatching("X").IgnoreCase; - inheritedSyntax = Helper().Matches("X").IgnoreCase; - builderSyntax = Builder().Matches("X").IgnoreCase; - } - } -#endif -} diff --git a/test/NUnitLite/src/tests/Syntax/SyntaxTest.cs b/test/NUnitLite/src/tests/Syntax/SyntaxTest.cs deleted file mode 100644 index 31a27dd71..000000000 --- a/test/NUnitLite/src/tests/Syntax/SyntaxTest.cs +++ /dev/null @@ -1,70 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Syntax -{ - public abstract class SyntaxTest - { - protected string parseTree; - protected IResolveConstraint staticSyntax; - protected IResolveConstraint inheritedSyntax; - protected IResolveConstraint builderSyntax; - - protected AssertionHelper Helper() - { - return new AssertionHelper(); - } - - protected ConstraintExpression Builder() - { - return new ConstraintExpression(); - } - - [Test] - public void SupportedByStaticSyntax() - { - Assert.That( - staticSyntax.Resolve().ToString(), - Is.EqualTo(parseTree).NoClip); - } - - [Test] - public void SupportedByConstraintBuilder() - { - Assert.That( - builderSyntax.Resolve().ToString(), - Is.EqualTo(parseTree).NoClip); - } - - [Test] - public void SupportedByInheritedSyntax() - { - Assert.That( - inheritedSyntax.Resolve().ToString(), - Is.EqualTo(parseTree).NoClip); - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/TestCompiler.cs b/test/NUnitLite/src/tests/Syntax/TestCompiler.cs deleted file mode 100644 index 237e2bf65..000000000 --- a/test/NUnitLite/src/tests/Syntax/TestCompiler.cs +++ /dev/null @@ -1,57 +0,0 @@ -// **************************************************************** -// Copyright 2007, Charlie Poole -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org. -// **************************************************************** - -using System; -using System.CodeDom.Compiler; -using System.IO; - -namespace NUnit.Framework.Syntax -{ - class TestCompiler - { - Microsoft.CSharp.CSharpCodeProvider provider; -#if CLR_1_1 - ICodeCompiler compiler; -#endif - CompilerParameters options; - - public TestCompiler() : this( null, null ) { } - - public TestCompiler( string[] assemblyNames ) : this( assemblyNames, null ) { } - - public TestCompiler( string[] assemblyNames, string outputName ) - { - this.provider = new Microsoft.CSharp.CSharpCodeProvider(); -#if CLR_1_1 - this.compiler = provider.CreateCompiler(); -#endif - this.options = new CompilerParameters(); - - if ( assemblyNames != null && assemblyNames.Length > 0 ) - options.ReferencedAssemblies.AddRange( assemblyNames ); - if ( outputName != null ) - options.OutputAssembly = outputName; - - options.IncludeDebugInformation = false; - options.TempFiles = new TempFileCollection( Path.GetTempPath(), false ); - options.GenerateInMemory = false; - } - - public CompilerParameters Options - { - get { return options; } - } - - public CompilerResults CompileCode( string code ) - { -#if CLR_2_0 || CLR_4_0 - return provider.CompileAssemblyFromSource( options, code ); -#else - return compiler.CompileAssemblyFromSource(options, code); -#endif - } - } -} diff --git a/test/NUnitLite/src/tests/Syntax/ThrowsTests.cs b/test/NUnitLite/src/tests/Syntax/ThrowsTests.cs deleted file mode 100644 index 451efa58e..000000000 --- a/test/NUnitLite/src/tests/Syntax/ThrowsTests.cs +++ /dev/null @@ -1,241 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework.Constraints; - -namespace NUnit.Framework.Syntax -{ - [TestFixture] - public class ThrowsTests - { - [Test] - public void ThrowsException() - { - IResolveConstraint expr = Throws.Exception; - Assert.AreEqual( - "", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsExceptionWithConstraint() - { - IResolveConstraint expr = Throws.Exception.With.Property("ParamName").EqualTo("myParam"); - Assert.AreEqual( - @">>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsExceptionTypeOf() - { - IResolveConstraint expr = Throws.Exception.TypeOf(typeof(ArgumentException)); - Assert.AreEqual( - ">", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsTypeOf() - { - IResolveConstraint expr = Throws.TypeOf(typeof(ArgumentException)); - Assert.AreEqual( - ">", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsTypeOfAndConstraint() - { - IResolveConstraint expr = Throws.TypeOf(typeof(ArgumentException)).And.Property("ParamName").EqualTo("myParam"); - Assert.AreEqual( - @" >>>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsExceptionTypeOfAndConstraint() - { - IResolveConstraint expr = Throws.Exception.TypeOf(typeof(ArgumentException)).And.Property("ParamName").EqualTo("myParam"); - Assert.AreEqual( - @" >>>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsTypeOfWithConstraint() - { - IResolveConstraint expr = Throws.TypeOf(typeof(ArgumentException)).With.Property("ParamName").EqualTo("myParam"); - Assert.AreEqual( - @" >>>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsTypeofWithMessage() - { - IResolveConstraint expr = Throws.TypeOf(typeof(ArgumentException)).With.Message.EqualTo("my message"); - Assert.AreEqual( - @" >>>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsInstanceOf() - { - IResolveConstraint expr = Throws.InstanceOf(typeof(ArgumentException)); - Assert.AreEqual( - ">", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsExceptionInstanceOf() - { - IResolveConstraint expr = Throws.Exception.InstanceOf(typeof(ArgumentException)); - Assert.AreEqual( - ">", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsInnerException() - { - IResolveConstraint expr = Throws.InnerException.TypeOf(typeof(ArgumentException)); - Assert.AreEqual( - ">>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsExceptionWithInnerException() - { - IResolveConstraint expr = Throws.Exception.With.InnerException.TypeOf(typeof(ArgumentException)); - Assert.AreEqual( - ">>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsTypeOfWithInnerException() - { - IResolveConstraint expr = Throws.TypeOf(typeof(System.Reflection.TargetInvocationException)) - .With.InnerException.TypeOf(typeof(ArgumentException)); - Assert.AreEqual( - " >>>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsTargetInvocationExceptionWithInnerException() - { - IResolveConstraint expr = Throws.TargetInvocationException - .With.InnerException.TypeOf(typeof(ArgumentException)); - Assert.AreEqual( - " >>>", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsArgumentException() - { - IResolveConstraint expr = Throws.ArgumentException; - Assert.AreEqual( - ">", - expr.Resolve().ToString()); - } - - [Test] - public void ThrowsInvalidOperationException() - { - IResolveConstraint expr = Throws.InvalidOperationException; - Assert.AreEqual( - ">", - expr.Resolve().ToString()); - } - -#if CLR_2_0 || CLR_4_0 -#if !NETCF - [Test] - public void DelegateThrowsException() - { - Assert.That( - delegate { throw new ArgumentException(); }, - Throws.Exception); - } - - [Test] - public void LambdaThrowsExcepton() - { - Assert.That( - () => new MyClass(null), - Throws.InstanceOf()); - } - - [Test] - public void LambdaThrowsExceptionWithMessage() - { - Assert.That( - () => new MyClass(null), - Throws.InstanceOf() - .And.Message.Matches("null")); - } - - internal class MyClass - { - public MyClass(string s) - { - if (s == null) - { - throw new ArgumentNullException(); - } - } - } - - [Test] - public void LambdaThrowsNothing() - { - Assert.That(() => (object)null, Throws.Nothing); - } -#else - [Test] - public void DelegateThrowsException() - { - Assert.That( - delegate { Throw(); return; }, - Throws.Exception); - } - - // Encapsulate throw to trick compiler and - // avoid unreachable code warning. Can't - // use pragma because this is also compiled - // under the .NET 1.0 and 1.1 compilers. - private void Throw() - { - throw new ApplicationException(); - } -#endif -#endif - } -} diff --git a/test/NUnitLite/src/tests/Syntax/TypeConstraints.cs b/test/NUnitLite/src/tests/Syntax/TypeConstraints.cs deleted file mode 100644 index a9ad9c0c8..000000000 --- a/test/NUnitLite/src/tests/Syntax/TypeConstraints.cs +++ /dev/null @@ -1,172 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.Framework.Syntax -{ - [TestFixture] - public class ExactTypeTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.TypeOf(typeof(string)); - inheritedSyntax = Helper().TypeOf(typeof(string)); - builderSyntax = Builder().TypeOf(typeof(string)); - } - } - - [TestFixture] - public class InstanceOfTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.InstanceOf(typeof(string)); - inheritedSyntax = Helper().InstanceOf(typeof(string)); - builderSyntax = Builder().InstanceOf(typeof(string)); - } - } - - [TestFixture] - public class AssignableFromTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.AssignableFrom(typeof(string)); - inheritedSyntax = Helper().AssignableFrom(typeof(string)); - builderSyntax = Builder().AssignableFrom(typeof(string)); - } - } - - [TestFixture] - public class AssignableToTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.AssignableTo(typeof(string)); - inheritedSyntax = Helper().AssignableTo(typeof(string)); - builderSyntax = Builder().AssignableTo(typeof(string)); - } - } - - [TestFixture] - public class AttributeTest : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Has.Attribute(typeof(TestFixtureAttribute)); - inheritedSyntax = Helper().Attribute(typeof(TestFixtureAttribute)); - builderSyntax = Builder().Attribute(typeof(TestFixtureAttribute)); - } - } - - [TestFixture] - public class AttributeTestWithFollowingConstraint : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = @">>>"; - staticSyntax = Has.Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; - inheritedSyntax = Helper().Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; - builderSyntax = Builder().Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; - } - } - -#if CLR_2_0 || CLR_4_0 - [TestFixture] - public class ExactTypeTest_Generic : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.TypeOf(); - inheritedSyntax = Helper().TypeOf(); - builderSyntax = Builder().TypeOf(); - } - } - - [TestFixture] - public class InstanceOfTest_Generic : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.InstanceOf(); - inheritedSyntax = Helper().InstanceOf(); - builderSyntax = Builder().InstanceOf(); - } - } - - [TestFixture] - public class AssignableFromTest_Generic : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.AssignableFrom(); - inheritedSyntax = Helper().AssignableFrom(); - builderSyntax = Builder().AssignableFrom(); - } - } - - [TestFixture] - public class AssignableToTest_Generic : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Is.AssignableTo(); - inheritedSyntax = Helper().AssignableTo(); - builderSyntax = Builder().AssignableTo(); - } - } - - [TestFixture] - public class AttributeTest_Generic : SyntaxTest - { - [SetUp] - public void SetUp() - { - parseTree = ""; - staticSyntax = Has.Attribute(); - inheritedSyntax = Helper().Attribute(); - builderSyntax = Builder().Attribute(); - } - } -#endif -} diff --git a/test/NUnitLite/src/tests/TestUtilities/Collections/SimpleObjectCollection.cs b/test/NUnitLite/src/tests/TestUtilities/Collections/SimpleObjectCollection.cs deleted file mode 100644 index 787619f49..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/Collections/SimpleObjectCollection.cs +++ /dev/null @@ -1,81 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.TestUtilities -{ - /// - /// SimpleObjectCollection is used in testing to wrap an array or - /// other collection, ensuring that only methods of the ICollection - /// interface are accessible. - /// - class SimpleObjectCollection : ICollection - { - private readonly ICollection inner; - - public SimpleObjectCollection(ICollection inner) - { - this.inner = inner; - } - - public SimpleObjectCollection(params object[] inner) - { - this.inner = inner; - } - - #region ICollection Members - - public void CopyTo(Array array, int index) - { - inner.CopyTo(array, index); - } - - public int Count - { - get { return inner.Count; } - } - - public bool IsSynchronized - { - get { return inner.IsSynchronized; } - } - - public object SyncRoot - { - get { return inner.SyncRoot; } - } - - #endregion - - #region IEnumerable Members - - public IEnumerator GetEnumerator() - { - return inner.GetEnumerator(); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/Collections/SimpleObjectList.cs b/test/NUnitLite/src/tests/TestUtilities/Collections/SimpleObjectList.cs deleted file mode 100644 index 6a32b1607..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/Collections/SimpleObjectList.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections; - -namespace NUnit.TestUtilities -{ - public class SimpleObjectList : IList - { - private IList inner; - - public SimpleObjectList(IList contents) - { - Initialize(contents); - } - - public SimpleObjectList(params object[] contents) - { - Initialize(contents); - } - - private void Initialize(IList contents) - { -#if CLR_1_1 - this.inner = new System.Collections.ArrayList(); -#else - this.inner = new System.Collections.Generic.List(); -#endif - foreach (object o in contents) - this.inner.Add(o); - } - - #region IList Members - - public int Add(object value) - { - return inner.Add(value); - } - - public void Clear() - { - inner.Clear(); - } - - public bool Contains(object value) - { - return inner.Contains(value); - } - - public int IndexOf(object value) - { - return inner.IndexOf(value); - } - - public void Insert(int index, object value) - { - inner.Insert(index, value); - } - - public bool IsFixedSize - { - get { return inner.IsFixedSize; } - } - - public bool IsReadOnly - { - get { return inner.IsReadOnly; } - } - - public void Remove(object value) - { - inner.Remove(value); - } - - public void RemoveAt(int index) - { - inner.RemoveAt(index); - } - - public object this[int index] - { - get { return inner[index]; } - set { inner[index] = value; } - } - - #endregion - - #region ICollection Members - - public void CopyTo(Array array, int index) - { - inner.CopyTo(array, index); - } - - public int Count - { - get { return inner.Count; } - } - - public bool IsSynchronized - { - get { return inner.IsSynchronized; } - } - - public object SyncRoot - { - get { return inner.SyncRoot; } - } - - #endregion - - #region IEnumerable Members - - public IEnumerator GetEnumerator() - { - return inner.GetEnumerator(); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/Comparers/AlwaysEqualComparer.cs b/test/NUnitLite/src/tests/TestUtilities/Comparers/AlwaysEqualComparer.cs deleted file mode 100644 index 8fb8bb388..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/Comparers/AlwaysEqualComparer.cs +++ /dev/null @@ -1,41 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2006 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.TestUtilities -{ - internal class AlwaysEqualComparer : IComparer - { - public bool Called = false; - - int IComparer.Compare(object x, object y) - { - Called = true; - - // This comparer ALWAYS returns zero (equal)! - return 0; - } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/Comparers/SimpleEqualityComparer.cs b/test/NUnitLite/src/tests/TestUtilities/Comparers/SimpleEqualityComparer.cs deleted file mode 100644 index a64f9f3bd..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/Comparers/SimpleEqualityComparer.cs +++ /dev/null @@ -1,43 +0,0 @@ -#if CLR_2_0 || CLR_4_0 -using System.Collections; -using System.Collections.Generic; - -namespace NUnit.TestUtilities -{ - public class SimpleEqualityComparer : IEqualityComparer - { - public bool Called; - - bool IEqualityComparer.Equals(object x, object y) - { - Called = true; -#if SILVERLIGHT - return Comparer.Default.Compare(x, y) == 0; -#else - return Comparer.Default.Compare(x, y) == 0; -#endif - } - - int IEqualityComparer.GetHashCode(object x) - { - return x.GetHashCode(); - } - } - - public class SimpleEqualityComparer : IEqualityComparer - { - public bool Called; - - bool IEqualityComparer.Equals(T x, T y) - { - Called = true; - return Comparer.Default.Compare(x, y) == 0; - } - - int IEqualityComparer.GetHashCode(T x) - { - return x.GetHashCode(); - } - } -} -#endif diff --git a/test/NUnitLite/src/tests/TestUtilities/Comparers/SimpleObjectComparer.cs b/test/NUnitLite/src/tests/TestUtilities/Comparers/SimpleObjectComparer.cs deleted file mode 100644 index 930991047..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/Comparers/SimpleObjectComparer.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections; - -namespace NUnit.TestUtilities -{ - public class SimpleObjectComparer : IComparer - { - public bool Called; - - public int Compare(object x, object y) - { - Called = true; -#if SILVERLIGHT - return System.Collections.Generic.Comparer.Default.Compare(x, y); -#else - return System.Collections.Comparer.Default.Compare(x, y); -#endif - } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/ResultSummary.cs b/test/NUnitLite/src/tests/TestUtilities/ResultSummary.cs deleted file mode 100644 index 0abf71933..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/ResultSummary.cs +++ /dev/null @@ -1,207 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - - using System; - using NUnit.Framework; - using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.TestUtilities -{ - /// - /// Summary description for ResultSummary. - /// - public class ResultSummary - { - private int resultCount = 0; - private int testsRun = 0; - private int failureCount = 0; - private int errorCount = 0; - private int successCount = 0; - private int inconclusiveCount = 0; - private int skipCount = 0; - private int ignoreCount = 0; - private int notRunnable = 0; - - private TimeSpan duration = TimeSpan.Zero; - private string name; - - public ResultSummary() { } - - public ResultSummary(ITestResult result) - { - Summarize(result); - } - - private void Summarize(ITestResult result) - { - if (this.name == null) - { - this.name = result.Name; - this.duration = result.Duration; - } - - if (result.HasChildren) - { - foreach (TestResult childResult in result.Children) - Summarize(childResult); - } - else - { - resultCount++; - - switch (result.ResultState.Status) - { - case TestStatus.Passed: - successCount++; - testsRun++; - break; - case TestStatus.Failed: - failureCount++; - testsRun++; - break; - //case TestStatus.Error: - //case TestStatus.Cancelled: - //errorCount++; - //testsRun++; - //break; - case TestStatus.Inconclusive: - inconclusiveCount++; - testsRun++; - break; - //case TestStatus.NotRunnable: - // notRunnable++; - // //errorCount++; - // break; - //case TestStatus.Ignored: - // ignoreCount++; - // break; - case TestStatus.Skipped: - default: - skipCount++; - break; - } - } - } - - public string Name - { - get { return name; } - } - - public bool Success - { - get { return failureCount == 0; } - } - - /// - /// Returns the number of test cases for which results - /// have been summarized. Any tests excluded by use of - /// Category or Explicit attributes are not counted. - /// - public int ResultCount - { - get { return resultCount; } - } - - /// - /// Returns the number of test cases actually run, which - /// is the same as ResultCount, less any Skipped, Ignored - /// or NonRunnable tests. - /// - public int TestsRun - { - get { return testsRun; } - } - - /// - /// Returns the number of tests that passed - /// - public int Passed - { - get { return successCount; } - } - - /// - /// Returns the number of test cases that had an error. - /// - public int Errors - { - get { return errorCount; } - } - - /// - /// Returns the number of test cases that failed. - /// - public int Failures - { - get { return failureCount; } - } - - /// - /// Returns the number of test cases that failed. - /// - public int Inconclusive - { - get { return inconclusiveCount; } - } - - /// - /// Returns the number of test cases that were not runnable - /// due to errors in the signature of the class or method. - /// Such tests are also counted as Errors. - /// - public int NotRunnable - { - get { return notRunnable; } - } - - /// - /// Returns the number of test cases that were skipped. - /// - public int Skipped - { - get { return skipCount; } - } - - public int Ignored - { - get { return ignoreCount; } - } - - public TimeSpan Duration - { - get { return duration; } - } - - public int TestsNotRun - { - get { return skipCount + ignoreCount + notRunnable; } - } - - public int ErrorsAndFailures - { - get { return errorCount + failureCount; } - } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/TestAssert.cs b/test/NUnitLite/src/tests/TestUtilities/TestAssert.cs deleted file mode 100644 index 4a51aab97..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/TestAssert.cs +++ /dev/null @@ -1,144 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.TestUtilities -{ - public class TestAssert - { - #region IsRunnable - - /// - /// Verify that a test is runnable - /// - public static void IsRunnable(Test test) - { - Assert.AreEqual(RunState.Runnable, test.RunState); - } - - /// - /// Verify that the first child test is runnable - /// - public static void FirstChildIsRunnable(Test test) - { - IsRunnable((Test)test.Tests[0]); - } - - /// - /// Verify that a Type can be used to create a - /// runnable fixture - /// - public static void IsRunnable(Type type) - { - TestSuite suite = TestBuilder.MakeFixture(type); - Assert.NotNull(suite, "Unable to construct fixture"); - Assert.AreEqual(RunState.Runnable, suite.RunState); - } - - /// - /// Verify that a Type is runnable, then run it and - /// verify the result. - /// - public static void IsRunnable(Type type, ResultState resultState) - { - TestSuite suite = TestBuilder.MakeFixture(type); - Assert.NotNull(suite, "Unable to construct fixture"); - Assert.AreEqual(RunState.Runnable, suite.RunState); - ITestResult result = TestBuilder.RunTest(suite); - Assert.AreEqual(resultState, result.ResultState); - } - - /// - /// Verify that a named test method is runnable - /// - public static void IsRunnable(Type type, string name) - { - Test test = TestBuilder.MakeTestCase(type, name); - Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); - } - - /// - /// Verify that the first child (usually a test case) - /// of a named test method is runnable - /// - public static void FirstChildIsRunnable(Type type, string name) - { - Test suite = TestBuilder.MakeTestCase(type, name); - TestAssert.FirstChildIsRunnable(suite); - } - - /// - /// Verify that a named test method is runnable, then - /// run it and verify the result. - /// - public static void IsRunnable(Type type, string name, ResultState resultState) - { - Test test = TestBuilder.MakeTestCase(type, name); - Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); - object testObject = Activator.CreateInstance(type); - ITestResult result = TestBuilder.RunTest(test, testObject); - if (result.HasChildren) // In case it's a parameterized method - result = (ITestResult)result.Children[0]; - Assert.That(result.ResultState, Is.EqualTo(resultState)); - } - - #endregion - - #region IsNotRunnable - public static void IsNotRunnable(Test test) - { - Assert.AreEqual(RunState.NotRunnable, test.RunState); - ITestResult result = TestBuilder.RunTest(test, null); - Assert.AreEqual(ResultState.NotRunnable, result.ResultState); - } - - public static void IsNotRunnable(Type type) - { - TestSuite fixture = TestBuilder.MakeFixture(type); - Assert.NotNull(fixture, "Unable to construct fixture"); - IsNotRunnable(fixture); - } - - public static void IsNotRunnable(Type type, string name) - { - IsNotRunnable(TestBuilder.MakeTestCase(type, name)); - } - - public static void FirstChildIsNotRunnable(Test suite) - { - IsNotRunnable((Test)suite.Tests[0]); - } - - public static void FirstChildIsNotRunnable(Type type, string name) - { - FirstChildIsNotRunnable(TestBuilder.MakeParameterizedMethodSuite(type, name)); - } - #endregion - - private TestAssert() { } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/TestBuilder.cs b/test/NUnitLite/src/tests/TestUtilities/TestBuilder.cs deleted file mode 100644 index 8ca12138a..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/TestBuilder.cs +++ /dev/null @@ -1,174 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2009 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Reflection; -using NUnit.Framework; -using NUnit.Framework.Api; -using NUnit.Framework.Builders; -using NUnit.Framework.Internal; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Extensibility; -using NUnit.Framework.Internal.WorkItems; -using System.Threading; - -namespace NUnit.TestUtilities -{ - /// - /// Utility Class used to build NUnit tests for use as test data - /// - public class TestBuilder - { - private static NUnitTestFixtureBuilder fixtureBuilder = new NUnitTestFixtureBuilder(); - private static NUnitTestCaseBuilder testBuilder = new NUnitTestCaseBuilder(); - -#if !NUNITLITE - static TestBuilder() - { - if (!CoreExtensions.Host.Initialized) - CoreExtensions.Host.Initialize(); - } -#endif - - public static TestSuite MakeFixture(Type type) - { - return (TestSuite)fixtureBuilder.BuildFrom(type); - } - - public static TestSuite MakeFixture(object fixture) - { - return (TestSuite)fixtureBuilder.BuildFrom(fixture.GetType()); - } - - public static TestSuite MakeParameterizedMethodSuite(Type type, string methodName) - { - return (TestSuite)MakeTestCase(type, methodName); - } - - public static Test MakeTestCase(Type type, string methodName) - { - MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (method == null) - Assert.Fail("Unable to find method {0} in type {1}", methodName, type.FullName); - return testBuilder.BuildFrom(method); - } - - public static Test MakeTestCase(object fixture, string methodName) - { - return MakeTestCase(fixture.GetType(), methodName); - } - - public static TestResult RunTestFixture(Type type) - { - TestSuite suite = MakeFixture(type); - - TestExecutionContext context = new TestExecutionContext(); - context.TestObject = null; - - CompositeWorkItem work = new CompositeWorkItem(suite, TestFilter.Empty); - return ExecuteAndWaitForResult(work, context); - } - - public static TestResult RunTestFixture(object fixture) - { - TestSuite suite = MakeFixture(fixture); - - TestExecutionContext context = new TestExecutionContext(); - context.TestObject = fixture; - - WorkItem work = suite.CreateWorkItem(TestFilter.Empty); - return ExecuteAndWaitForResult(work, context); - } - - public static ITestResult RunTestCase(Type type, string methodName) - { - Test test = MakeTestCase(type, methodName); - - object testObject = null; - if (!IsStaticClass(type)) - testObject = Activator.CreateInstance(type); - - return RunTest(test, testObject); - } - - public static ITestResult RunTestCase(object fixture, string methodName) - { - Test test = MakeTestCase(fixture, methodName); - return RunTest(test, fixture); - } - - public static WorkItem RunTestCaseAsync(object fixture, string methodName) - { - Test test = MakeTestCase(fixture, methodName); - return RunTestAsync(test, fixture); - } - - public static ITestResult RunTest(Test test) - { - return RunTest(test, null); - } - - public static WorkItem RunTestAsync(Test test) - { - return RunTestAsync(test, (object)null); - } - - public static WorkItem RunTestAsync(Test test, object testObject) - { - TestExecutionContext context = new TestExecutionContext(); - context.TestObject = testObject; - - WorkItem work = test.CreateWorkItem(TestFilter.Empty); - work.Execute(context); - - return work; - } - - public static ITestResult RunTest(Test test, object testObject) - { - TestExecutionContext context = new TestExecutionContext(); - context.TestObject = testObject; - - WorkItem work = test.CreateWorkItem(TestFilter.Empty); - return ExecuteAndWaitForResult(work, context); - } - - private static TestResult ExecuteAndWaitForResult(WorkItem work, TestExecutionContext context) - { - work.Execute(context); - - // TODO: Replace with an event - while (work.State != WorkItemState.Complete) - Thread.Sleep(1); - - return work.Result; - } - - private static bool IsStaticClass(Type type) - { - return type.IsAbstract && type.IsSealed; - } - - private TestBuilder() { } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/TestComparer.cs b/test/NUnitLite/src/tests/TestUtilities/TestComparer.cs deleted file mode 100644 index aa83dffaf..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/TestComparer.cs +++ /dev/null @@ -1,51 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2006 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using System.Collections; - -namespace NUnit.TestUtilities -{ - internal class TestComparer : IComparer - { - public bool Called = false; - - #region IComparer Members - public int Compare(object x, object y) - { - Called = true; - - if (x == null && y == null) - return 0; - - if (x == null || y == null) - return -1; - - if (x.Equals(y)) - return 0; - - return -1; - } - #endregion - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/TestDelegates.cs b/test/NUnitLite/src/tests/TestUtilities/TestDelegates.cs deleted file mode 100644 index 6edfd8b73..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/TestDelegates.cs +++ /dev/null @@ -1,66 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2008 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; - -namespace NUnit.TestUtilities -{ - public class TestDelegates - { - public static void ThrowsArgumentException() - { - throw new ArgumentException("myMessage", "myParam"); - } - - public static void ThrowsSystemException() - { - throw new Exception("my message"); - } - - public static void ThrowsNothing() - { - } - - public static void ThrowsCustomException() - { - throw new CustomException(); - } - - public static void ThrowsDerivedCustomException() - { - throw new DerivedCustomException(); - } - - public class CustomException : Exception - { - } - - public class DerivedCustomException : CustomException - { - } - - public class DerivedException : Exception - { - } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/TestFinder.cs b/test/NUnitLite/src/tests/TestUtilities/TestFinder.cs deleted file mode 100644 index 84337e64a..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/TestFinder.cs +++ /dev/null @@ -1,98 +0,0 @@ -// *********************************************************************** -// Copyright (c) 2007 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** - -using System; -using NUnit.Framework; -using NUnit.Framework.Api; -using NUnit.Framework.Internal; - -namespace NUnit.TestUtilities -{ - /// - /// Utility class used to locate tests by name in a test suite - /// - public class TestFinder - { - public static Test MustFind(string name, TestSuite suite, bool recursive) - { - Test test = Find(name, suite, recursive); - - Assert.NotNull(test, "Unable to find test {0}", name); - - return test; - } - - public static Test Find(string name, TestSuite suite, bool recursive) - { - foreach (Test child in suite.Tests) - { - if (child.Name == name) - return child; - if (recursive) - { - TestSuite childSuite = child as TestSuite; - if (childSuite != null) - { - Test grandchild = Find(name, childSuite, true); - if (grandchild != null) - return grandchild; - } - } - } - - return null; - } - - public static ITestResult MustFind(string name, TestResult result, bool recursive) - { - ITestResult foundResult = Find(name, result, recursive); - - Assert.NotNull(foundResult, "Unable to find result for {0}", name); - - return foundResult; - } - - public static ITestResult Find(string name, TestResult result, bool recursive) - { - if (result.HasChildren) - { - foreach (TestResult childResult in result.Children) - { - if (childResult.Name == name) - return childResult; - - if (recursive && childResult.HasChildren) - { - ITestResult r = Find(name, childResult, true); - if (r != null) - return r; - } - } - } - - return null; - } - - private TestFinder() { } - } -} diff --git a/test/NUnitLite/src/tests/TestUtilities/UniqueValues.cs b/test/NUnitLite/src/tests/TestUtilities/UniqueValues.cs deleted file mode 100644 index 2af5911f5..000000000 --- a/test/NUnitLite/src/tests/TestUtilities/UniqueValues.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections; -using NUnit.Framework; - -namespace NUnit.TestUtilities -{ - public class UniqueValues - { - public static int Count(IEnumerable actual) - { - NUnit.ObjectList list = new NUnit.ObjectList(); - - foreach (object o1 in actual) - if (!list.Contains(o1)) - list.Add(o1); - - return list.Count; - } - - public static void Check(IEnumerable values, int minExpected) - { - int count = Count(values); - Assert.That(count, Is.Not.EqualTo(1), "All values were the same!"); - // TODO: Change to an actual warning once we implement them - Assert.That(count, Is.GreaterThanOrEqualTo(minExpected), "WARNING: The number of unique values less than expected."); - } - - #region Self-test - - [TestCase(1, 2, 3, 4, 5, ExpectedResult = 5)] - [TestCase(1, 2, 3, 4, 3, ExpectedResult = 4)] - [TestCase(1, 1, 1, 1, 1, ExpectedResult = 1)] - [TestCase(1, 2, 1, 2, 1, ExpectedResult = 2)] - [TestCase(1, 1, 1, 2, 2, ExpectedResult = 2)] -#if !NET_1_1 - [TestCase(ExpectedResult = 0)] -#endif - public static int CountUniqueValuesTest(params int[] values) - { - return UniqueValues.Count(values); - } - - #endregion - } -} diff --git a/test/NUnitLite/src/tests/nunitlite.tests-2.0.csproj b/test/NUnitLite/src/tests/nunitlite.tests-2.0.csproj deleted file mode 100644 index 05de9e844..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-2.0.csproj +++ /dev/null @@ -1,263 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {C8FA4073-B24E-4178-93A1-5E1256C8B528} - Exe - Properties - NUnitLite.Tests - nunitlite.tests - - - 3.5 - - - false - v2.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - obj\$(Configuration)\net-2.0\ - - - true - full - false - TRACE;DEBUG;NET_2_0,CLR_2_0,NUNITLITE - prompt - 4 - ..\..\bin\Debug\net-2.0\ - - - pdbonly - true - TRACE;NET_2_0,CLR_2_0,NUNITLITE - prompt - 4 - ..\..\bin\Release\net-2.0\ - - - - - - - - {C24A3FC4-2541-4E9C-BADD-564777610B75} - nunitlite-2.0 - - - {1516338A-F26B-4BA7-AF6E-C3F6A39DC45B} - mock-assembly-2.0 - - - {442DAB16-3063-4FE3-90B6-C29C3D85360D} - nunitlite.testdata-2.0 - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - False - .NET Framework 3.5 SP1 - false - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-3.5.csproj b/test/NUnitLite/src/tests/nunitlite.tests-3.5.csproj deleted file mode 100644 index bb2ff2988..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-3.5.csproj +++ /dev/null @@ -1,262 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {94A4E298-F324-4531-856F-127505F766E5} - Exe - Properties - NUnitLite.Tests - nunitlite.tests - - - 3.5 - - - false - v3.5 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - obj\$(Configuration)\net-3.5\ - - - true - full - false - ..\..\bin\Debug\net-3.5\ - TRACE;DEBUG;NET_3_5, CLR_2_0,NUNITLITE - prompt - 4 - AllRules.ruleset - - - pdbonly - true - ..\..\bin\Release\net-3.5\ - TRACE;NET_3_5, CLR_2_0,NUNITLITE - prompt - 4 - AllRules.ruleset - - - - - - - - {43B24DC5-16D6-45EF-93F1-B021B785A892} - nunitlite-3.5 - - - {1798FBBC-4B6E-4ED8-90A8-7DD9C36194E7} - mock-assembly-3.5 - - - {652AFEEB-B19C-4C67-A014-2248EA72F229} - nunitlite.testdata-3.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - False - .NET Framework 3.5 SP1 - false - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-4.0.csproj b/test/NUnitLite/src/tests/nunitlite.tests-4.0.csproj deleted file mode 100644 index 1443f59ff..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-4.0.csproj +++ /dev/null @@ -1,262 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {497A578E-EF93-4190-96E0-B7F22E08027B} - Exe - Properties - NUnitLite.Tests - nunitlite.tests - - - 3.5 - - - false - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - obj\$(Configuration)\net-4.0\ - - - true - full - false - ..\..\bin\Debug\net-4.0\ - TRACE;DEBUG;NET_4_0, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - - - pdbonly - true - ..\..\bin\Release\net-4.0\ - TRACE;NET_4_0, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - - - - - - - - {1567BCCE-7BE9-4815-84D7-7F794DB39081} - nunitlite-4.0 - - - {961F4A5A-CAC4-4A53-9EF0-C6EE26A6429A} - mock-assembly-4.0 - - - {5C77A144-3CD1-42FC-B622-410E1945CA1E} - nunitlite.testdata-4.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - False - .NET Framework 3.5 SP1 - false - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-4.5.csproj b/test/NUnitLite/src/tests/nunitlite.tests-4.5.csproj deleted file mode 100644 index 560150599..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-4.5.csproj +++ /dev/null @@ -1,274 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {B08DC15F-FC46-4B50-9366-8F745F41A869} - Exe - Properties - NUnitLite.Tests - nunitlite.tests - - - 3.5 - - - false - v4.5 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - obj\$(Configuration)\net-4.5\ - - - true - full - false - ..\..\bin\Debug\net-4.5\ - TRACE;DEBUG;NET_4_5, CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - false - - - pdbonly - true - ..\..\bin\Release\net-4.5\ - TRACE;NET_4_5,CLR_4_0,NUNITLITE - prompt - 4 - AllRules.ruleset - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - False - .NET Framework 3.5 SP1 - false - - - - - - - - {d12f0f7b-8de3-43ec-ba49-41052d065a9b} - nunitlite-4.5 - - - {a57ffbd8-684a-4868-a4e1-a5d28ec6ea3b} - mock-assembly-4.5 - - - {6358fbca-9ca2-4a70-af87-18b916400cee} - nunitlite.testdata-4.5 - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-netcf-2.0.csproj b/test/NUnitLite/src/tests/nunitlite.tests-netcf-2.0.csproj deleted file mode 100644 index e9ce5bbe8..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-netcf-2.0.csproj +++ /dev/null @@ -1,229 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {4B518BF0-D523-4F75-AF3B-9B41865E634A} - Exe - Properties - NUnit.Framework.Tests - nunitlite.tests - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - NUnitLite - v2.0 - Windows CE - - - - - obj\$(Configuration)\netcf-2.0\ - - - true - full - false - ..\..\bin\Debug\netcf-2.0 - TRACE;DEBUG;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\..\bin\Release\netcf-2.0\ - TRACE;WindowsCE;NETCF;NETCF_2_0;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {BED999D7-F594-4CE4-A037-E40E2B9C1288} - nunitlite-netcf-2.0 - - - {33EA4538-3452-42ED-92A9-4CC3B25032AD} - mock-assembly-netcf-2.0 - - - {F67E80E8-DF9F-4C66-9142-5002FA638EB7} - nunitlite.testdata-netcf-2.0 - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-netcf-3.5.csproj b/test/NUnitLite/src/tests/nunitlite.tests-netcf-3.5.csproj deleted file mode 100644 index 03bc0722e..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-netcf-3.5.csproj +++ /dev/null @@ -1,227 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {80A9EC94-2C42-44AC-9D2C-E1418D712C48} - Exe - Properties - NUnit.Framework.Tests - nunitlite.tests - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - nunitlite.tests_netcf_3._5 - v3.5 - Windows CE - - - obj\$(Configuration)\netcf-3.5\ - - - true - full - false - ..\..\bin\Debug\netcf-3.5\ - TRACE;DEBUG;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\..\bin\Release\netcf-3.5\ - TRACE;WindowsCE;NETCF;NETCF_3_5;CLR_2_0;NUNITLITE - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {5F6CB3DC-5CE5-4C6A-AB23-936DB3B35DCC} - nunitlite-netcf-3.5 - - - {B0C85907-1103-44F4-ACFF-6A1B9170C0B1} - mock-assembly-netcf-3.5 - - - {0B7C0B55-6A49-4F32-993E-C9ED6DA0B73C} - nunitlite.testdata-netcf-3.5 - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-sl-3.0.csproj b/test/NUnitLite/src/tests/nunitlite.tests-sl-3.0.csproj deleted file mode 100644 index 4bc177f8d..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-sl-3.0.csproj +++ /dev/null @@ -1,272 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {FFEA1F81-9631-43A8-8368-FBC14B1E7B02} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnitLite.Tests - nunitlite.tests - Silverlight - v3.0 - $(TargetFrameworkVersion) - true - - true - true - nunitlite.tests-sl-3.0.xap - Properties\AppManifest.xml - NUnitLite.Tests.App - TestPage.html - true - true - true - Properties\OutOfBrowserSettings.xml - false - true - - false - - obj\$(Configuration)\sl-3.0\ - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-3.0\ - TRACE;DEBUG;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-3.0\ - TRACE;SILVERLIGHT;SL_3_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - false - - - - - - - - $(MSBuildExtensionsPath)\..\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Testing\Microsoft.Silverlight.Testing.dll - - - $(MSBuildExtensionsPath)\..\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Testing\Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll - - - True - - - True - - - True - - - True - - - True - - - True - - - - - - App.xaml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - MSBuild:Compile - - - - - - - - - - - {02B02379-2596-4E45-8B10-835D62EA2D9E} - nunitlite-sl-3.0 - - - {BB355D2C-FB4F-4526-9B40-7944C40FDFDA} - mock-assembly-sl-3.0 - - - {6BB1FF9E-DF15-4999-8EEE-F4DA328FBCBB} - nunitlite.testdata-sl-3.0 - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-sl-4.0.csproj b/test/NUnitLite/src/tests/nunitlite.tests-sl-4.0.csproj deleted file mode 100644 index 2bf2d26ed..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-sl-4.0.csproj +++ /dev/null @@ -1,279 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {0B899C26-9114-440A-A8A1-615CDE7EE6BD} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnitLite.Tests - nunitlite.tests - Silverlight - v4.0 - $(TargetFrameworkVersion) - true - - true - true - nunitlite.tests-sl-4.0.xap - Properties\AppManifest.xml - NUnitLite.Tests.App - TestPage.html - true - true - true - Properties\OutOfBrowserSettings.xml - false - true - - obj\$(Configuration)\sl-4.0\ - - - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-4.0\ - TRACE;DEBUG;SILVERLIGHT;SL_4_0;CLR_4_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-4.0\ - TRACE;SILVERLIGHT;SL_4_0;CLR_2_0;NUNITLITE - true - true - prompt - 4 - - - false - - - - - - - - $(MSBuildExtensionsPath)\..\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Testing\Microsoft.Silverlight.Testing.dll - - - $(MSBuildExtensionsPath)\..\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Testing\Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll - - - True - - - - - - True - - - True - - - - - - App.xaml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - MSBuild:Compile - - - - - - - - {41326141-EB24-4984-9D9B-5CFAA55946BA} - nunitlite-sl-4.0 - - - {3C1249FC-B5DF-4E3A-ADDD-817526254876} - mock-assembly-sl-4.0 - - - {E97412B5-8C91-4236-8E9A-24C8E20BC675} - nunitlite.testdata-sl-4.0 - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests-sl-5.0.csproj b/test/NUnitLite/src/tests/nunitlite.tests-sl-5.0.csproj deleted file mode 100644 index efe3a20b2..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests-sl-5.0.csproj +++ /dev/null @@ -1,274 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {7107C352-7F42-497E-A26C-25E9AAE8E54C} - {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NUnitLite.Tests - nunitlite.tests - Silverlight - v5.0 - $(TargetFrameworkVersion) - true - - true - true - nunitlite.tests-sl-5.0.xap - Properties\AppManifest.xml - NUnitLite.Tests.App - TestPage.html - true - true - true - Properties\OutOfBrowserSettings.xml - false - true - - - obj\$(Configuration)\sl-5.0\ - - - - - - v3.5 - - - true - full - false - ..\..\bin\Debug\sl-5.0\ - TRACE;DEBUG;SILVERLIGHT;CLR_4_0;SL_5_0;NUNITLITE - true - true - prompt - 4 - - - pdbonly - true - ..\..\bin\Release\sl-5.0\ - TRACE;SILVERLIGHT;CLR_4_0;SL_5_0;NUNITLITE - true - true - prompt - 4 - - - - $(MSBuildExtensionsPath)\..\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Testing\Microsoft.Silverlight.Testing.dll - - - $(MSBuildExtensionsPath)\..\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Testing\Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll - - - False - True - - - True - - - - True - - - True - - - - - - App.xaml - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - MSBuild:Compile - - - - - - - - {5EFE54B3-2494-4DF4-A42A-8492A5EC4BA3} - nunitlite-sl-5.0 - - - {3C19A734-11BB-48FD-81D0-042B6A8D4CFC} - mock-assembly-sl-5.0 - - - {A2B5D1FA-D865-4B30-A82D-30BB1C8C474E} - nunitlite.testdata-sl-5.0 - - - - - - - - - - - \ No newline at end of file diff --git a/test/NUnitLite/src/tests/nunitlite.tests.build b/test/NUnitLite/src/tests/nunitlite.tests.build deleted file mode 100644 index 62fea7e8a..000000000 --- a/test/NUnitLite/src/tests/nunitlite.tests.build +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/NUnitLiteRunner/NUnitLiteRunner.csproj b/test/NUnitLiteRunner/NUnitLiteRunner.csproj index e15541f5b..8ff1241eb 100644 --- a/test/NUnitLiteRunner/NUnitLiteRunner.csproj +++ b/test/NUnitLiteRunner/NUnitLiteRunner.csproj @@ -50,8 +50,12 @@ {46c5b3d9-45e8-46b6-89f7-837d52c6187a} MsgPack.UnitTest.Unity.Il2cpp.Full.Desktop - - {43b24dc5-16d6-45ef-93f1-b021b785a892} + + {7fa125b4-e377-4d4c-aecb-17b934e3a4b3} + nunit.framework-3.5 + + + {82f93f6e-5c10-4cc7-bc65-ac0b9ca6d39a} nunitlite-3.5 diff --git a/test/NUnitLiteRunner/Program.cs b/test/NUnitLiteRunner/Program.cs index 3e9df6d9c..2c346534e 100644 --- a/test/NUnitLiteRunner/Program.cs +++ b/test/NUnitLiteRunner/Program.cs @@ -24,7 +24,9 @@ using MsgPack.Serialization; -using NUnitLite.Runner; +using NUnit.Common; + +using NUnitLite; namespace MsgPack.NUnitLiteRunner { @@ -41,7 +43,7 @@ private static void Main( string[] args ) adjustedArgs.AddRange( args ); adjustedArgs.Add( AssemblyName ); PreHeat(); - new TextUI().Execute( adjustedArgs.ToArray() ); + new TextRunner().Execute( adjustedArgs.ToArray() ); } [MethodImpl( MethodImplOptions.NoOptimization )] diff --git a/test/RoslynAnalyzerUnitTestExplorer.ttinclude b/test/RoslynAnalyzerUnitTestExplorer.ttinclude index fbaf36e4a..af8b9c871 100644 --- a/test/RoslynAnalyzerUnitTestExplorer.ttinclude +++ b/test/RoslynAnalyzerUnitTestExplorer.ttinclude @@ -11,6 +11,7 @@ <#@ import namespace="System.Globalization" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> +<#@ import namespace="System.Text.RegularExpressions" #> <#@ import namespace="System.Threading.Tasks" #> <#@ import namespace="Microsoft.CodeAnalysis" #> <#@ import namespace="Microsoft.CodeAnalysis.CSharp" #> @@ -61,6 +62,11 @@ private class TestClassExplorer /// > private readonly string _testSkippingAttributeFullName; + /// + /// The type full name of "test case" inidicator attribute type. + /// > + private readonly string _testCaseAttributeFullName; + /// /// The array of type full names of attributes which should mark significant methods including test method, setup method, etc. /// > @@ -76,10 +82,11 @@ private class TestClassExplorer /// The type full name of "per test setip routine" inidicator attribute type. /// The type full name of "per test cleanup routine" inidicator attribute type. /// The type full name of "skipping specified test" inidicator attribute type. + /// The type full name of "test case" inidicator attribute type. public TestClassExplorer( string testClassAttributeFullName, string testMethodAttributeFullName, string fixtureSetupAttributeFullName, string fixtureCleanupAttributeFullName, string testSetupAttributeFullName, string testCleanupAttributeFullName, - string testSkippingAttributeFullName + string testSkippingAttributeFullName, string testCaseAttributeFullName ) { this._testClassAttributeFullName = testClassAttributeFullName; @@ -89,6 +96,7 @@ private class TestClassExplorer this._testSetupAttributeFullName = testSetupAttributeFullName; this._testCleanupAttributeFullName = testCleanupAttributeFullName; this._testSkippingAttributeFullName = testSkippingAttributeFullName; + this._testCaseAttributeFullName = testCaseAttributeFullName; this._significantMethodAttributeFullNames = new [] { testMethodAttributeFullName, fixtureSetupAttributeFullName, fixtureCleanupAttributeFullName, testSetupAttributeFullName, testCleanupAttributeFullName }; } @@ -109,7 +117,8 @@ private class TestClassExplorer "NUnit.Framework.TestFixtureTearDownAttribute", "NUnit.Framework.SetUpAttribute", "NUnit.Framework.TearDownAttribute", - "NUnit.Framework.IgnoreAttribute" + "NUnit.Framework.IgnoreAttribute", + "NUnit.Framework.TestCaseAttribute" ); } @@ -166,8 +175,13 @@ private class TestClassExplorer g.Where( x => x.member.GetAttributes().Any( a => GetAttributeName( a ) == this._testMethodAttributeFullName ) // Only test methods && x.member.GetAttributes().All( a => GetAttributeName( a ) != this._testSkippingAttributeFullName ) // Excludes "Ignored" method - ).Select( x => new TestMethod( x.member.Name ) ) - .OrderBy( x => x.Name ) + ).Select( x => + new TestMethod( + x.member.Name, + // only test data from attribute constructor arguments are supported. + x.member.GetAttributes().Where( a => GetAttributeName( a ) == this._testCaseAttributeFullName ).Select( a => GetTestData( a ) ).ToArray() + ) + ).OrderBy( x => x.Name ) ) { FixtureSetup = GetSpecialMethodName( g.Select( x => x.member ), this._fixtureSetupAttributeFullName ), @@ -198,6 +212,115 @@ private class TestClassExplorer return attribute.AttributeClass.ToDisplayString( QualifiedNameOnlyFormat ); } + /// + /// Gets test data for specified "test case". + /// + /// The attribute. + /// + /// The test data for the case. The element should be primitive value types, string or null. + /// + private static string[] GetTestData( AttributeData attribute ) + { + TypedConstant[] constructorArguments = attribute.ConstructorArguments.ToArray(); + switch ( constructorArguments.Length ) + { + case 1: + { + if ( constructorArguments[ 0 ].Kind == TypedConstantKind.Array ) + { + // [Attr(new object[]{ a, b, c })] + // Returns array's content (Values is IEnumerable) + return constructorArguments[ 0 ].Values.Select( ToCSharpLiteral ).ToArray(); + } + else + { + goto default; + } + } + default: + { + // [Attr( a, b, c )] + return constructorArguments.Select( ToCSharpLiteral ).ToArray(); + } + } + } + + /// + /// Converts a Roslyn to a C# literal representation. + /// + /// A Roslyn . + /// A C# literal representation. + private static string ToCSharpLiteral( TypedConstant constant ) + { + if ( constant.IsNull ) + { + return "null"; + } + + switch( constant.Kind ) + { + case TypedConstantKind.Enum: + { + var value = constant.Value.ToString(); + if ( Regex.IsMatch( value, @"^\d+$" ) ) + { + return "( " + constant.Type.Name + " )" + constant.Value; + } + else + { + return constant.Type.Name + "." + constant.Value; + } + } + case TypedConstantKind.Type: + { + // TODO: generic type + return "typeof( " + constant.Value + " )"; + } + case TypedConstantKind.Primitive: + { + switch( Type.GetTypeCode( constant.Value.GetType() ) ) + { + case TypeCode.String: + { + return "@\"" + constant.Value.ToString().Replace( "\"", "\"\"" ) + "\""; + } + case TypeCode.Char: + { + return "'" + constant.Value + "'"; + } + case TypeCode.Int64: + { + return constant.Value + "L"; + } + case TypeCode.UInt32: + { + return constant.Value + "U"; + } + case TypeCode.UInt64: + { + return constant.Value + "UL"; + } + case TypeCode.Single: + { + return constant.Value + "F"; + } + case TypeCode.Decimal: + { + return constant.Value + "M"; + } + default: + { + return constant.Value.ToString(); + } + } + } + default: + { + return "__ERROR(" + constant.Kind + ")__"; + } + } + } + /// /// Gets the name of the special method which marked with specified attribute. /// diff --git a/test/Xamarin.Android.Common.props b/test/Xamarin.Android.Common.props new file mode 100644 index 000000000..78a8ae86c --- /dev/null +++ b/test/Xamarin.Android.Common.props @@ -0,0 +1,96 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + Library + Properties + MsgPack + 512 + True + Resources\Resource.Designer.cs + Resource + Off + false + v2.3 + Properties\AndroidManifest.xml + Resources + Assets + false + + + + + $(DefineConstants);TRACE;AOT;XAMARIN;NUNITLITE;NETSTANDARD2_0;FEATURE_TAP;FEATURE_CONCURRENT;FEATURE_POINTER_CONVERSION;FEATURE_MEMCOPY + prompt + 4 + 512M + false + true + Full + $(AssemblyName);Xamarin.Android.NUnitLite + true + false + true + false + + + true + Full + False + bin\Debug\ + $(DefineConstants);DEBUG + false + + + PdbOnly + True + bin\Release\ + true + + + + + + + + + + + + + Properties\AssemblyInfo.cs + + + MainActivity.cs + + + + + MsgPack.snk + + + cases.mpac + + + cases_compact.mpac + + + Resources\AboutResources.txt + + + Assets\AboutAssets.txt + + + + + + + + {5bcec32e-990e-4de5-945f-bd27326a7418} + MsgPack + + + \ No newline at end of file diff --git a/test/Xamarin.iOS.Common.props b/test/Xamarin.iOS.Common.props new file mode 100644 index 000000000..143861240 --- /dev/null +++ b/test/Xamarin.iOS.Common.props @@ -0,0 +1,127 @@ + + + + iPhoneSimulator + Exe + Resources + Properties + true + ..\src\MsgPack.snk + + + + + $(DefineConstants);AOT;XAMARIN;NUNITLITE;NETSTANDARD2_0;FEATURE_TAP;FEATURE_CONCURRENT;FEATURE_POINTER_CONVERSION;FEATURE_MEMCOPY + + + 9.3 + false + False + False + True + False + False + False + False + True + --xml=${ProjectDir}/linker.xml + False + false + Default + HttpClientHandler + False + + + Entitlements.plist + false + None + + + true + + ARMv7 + + + + + Entitlements.plist + false + Full + + + iPhone Developer + + + iPhone Developer + + + true + Automatic:AdHoc + iPhone Distribution + + + Automatic:AppStore + iPhone Distribution + + + + + + + + + + + + + + + + + MsgPack.snk + + + cases.mpac + + + cases_compact.mpac + + + + + + Properties\AssemblyInfo.cs + + + AppDelegate.cs + + + Main.cs + + + + + cases.json + + + Resources\Default-568h%402x.png + + + Resources\Default.png + + + Resources\Default%402x.png + + + + + Designer + + + + + {5bcec32e-990e-4de5-945f-bd27326a7418} + MsgPack + + + \ No newline at end of file diff --git a/tools/MakeCert/New-TestCerft.ps1 b/tools/MakeCert/New-TestCerft.ps1 new file mode 100644 index 000000000..abb42dcef --- /dev/null +++ b/tools/MakeCert/New-TestCerft.ps1 @@ -0,0 +1,49 @@ +<# +.SYNOPSIS +Make test certificate for UWP unit test programs. +.PARAMETER FilePath +Specify output file path. Default is "./testcert.pfx" +.DESCRIPTION +This script makes self-signed certificates for code signing with CN=MsgPack.Cli.UnitTest, RSA256, SHA256 with maximum expiry date. +Note that the pfx file has empty password. +#> +#requires -Version 5.1 + +using namespace System.IO +using namespace System.Security.Cryptography +using namespace System.Security.Cryptography.X509Certificates + +[CmdletBinding(PositionalBinding = $false)] +param( + [ValidateNotNullOrEmpty()][string]$FilePath = "./testcert.pfx" +) + +Set-StrictMode -Version 5.1 + +[string]$subject = "CN=MsgPack.Cli.UnitTest" +[RSA]$password = [RSA]::Create(2048) +[HashAlgorithmName]$hashAlgorithm = [HashAlgorithmName]::SHA256 +[RSASignaturePadding]$padding = [RSASignaturePadding]::Pkcs1 +[DateTimeOffset]$notBefore = [System.DateTimeOffset]::new(2019, 10, 1, 0, 0, 0, 0) +# Some implementation has year 2037 problem, they cannot accept date after 2038/01/19. +[DateTimeOffset]$notAfter = [System.DateTimeOffset]::FromUnixTimeSeconds([Int32]::MaxValue) + +# Try load CertificateRequest type dinamically to support multiple platforms... +$certReqType = [System.Linq.Enumerable].Assembly.GetType("System.Security.Cryptography.X509Certificates.CertificateRequest") +if ($null -eq $certReqType) { + # This should be pwsh + $certReqType = [X509Certificate].Assembly.GetType("System.Security.Cryptography.X509Certificates.CertificateRequest") + if ($null -eq $certReqType) { + throw [PlatformNotSupportedException]::new("pwsh, or PowerShell with .NET Framework 4.7.2 or later is required."); + } +} + +# Create CertificateRequest instance +$certReq = $certReqType::new($subject, $password, $hashAlgorithm, $padding) +# This cert is for code signing: +$certReq.CertificateExtensions.Add([X509EnhancedKeyUsageExtension]::new([X509Extension]::new([Oid]::FromOidValue("2.5.29.37", [OidGroup]::All ), @(48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 3), $true), $true)) +# This cert is end entity: 2.5.29.19, {48,0}, critical. +$certReq.CertificateExtensions.Add([X509BasicConstraintsExtension]::new([X509Extension]::new([Oid]::FromOidValue("2.5.29.19", [OidGroup]::All ), @(48, 0), $true), $true)) + +[X509Certificate2]$cert = $certReq.CreateSelfSigned($notBefore, $notAfter) +[File]::WriteAllBytes($FilePath, $cert.Export([X509ContentType]::Pfx, [String]::Empty)) diff --git a/tools/SyncProjects/SyncProjects.sln b/tools/SyncProjects/SyncProjects.sln deleted file mode 100644 index 1c7c0ae7d..000000000 --- a/tools/SyncProjects/SyncProjects.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyncProjects", "SyncProjects\SyncProjects.csproj", "{108079AF-D248-4351-8D9E-2D9A12625673}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x86 = Debug|x86 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {108079AF-D248-4351-8D9E-2D9A12625673}.Debug|x86.ActiveCfg = Debug|x86 - {108079AF-D248-4351-8D9E-2D9A12625673}.Debug|x86.Build.0 = Debug|x86 - {108079AF-D248-4351-8D9E-2D9A12625673}.Release|x86.ActiveCfg = Release|x86 - {108079AF-D248-4351-8D9E-2D9A12625673}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/tools/SyncProjects/SyncProjects/.gitignore b/tools/SyncProjects/SyncProjects/.gitignore deleted file mode 100644 index 25b71e44a..000000000 --- a/tools/SyncProjects/SyncProjects/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -bin/ -Bin/ \ No newline at end of file diff --git a/tools/SyncProjects/SyncProjects/Program.cs b/tools/SyncProjects/SyncProjects/Program.cs deleted file mode 100644 index 6a06bdd4c..000000000 --- a/tools/SyncProjects/SyncProjects/Program.cs +++ /dev/null @@ -1,405 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text.RegularExpressions; -using System.Xml; -using System.Xml.Linq; -using NDesk.Options; - -namespace SyncProjects -{ - // TODO: This tool might not work for Empty destination projects. - class Program - { - private const string Ns = "{http://schemas.microsoft.com/developer/msbuild/2003}"; - - static int Main( string[] args ) - { - var file = "Sync.xml"; - var sourceBasePath = "src" + Path.DirectorySeparatorChar; - var projectExtension = ".csproj"; - bool help = false; - - var options = - new OptionSet - { - { "d|def=", "File path to synchronization definition. Default: Sync.xml", v => file = v }, - { "s|src=", "File path to base directory of source tree. Default: src" + Path.DirectorySeparatorChar, v => sourceBasePath = v }, - { "e|ext=", "Extension (including leading dot) of the project file. Default: .csproj", v => projectExtension = v }, - { "h|?|help", "Show this help.", _ => help = true }, - }; - - options.Parse( args ); - if ( help ) - { - Console.WriteLine( "SyncProjects" ); - Console.WriteLine(); - Console.WriteLine( "Usage: SyncProjects.exe []" ); - Console.WriteLine(); - Console.WriteLine( "Options:" ); - options.WriteOptionDescriptions( Console.Out ); - return 0; - } - - try - { - SynchronizeProjects( file, sourceBasePath, projectExtension ); - return 0; - } - catch ( Exception ex ) - { - Console.Error.WriteLine( ex ); - return Marshal.GetHRForException( ex ); - } - } - - private static readonly XElement EmptyExcludes = new XElement( "Excludes" ); - - private static void SynchronizeProjects( string syncFilePath, string sourceBasePath, string projectFileExtension ) - { - var sync = XDocument.Load( syncFilePath ); - if ( sync.Root == null || sync.Root.Name.LocalName != "ProjectSync" ) - { - throw new XmlException( "Invalid sync file." ); - } - - foreach ( var project in - sync.Root.Elements( "Project" ) - .Select( p => - new - { - Name = p.Attribute( "Name" ), - Base = p.Attribute( "Base" ), - Includes = - p.Elements( "Include" ) - .Select( ToPattern ).Where( pattern => pattern != null ).ToArray(), - Excludes = - p.Elements( "Exclude" ) - .Select( ToPattern ).Where( pattern => pattern != null ).ToArray(), - Preserves = - p.Elements( "Preserve" ) - .Select( ToPattern ).Where( pattern => pattern != null ).ToArray() - } - ) ) - { - var projectFilePath = Path.Combine( sourceBasePath, project.Name.Value, project.Name.Value + projectFileExtension ); - var projectXml = XDocument.Load( projectFilePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo ); - if ( projectXml.Root == null || projectXml.Root.Name.LocalName != "Project" ) - { - throw new XmlException( "Invalid project file :" + projectFilePath ); - } - - var baseProjectFilePath = Path.Combine( sourceBasePath, project.Base.Value, project.Base.Value + projectFileExtension ); - var baseProjectXml = XDocument.Load( baseProjectFilePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo ); - if ( baseProjectXml.Root == null || baseProjectXml.Root.Name.LocalName != "Project" ) - { - throw new XmlException( "Invalid project file :" + baseProjectFilePath ); - } - - var relativePath = - GetRelativePath( - Path.GetDirectoryName( projectFilePath ), - Path.GetDirectoryName( baseProjectFilePath ) - ); - - var targetItemGroups = - baseProjectXml.Root - .Elements( Ns + "ItemGroup" ) - .Select( ig => - { - ig.Elements() - .Where( - e => - e.Attribute( "Include" ) != null - && project.Excludes.Any( excludes => - e.Element( Ns + "Link" ) != null - ? Regex.IsMatch( e.Element( Ns + "Link" ).Value, excludes ) - : Regex.IsMatch( e.Attribute( "Include" ).Value, excludes ) - ) - ).Remove(); - return ig; - } - ).Where( ig => ig.Elements().Any() ) - .Select( e => new ItemGroup( e ) ); - var baseItemGroups = baseProjectXml.Root.Elements( Ns + "ItemGroup" ).SelectMany( ig => ig.Elements() ).ToLookup( e => e.Name.LocalName ); - - var existingItemGroups = - projectXml.Root.Elements( Ns + "ItemGroup" ) - .Where( e => e.HasElements ) - .Select( e => new ItemGroup( e ) ) - .ToDictionaryDebuggable( e => e.Key, projectFilePath ); - foreach ( var itemGroup in targetItemGroups ) - { - switch ( itemGroup.Key ) - { - case "Compile": - case "Content": - case "None": - { - // If there are no for current type, then create new type and register it to the document and bookkeeping. - XElement destinationElement; - ItemGroup destinationGroup; - if ( existingItemGroups.TryGetValue( itemGroup.Key, out destinationGroup ) ) - { - destinationElement = destinationGroup.Element; - } - else - { - destinationElement = new XElement( Ns + "ItemGroup" ); - // insert to the destination DOM - projectXml.Root.Elements( Ns + "ItemGroup" ).Last().AddAfterSelf( destinationElement ); - // bookkeeping - existingItemGroups.Add( itemGroup.Key, new ItemGroup( destinationElement, itemGroup.Key ) ); - } - - CopyItemGroup( - itemGroup.Key, - baseItemGroups[ itemGroup.Key ], - destinationElement, - relativePath, - project.Includes, - project.Excludes, - project.Preserves - ); - break; - } - } - } - - // Avoid empty ItemGroups - projectXml.Root.Elements( Ns + "ItemGroup" ).Where( ig => !ig.HasElements ).Remove(); - - projectXml.Save( projectFilePath ); - } - } - - private static void CopyItemGroup( string elementName, IEnumerable sourceItems, XElement destinationItemGroup, string relativePath, IEnumerable includings, IEnumerable excludings, IEnumerable preservings ) - { - var remaining = - destinationItemGroup.Elements( Ns + elementName ) - .Where( e => - e.Attribute( "Include" ) != null && - preservings.Any( preserves => - e.Element( Ns + "Link" ) != null - ? Regex.IsMatch( e.Element( Ns + "Link" ).Value, preserves ) - : Regex.IsMatch( e.Attribute( "Include" ).Value, preserves ) - ) - ).Select( e => new XElement( e ) ) - .ToArray(); - - var appendings = - sourceItems - .Where( e => - e.Attribute( "Include" ) != null && - includings.Any( includes => - Regex.IsMatch( e.Attribute( "Include" ).Value, includes ) - ) - ).Select( e => CreateCopyingElement( relativePath, e ) ) - .ToArray(); - - destinationItemGroup.Elements( Ns + elementName ).Remove(); - - var adding = new Dictionary(); - - foreach ( var item in - sourceItems.Where( e => - e.Attribute( "Include" ) != null && - !excludings.Any( excludes => - e.Element( Ns + "Link" ) != null - ? Regex.IsMatch( e.Element( Ns + "Link" ).Value, excludes ) - : Regex.IsMatch( e.Attribute( "Include" ).Value, excludes ) - ) && - !preservings.Any( preserves => - e.Element( Ns + "Link" ) != null - ? Regex.IsMatch( e.Element( Ns + "Link" ).Value, preserves ) - : Regex.IsMatch( e.Attribute( "Include" ).Value, preserves ) - ) - ).Select( copying => - CreateCopyingElement( relativePath, copying ) - ).Concat( remaining ).Concat( appendings ) ) - { - var itemPath = item.Attribute( "Include" ).Value; - if ( !adding.ContainsKey( itemPath ) ) - { - adding.Add( itemPath, item ); - } - } - - // To stable order, sort with their "display path". - destinationItemGroup.Add( - adding.OrderBy( kv => - ( kv.Value.Element( "Link" ) == null ? kv.Key : kv.Value.Element( "Link" ).Value ), - StringComparer.OrdinalIgnoreCase - ).Select( kv => kv.Value ) - ); - } - - private static XElement CreateCopyingElement( string relativePath, XElement copying ) - { - return - copying.Element( Ns + "Link" ) != null - ? new XElement( copying ) - : new XElement( - copying.Name, - new XAttribute( - "Include", - Path.Combine( relativePath, copying.Attribute( "Include" ).Value ) - ), - new XElement( Ns + "Link", copying.Attribute( "Include" ).Value ) - ); - } - - #region String Utlities - - private static readonly char[] DirectorySeparators = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; - private static readonly string DirectorySeparatorPattern = - "(" + Regex.Escape( Path.AltDirectorySeparatorChar.ToString() ) + "|" + Regex.Escape( Path.DirectorySeparatorChar.ToString() ) + ")"; - - private static string ToPattern( XElement xml ) - { - var file = xml.Attribute( "File" ); - var path = xml.Attribute( "Path" ); - if ( file == null && path == null ) - { - return null; - } - - if ( file == null ) - { - return - "^" + - String.Join( - DirectorySeparatorPattern, - path.Value.Split( DirectorySeparators, StringSplitOptions.RemoveEmptyEntries ).Select( ToPathRegex ) - ) + - "$"; - } - else - { - var filePattern = ToFileRegex( ( file.Value ) ); - return "(^" + filePattern + "|" + DirectorySeparatorPattern + filePattern + ")$"; - } - } - - private static string ToPathRegex( string wildcard ) - { - // Wildcard in path should not contain directory separator. - return Regex.Escape( wildcard ).Replace( "\\*\\*", ".*" ).Replace( "\\*", @"[^\\]*" ).Replace( "\\?", @"[^\\]" ); - } - - private static string ToFileRegex( string wildcard ) - { - return Regex.Escape( wildcard ).Replace( "\\*", ".*" ).Replace( "\\?", "." ); - } - - private static string GetRelativePath( string fromPath, string toPath ) - { - var fromPathSegments = fromPath.Split( DirectorySeparators, StringSplitOptions.RemoveEmptyEntries ); - var toPathSegments = toPath.Split( DirectorySeparators, StringSplitOptions.RemoveEmptyEntries ); - var sameTo = 0; - for ( ; sameTo < fromPathSegments.Length && sameTo < toPathSegments.Length; sameTo++ ) - { - if ( !fromPathSegments[ sameTo ].Equals( toPathSegments[ sameTo ], StringComparison.OrdinalIgnoreCase ) ) - { - break; - } - } - - return String.Join( Path.DirectorySeparatorChar.ToString( CultureInfo.InvariantCulture ), Enumerable.Repeat( "..", fromPathSegments.Length - sameTo ).Concat( toPathSegments.Skip( sameTo ) ) ); - } - - #endregion - - private class ItemGroup - { - public readonly XElement Element; - public readonly string Key; - - public ItemGroup( XElement newItemGroup, string key ) - { - this.Element = newItemGroup; - this.Key = key; - } - - public ItemGroup( XElement itemGroup ) - { - this.Element = itemGroup; - try - { - this.Key = itemGroup.Elements().Select( e => e.Name.LocalName ).Distinct().Single(); - } - catch ( InvalidOperationException ) - { - var lineInfo = ( ( itemGroup ) as IXmlLineInfo ?? NullXmlLineInfo.Instance ); - throw new InvalidOperationException( - String.Format( - CultureInfo.CurrentCulture, - "ItemGroup at line {0} of xml file '{1}' contains hetro genious children [{2}].", - lineInfo.LineNumber, - itemGroup.Document.BaseUri, - String.Join( ", ", itemGroup.Elements().Select( e => e.Name.LocalName ).Distinct() ) - ) - ); - } - } - } - - private sealed class NullXmlLineInfo : IXmlLineInfo - { - public static readonly NullXmlLineInfo Instance = new NullXmlLineInfo(); - - public bool HasLineInfo() - { - return false; - } - - public int LineNumber - { - get { return -1; } - } - - public int LinePosition - { - get { return -1; } - } - } - - } - - internal static class EnumerableEx - { - public static Dictionary ToDictionaryDebuggable( - this IEnumerable source, - Func keySelector, - string filePath - ) - { - var dictionary = new Dictionary(); - foreach ( var item in source ) - { - var key = keySelector( item ); - try - { - dictionary.Add( key, item ); - } - catch ( ArgumentException ex ) - { - throw new InvalidOperationException( - String.Format( - CultureInfo.CurrentCulture, - "Failed to process file '{0}'. Key '{1}' is duplicated.", - filePath, - key - ), - ex - ); - } - } - - return dictionary; - } - } -} diff --git a/tools/SyncProjects/SyncProjects/Properties/AssemblyInfo.cs b/tools/SyncProjects/SyncProjects/Properties/AssemblyInfo.cs deleted file mode 100644 index a6836ca9f..000000000 --- a/tools/SyncProjects/SyncProjects/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 -// アセンブリに関連付けられている情報を変更するには、 -// これらの属性値を変更してください。 -[assembly: AssemblyTitle( "SyncProjects" )] -[assembly: AssemblyDescription( "" )] -[assembly: AssemblyConfiguration( "" )] -[assembly: AssemblyCompany( "" )] -[assembly: AssemblyProduct( "SyncProjects" )] -[assembly: AssemblyCopyright( "Copyright © 2012" )] -[assembly: AssemblyTrademark( "" )] -[assembly: AssemblyCulture( "" )] - -// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから -// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 -// その型の ComVisible 属性を true に設定してください。 -[assembly: ComVisible( false )] - -// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です -[assembly: Guid( "d2faf749-ec6a-402b-b34c-586df0860f0b" )] - -// アセンブリのバージョン情報は、以下の 4 つの値で構成されています: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を -// 既定値にすることができます: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion( "1.0.0.0" )] -[assembly: AssemblyFileVersion( "1.0.0.0" )] diff --git a/tools/SyncProjects/SyncProjects/SyncProjects.csproj b/tools/SyncProjects/SyncProjects/SyncProjects.csproj deleted file mode 100644 index d961a418b..000000000 --- a/tools/SyncProjects/SyncProjects/SyncProjects.csproj +++ /dev/null @@ -1,63 +0,0 @@ - - - - Debug - x86 - 8.0.30703 - 2.0 - {108079AF-D248-4351-8D9E-2D9A12625673} - Exe - Properties - SyncProjects - SyncProjects - v4.0 - Client - 512 - - - x86 - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x86 - pdbonly - true - ..\bin\ - TRACE - prompt - 4 - - - - ..\packages\NDesk.Options.0.2.1\lib\NDesk.Options.dll - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/SyncProjects/SyncProjects/packages.config b/tools/SyncProjects/SyncProjects/packages.config deleted file mode 100644 index c8ff80e88..000000000 --- a/tools/SyncProjects/SyncProjects/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tools/SyncProjects/bin/NDesk.Options.dll b/tools/SyncProjects/bin/NDesk.Options.dll deleted file mode 100644 index df4587895..000000000 Binary files a/tools/SyncProjects/bin/NDesk.Options.dll and /dev/null differ diff --git a/tools/SyncProjects/bin/SyncProjects.exe b/tools/SyncProjects/bin/SyncProjects.exe deleted file mode 100644 index a80b9d222..000000000 Binary files a/tools/SyncProjects/bin/SyncProjects.exe and /dev/null differ diff --git a/tools/SyncProjects2/.editorconfig b/tools/SyncProjects2/.editorconfig new file mode 100644 index 000000000..7a39d2421 --- /dev/null +++ b/tools/SyncProjects2/.editorconfig @@ -0,0 +1,89 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +# Note: T4 Editor cannot handle non-CRLF, so locally use CRLF and push as LF via git +end_of_line = crlf +insert_final_newline = true + +# Matches multiple files with brace expansion notation +# Set default charset +[*] +charset = utf-8 + +# 4 width tab indentation +[*.{cs,tt,ttinclude}] +indent_style = tab +tab_width = 4 + +# 2 space indentation +[*.{xml,csproj}] +indent_style = space +indent_size = 2 + +# From https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference +# and https://github.com/dotnet/roslyn/blob/master/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs +[*.cs] +dotnet_style_qualification_for_field = true:warning +dotnet_style_qualification_for_property = true:warning +dotnet_style_qualification_for_method = true:warning +dotnet_style_qualification_for_event = true:warning +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = false:warning +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_coalesce_expression = true:warning +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion +dotnet_sort_system_directives_first = true +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = true +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = true +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_parentheses = expressions,type_casts,control_flow_statements +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_cast = false +csharp_space_around_declaration_statements = true +csharp_space_before_open_square_brackets = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_square_brackets = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_semicolon_in_for_statement = true +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_around_binary_operators = true +csharp_indent_braces = false +csharp_indent_block_contents = true +csharp_indent_switch_labels = true +csharp_indent_case_contents = false +csharp_indent_labels = false +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Disabled for Unity compatibility until 2017.1 RTM +[*.cs] +dotnet_style_null_propagation = false:warning +csharp_style_expression_bodied_methods = true:suggestion +csharp_style_expression_bodied_constructors = true:suggestion +csharp_style_expression_bodied_operators = true:suggestion +csharp_style_expression_bodied_properties = true:suggestion +csharp_style_expression_bodied_indexers = true:suggestion +csharp_style_expression_bodied_accessors = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion diff --git a/tools/SyncProjects2/.gitignore b/tools/SyncProjects2/.gitignore new file mode 100644 index 000000000..cd42ee34e --- /dev/null +++ b/tools/SyncProjects2/.gitignore @@ -0,0 +1,2 @@ +bin/ +obj/ diff --git a/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/MsgPack.Tools.Build.SyncProject.csproj b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/MsgPack.Tools.Build.SyncProject.csproj new file mode 100644 index 000000000..9162aacbe --- /dev/null +++ b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/MsgPack.Tools.Build.SyncProject.csproj @@ -0,0 +1,13 @@ + + + + netstandard1.5 + MsgPack + + + + + + + + \ No newline at end of file diff --git a/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/Glob.cs b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/Glob.cs new file mode 100644 index 000000000..e3ea2d7f2 --- /dev/null +++ b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/Glob.cs @@ -0,0 +1,108 @@ +#region -- License Terms -- +// MessagePack for CLI +// +// Copyright (C) 2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using Newtonsoft.Json; + +namespace MsgPack.Tools.Build +{ + /// + /// Represents glob information for project synchronizer. + /// + [JsonConverter( typeof( GlobJsonConverter ) )] + public struct Glob : IEquatable + { + /// + /// Gets the path. + /// + /// + /// The path glob pattern. + /// + public string Path { get; } + + /// + /// Gets the type. + /// + /// + /// The type of this entry. + /// + public GlobType Type { get; } + + /// + /// Initializes a new instance of the struct. + /// + /// The path glob pattern. + /// The type of this entry. + public Glob( string path, GlobType type ) + { + this.Path = path; + this.Type = type; + } + + /// + /// Determines whether the other object which is same type is equal to this instance or not. + /// + /// The object to be compared to this object. + /// + /// true, if the is equal to this instance; otherwise, false. + /// + public bool Equals( Glob other ) + => this.Path == other.Path && this.Type == other.Type; + + /// + /// Determines whether the specified , is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals( object obj ) + => ( obj is Glob other ) ? this.Equals( other ) : false; + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() + => ( this.Path?.GetHashCode() ).GetValueOrDefault() ^ this.Type.GetHashCode(); + + /// + /// Determines whether objects are equal to each other. + /// + /// A . + /// A . + /// + /// true, if the specified object are equal; otherwise, false. + /// + public static bool operator ==( Glob left, Glob right ) + => left.Equals( right ); + + /// + /// Determines whether objects are not equal to each other. + /// + /// A . + /// A . + /// + /// true, if the specified object are not equal; otherwise, false. + /// + public static bool operator !=( Glob left, Glob right ) + => !left.Equals( right ); + } +} diff --git a/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/GlobJsonConverter.cs b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/GlobJsonConverter.cs new file mode 100644 index 000000000..734511cf7 --- /dev/null +++ b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/GlobJsonConverter.cs @@ -0,0 +1,80 @@ +#region -- License Terms -- +// MessagePack for CLI +// +// Copyright (C) 2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using System.Diagnostics; +using Newtonsoft.Json; + +namespace MsgPack.Tools.Build +{ + /// + /// for structure. + /// + internal sealed class GlobJsonConverter : JsonConverter + { + public GlobJsonConverter() { } + + public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) + { + var target = ( Glob )value; + + writer.WriteStartObject(); + writer.WritePropertyName( "type" ); + writer.WriteValue( target.Type ); + writer.WritePropertyName( "path" ); + writer.WriteValue( target.Path ); + writer.WriteEndObject(); + } + + public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) + { + Debug.Assert( reader.TokenType == JsonToken.StartObject ); + var path = default( string ); + var type = default( GlobType? ); + var lastDepth = reader.Depth; + + while ( reader.Read() && reader.Depth > lastDepth ) + { + Debug.Assert( reader.TokenType == JsonToken.PropertyName ); + switch ( reader.Value as string ) + { + case "path": + { + path = reader.ReadAsString(); + break; + } + case "type": + { + type = ( GlobType )Enum.Parse( typeof( GlobType ), reader.ReadAsString(), ignoreCase: true ); + break; + } + } + } + + if ( path == null || type == null ) + { + throw new JsonSerializationException( "Both of 'path' and 'type' are required." ); + } + + return new Glob( path, type.Value ); + } + + public override bool CanConvert( Type objectType ) + => objectType == typeof( Glob ); + } +} diff --git a/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/GlobType.cs b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/GlobType.cs new file mode 100644 index 000000000..d7dd07387 --- /dev/null +++ b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/GlobType.cs @@ -0,0 +1,37 @@ +#region -- License Terms -- +// MessagePack for CLI +// +// Copyright (C) 2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + + +namespace MsgPack.Tools.Build +{ + /// + /// Represents type of the . + /// + public enum GlobType + { + /// + /// Indicates inclusion of the matched items. + /// + Include = 0, + + /// + /// Indicates exclusion of the matched items from inclusions. + /// + Remove + } +} diff --git a/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/ProjectSynchronizationDefinition.cs b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/ProjectSynchronizationDefinition.cs new file mode 100644 index 000000000..3bbe096ec --- /dev/null +++ b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/ProjectSynchronizationDefinition.cs @@ -0,0 +1,135 @@ +#region -- License Terms -- +// MessagePack for CLI +// +// Copyright (C) 2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Newtonsoft.Json; + +namespace MsgPack.Tools.Build +{ + /// + /// Defines project synchronization inputs. + /// + public sealed class ProjectSynchronizationDefinition + { + /// + /// Gets or sets the name of the target project. + /// + /// + /// The name of the target project. This value will be updated to full path when . + /// + [JsonProperty( "name" )] + public string TargetProjectName { get; set; } + + /// + /// Gets or sets the name of the base definition. + /// + /// + /// The name of the base definition. + /// + [JsonProperty( "base" )] + public string BaseDefinitionName { get; set; } + + private readonly IList> _baseGlobs = new List>(); + + /// + /// Gets the globs. + /// + /// + /// The globs. This value will not be null. + /// + [JsonProperty( "globs" )] + public IList Globs { get; } = new List(); + + /// + /// Initializes a new instance of the class. + /// + public ProjectSynchronizationDefinition() { } + + /// + /// Creates new instances from specified JSON data. + /// + /// The reader for JSON text. + /// A collection of deserialized . + public static IEnumerable FromJson( TextReader reader ) + => new JsonSerializer().Deserialize( new JsonTextReader( reader ) ); + + /// + /// Resolves the project names to full path with specified informations. + /// + /// The base directory of resolution. + /// The project file extension including leading dot. If the leading dot is missing, dot should be prepended. + /// + /// If the original matches mulitiple project files, the result is undefined. + /// This method updates properties. + /// + public void ResolveProjectName( string baseDirectory, string projectExtension ) + { + var realProjectExtension = projectExtension; + if ( realProjectExtension.FirstOrDefault() != '.' ) + { + realProjectExtension = '.' + realProjectExtension; + } + + foreach ( var candidate in Directory.GetFiles( baseDirectory, "*" + realProjectExtension, SearchOption.AllDirectories ) ) + { + var projectName = Path.GetFileNameWithoutExtension( candidate ); + if ( projectName == this.TargetProjectName ) + { + this.TargetProjectName = candidate; + } + } + } + + /// + /// Gets resolved globs for base definition hiearchy. + /// + /// Resolved globs for base definition hiearchy. + public IEnumerable GetResolvedGlobs() + => this._baseGlobs.Reverse().SelectMany( x => x ).Concat( this.Globs ); + + /// + /// Resolves base definition hiearchy. + /// + /// A delegate to get base definition by its name. + /// is null. + public void ResolveBase( Func baseResolver ) + { + if ( baseResolver == null ) + { + throw new ArgumentNullException( nameof( baseResolver ) ); + } + + this._baseGlobs.Clear(); + + var baseName = this.BaseDefinitionName; + while ( !String.IsNullOrEmpty( baseName ) ) + { + var baseDefinition = baseResolver( baseName ); + if ( baseDefinition != null ) + { + this._baseGlobs.Add( baseDefinition.Globs ); + } + + baseName = baseDefinition?.BaseDefinitionName; + } + } + } +} diff --git a/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/ProjectSynchronizer.cs b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/ProjectSynchronizer.cs new file mode 100644 index 000000000..1ce8688b1 --- /dev/null +++ b/tools/SyncProjects2/MsgPack.Tools.Build.SyncProject/Tools/Build/ProjectSynchronizer.cs @@ -0,0 +1,259 @@ +#region -- License Terms -- +// MessagePack for CLI +// +// Copyright (C) 2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml.Linq; +using Microsoft.Build.Construction; +using Microsoft.Build.Evaluation; + +namespace MsgPack.Tools.Build +{ + /// + /// Implements project synchronization + /// + public sealed class ProjectSynchronizer + { + private const string Ns = "{http://schemas.microsoft.com/developer/msbuild/2003}"; + private static readonly XName ItemGroup = Ns + "ItemGroup"; + private static readonly XName Compile = Ns + "Compile"; + private static readonly XName Link = Ns + "Link"; + private static readonly XName DependentUpon = Ns + "DependentUpon"; + private static readonly XName AutoGen = Ns + "AutoGen"; + private static readonly XName DesignTime = Ns + "DesignTime"; + private static readonly XName Include = XName.Get( "Include" ); + + private static readonly Encoding Utf8BomEncoding = new UTF8Encoding( encoderShouldEmitUTF8Identifier: true ); + + private readonly Project _inMemory; + private readonly XDocument _projectXml; + private readonly ProjectItemGroupElement _targetItemGroup; + + /// + /// Initializes a new instance of the class. + /// + /// The project XML. + /// The project file path to solve pathes. + /// is null. + public ProjectSynchronizer( XDocument project, string projectPath ) + { + this._projectXml = project ?? throw new ArgumentNullException( nameof( project ) ); + this._inMemory = new Project { FullPath = projectPath }; + + this._targetItemGroup = this._inMemory.Xml.CreateItemGroupElement(); + this._inMemory.Xml.AppendChild( this._targetItemGroup ); + this._inMemory.ReevaluateIfNecessary(); + } + + /// + /// Evaluates the specified globs and updates project states. + /// + /// The globs. + public void Evaluate( IEnumerable globs ) + { + foreach ( var glob in globs ?? Enumerable.Empty() ) + { + switch ( glob.Type ) + { + case GlobType.Include: + { + var include = this._inMemory.Xml.CreateItemElement( Compile.LocalName, glob.Path ); + this._targetItemGroup.AppendChild( include ); + break; + } + case GlobType.Remove: + { + var remove = this._inMemory.Xml.CreateItemElement( Compile.LocalName ); + remove.Remove = glob.Path; + this._targetItemGroup.AppendChild( remove ); + break; + } + } + } + } + + /// + /// Saves this instance to original location. + /// + /// The target . + public void Save( TextWriter writer ) + { + this._inMemory.ReevaluateIfNecessary(); + + var itemGroup = default( XElement ); + var removings = new List(); + var dependentUpons = new Dictionary(); + var autoGens = new HashSet(); + foreach ( var compile in this._projectXml.Root.Elements( ItemGroup ).Elements( Compile ) ) + { + if ( itemGroup == null ) + { + itemGroup = compile.Parent; + } + + removings.Add( compile ); + var dependentUpon = compile.Element( DependentUpon ); + if ( dependentUpon != null ) + { + dependentUpons[ compile.Attribute( Include ).Value ] = dependentUpon.Value; + } + + var autoGen = compile.Element( AutoGen ); + if ( autoGen != null ) + { + autoGens.Add( compile.Attribute( Include ).Value ); + } + } + + foreach ( var removing in removings ) + { + removing.Remove(); + } + + if ( itemGroup == null ) + { + itemGroup = new XElement( ItemGroup ); + this._projectXml.Root.Add( itemGroup ); + } + + var projectDirectory = Path.GetDirectoryName( this._inMemory.FullPath ); + var added = new HashSet(); + foreach ( var include in this._inMemory.GetItems( Compile.LocalName ).OrderBy( x => x.EvaluatedInclude ) ) + { + + // For old msbuild systems, replace '/' with '\'. + var pathToItem = include.EvaluatedInclude.Replace( '/', '\\' ); + + if ( !added.Add( pathToItem ) ) + { + // Skip duplicated. + continue; + } + + if ( include.EvaluatedInclude.StartsWith( ".." ) ) + { + itemGroup.Add( + new XElement( + Compile, + new XAttribute( Include, pathToItem ), + new XElement( + Link, + ToProjectRelativePath( pathToItem ) + ) + ) + ); + } + else + { + var compile = new XElement( Compile, new XAttribute( Include, pathToItem ) ); + if ( autoGens.Contains( pathToItem ) ) + { + compile.Add( + new XElement( AutoGen, "True" ), + new XElement( DesignTime, "True" ) + ); + } + + if ( dependentUpons.TryGetValue( pathToItem, out var dependentUpon ) ) + { + compile.Add( + new XElement( DependentUpon, dependentUpon ) + ); + } + + itemGroup.Add( compile ); + } + } + + this._projectXml.Save( writer ); + } + + private static string ToProjectRelativePath( string maybeRelativePath ) + { + if ( maybeRelativePath.EndsWith( "AssemblyInfo.cs" ) ) + { + return "Properties\\" + Path.GetFileName( maybeRelativePath ); + } + + var firstSeparator = maybeRelativePath.IndexOf( '\\' ); + var secondSeparator = maybeRelativePath.IndexOf( '\\', firstSeparator + 1 ); + if ( secondSeparator < 0 ) + { + return Path.GetFileName( maybeRelativePath ); + } + + return maybeRelativePath.Substring( secondSeparator + 1 ); + } + + /// + /// Loads the base globs from specified project file. + /// + /// The project. + /// Globs. This value will not be null. + /// is null. + public static IEnumerable LoadBaseGlobs( Project project ) + => ( project ?? throw new ArgumentNullException( nameof( project ) ) ) + .GetItems( Compile.LocalName ) + .Where( x => !String.IsNullOrEmpty( x.Xml.Remove ) && !String.IsNullOrEmpty( x.Xml.Include ) ) + .Select( x => + !String.IsNullOrEmpty( x.Xml.Remove ) + ? new Glob( x.Xml.Remove, GlobType.Remove ) + : new Glob( x.Xml.Include, GlobType.Include ) + ); + + /// + /// Do project synchronization with the specified definition. + /// + /// The definition. + /// Global properties. + /// is null. + public static void Synchronize( ProjectSynchronizationDefinition definition, IDictionary globalProperties ) + { + if ( definition == null ) + { + throw new ArgumentNullException( nameof( definition ) ); + } + + var baseProject = new Project(); + foreach ( var property in globalProperties ) + { + baseProject.SetGlobalProperty( property.Key, property.Value ); + } + + var baseGlobs = LoadBaseGlobs( baseProject ); + var synchronizer = + new ProjectSynchronizer( + XDocument.Load( definition.TargetProjectName, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo ), + Path.GetFullPath( definition.TargetProjectName ) + ); + synchronizer.Evaluate( baseGlobs.Concat( definition.GetResolvedGlobs() ) ); + + using ( var stream = new MemoryStream() ) + using ( var writer = new StreamWriter( stream, Utf8BomEncoding ) ) + { + synchronizer.Save( writer ); + writer.Flush(); + + File.WriteAllBytes( definition.TargetProjectName, stream.ToArray() ); + } + } + } +} diff --git a/tools/SyncProjects2/SyncProjects2.sln b/tools/SyncProjects2/SyncProjects2.sln new file mode 100644 index 000000000..97b618d1f --- /dev/null +++ b/tools/SyncProjects2/SyncProjects2.sln @@ -0,0 +1,48 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.16 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsgPack.Tools.Build.SyncProject", "MsgPack.Tools.Build.SyncProject\MsgPack.Tools.Build.SyncProject.csproj", "{2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SyncProjects2", "SyncProjects2\SyncProjects2.csproj", "{34B439D3-459E-4041-B4A3-FFFF70A613E6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Debug|x64.ActiveCfg = Debug|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Debug|x64.Build.0 = Debug|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Debug|x86.ActiveCfg = Debug|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Debug|x86.Build.0 = Debug|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Release|Any CPU.Build.0 = Release|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Release|x64.ActiveCfg = Release|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Release|x64.Build.0 = Release|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Release|x86.ActiveCfg = Release|Any CPU + {2CD19747-0108-46C2-A0A3-6F7D3FE46BC2}.Release|x86.Build.0 = Release|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Debug|x64.ActiveCfg = Debug|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Debug|x64.Build.0 = Debug|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Debug|x86.ActiveCfg = Debug|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Debug|x86.Build.0 = Debug|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Release|Any CPU.Build.0 = Release|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Release|x64.ActiveCfg = Release|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Release|x64.Build.0 = Release|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Release|x86.ActiveCfg = Release|Any CPU + {34B439D3-459E-4041-B4A3-FFFF70A613E6}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/tools/SyncProjects2/SyncProjects2/Program.cs b/tools/SyncProjects2/SyncProjects2/Program.cs new file mode 100644 index 000000000..481c97d3a --- /dev/null +++ b/tools/SyncProjects2/SyncProjects2/Program.cs @@ -0,0 +1,98 @@ +#region -- License Terms -- +// MessagePack for CLI +// +// Copyright (C) 2015 FUJIWARA, Yusuke +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Mono.Options; +using MsgPack.Tools.Build; + +namespace SyncProject2 +{ + internal static class Program + { + private static int Main( string[] args ) + { + try + { + var file = "Sync.json"; + var sourceBasePath = "src" + Path.DirectorySeparatorChar; + var projectExtension = ".csproj"; + var msbuildExtensionsPath = Environment.ExpandEnvironmentVariables( @"%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild" ); + var help = false; + + var options = + new OptionSet + { + { "d|def=", "File path to synchronization definition. Default: Sync.xml", v => file = v }, + { "s|src=", "File path to base directory of source tree. Default: src" + Path.DirectorySeparatorChar, v => sourceBasePath = v }, + { "e|ext=", "Extension (including leading dot) of the project file. Default: .csproj", v => projectExtension = v }, + { "msbuild-ext-path=", "Specify MSBuild extensions path. Default is \\MSBuild.", v => msbuildExtensionsPath = v }, + { "h|?|help", "Show this help.", _ => help = true }, + }; + + options.Parse( args ); + if ( help ) + { + Console.Error.WriteLine( "SyncProjects" ); + Console.Error.WriteLine(); + Console.Error.WriteLine( "Usage: SyncProjects2 []" ); + Console.Error.WriteLine(); + Console.Error.WriteLine( "Options:" ); + options.WriteOptionDescriptions( Console.Out ); + return 1; + } + + SynchronizeProjects( file, sourceBasePath, projectExtension, msbuildExtensionsPath ); + + return 0; + } + catch ( Exception ex ) + { + Console.Error.WriteLine( ex ); + return ex.HResult; + } + } + + private static void SynchronizeProjects( string file, string sourceBasePath, string projectExtension, string msbuildExtensionsPath ) + { + var globalProperties = + new Dictionary + { + [ "MSBuildExtensionsPath" ] = msbuildExtensionsPath, + [ "EnableDefaultItems" ] = "true" + }; + + Dictionary definitions; + using ( var reader = File.OpenText( file ) ) + { + definitions = ProjectSynchronizationDefinition.FromJson( reader ).ToDictionary( x => x.TargetProjectName ); + } + + foreach ( var definition in definitions ) + { + definition.Value.ResolveProjectName( sourceBasePath, projectExtension ); + definition.Value.ResolveBase( key => definitions.TryGetValue( key, out var found ) ? found : null ); + + Console.Error.WriteLine( $"Process {definition.Value.TargetProjectName}" ); + ProjectSynchronizer.Synchronize( definition.Value, globalProperties ); + } + } + } +} \ No newline at end of file diff --git a/tools/SyncProjects2/SyncProjects2/SyncProjects2.csproj b/tools/SyncProjects2/SyncProjects2/SyncProjects2.csproj new file mode 100644 index 000000000..971586b3a --- /dev/null +++ b/tools/SyncProjects2/SyncProjects2/SyncProjects2.csproj @@ -0,0 +1,25 @@ + + + + Exe + netcoreapp1.0 + + + + bin\Release\netcoreapp1.0\ + + + + bin\Debug\netcoreapp1.0\ + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/mpu/ReadMe.txt b/tools/mpu/ReadMe.txt new file mode 100644 index 000000000..db7b596bc --- /dev/null +++ b/tools/mpu/ReadMe.txt @@ -0,0 +1,5 @@ +Please build by own as following: + +msbuild (solutionroot)/src/mpu/mpu.csproj /p:Configuration=Release + +This will be drop mpu for .NET 3.5 and 4.5. \ No newline at end of file diff --git a/tools/mpu/bin/MsgPack.dll b/tools/mpu/bin/MsgPack.dll deleted file mode 100644 index 2757a7678..000000000 Binary files a/tools/mpu/bin/MsgPack.dll and /dev/null differ diff --git a/tools/mpu/bin/MsgPack.xml b/tools/mpu/bin/MsgPack.xml deleted file mode 100644 index 73965bc84..000000000 --- a/tools/mpu/bin/MsgPack.xml +++ /dev/null @@ -1,14049 +0,0 @@ - - - - MsgPack - - - - - Define bit operations which enforce big endian. - - - - - Defines binary related utilities. - - - - - Singleton empty []. - - - - - Manages internal thread-local buffers for packer/unpacker. - - - - - Debugger type proxy for . - - The element type of the collection. - - - - Debugger type proxy for . - - The key type of the dictionary. - The value type of the dictionary. - - - - Provides bit access for . - - - - - Value as . - - - - - Most significant byte of current endian. - - - - - 2nd bit from most significant byte of current endian. - - - - - 3rd byte from most significant byte of current endian. - - - - - Least byte of current endian. - - - - - Initializes a new instance of the type from specified . - - Value of . - - - - Initializes a new instance of the type from specified [] which is big endian. - - Array of which contains bytes in big endian. - Offset to read. - - - - Provides bit access for . - - - - - Value as . - - - - - Most significant byte of current endian. - - - - - 2nd bit from most significant byte of current endian. - - - - - 3rd byte from most significant byte of current endian. - - - - - 4th byte from most significant byte of current endian. - - - - - 5th byte from most significant byte of current endian. - - - - - 6th byte from most significant byte of current endian. - - - - - 7th byte from most significant byte of current endian. - - - - - Least significant byte of current endian. - - - - - Initializes a new instance of the type from specified [] which is big endian. - - Array of which contains bytes in big endian. - Offset to read. - - - - Exception occured when inbound stream is invalid as serialized Message Pack stream. - - - - - Initializes a new instance of the class with the default error message. - - - - - Initializes a new instance of the class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - - The error message that explains the reason for the exception. - - The exception that is the cause of the current exception, or a null if no inner exception is specified. - - - - - Initializes a new instance of the class with serialized data. - - - The that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - The parameter is null. - - - The class name is null or is zero (0). - - - - - An interface which is implemented by the objects which know how to pack themselves using specified . - - - - Custom serialization interfaces are lightweight way to implement custom serialization especially you own the type itself. - You can tweak individual member serialization as well. For example: - - Encode text data which may contain non-ASCII charactors with UTF-16 format. - Pack binary with encryption or compression. - - - - - - - Packs this object contents to the specified . - - The that this object will write to. - Packing options. This value can be null. - - is null. - - - Failed to serialize this object. - - - - In general, objet's state will be serialized as array or map. - If so, emit array/map header with the items count via or , - then serialize states themselves. - - - On the other hand, value types may be serialized as single value. - For example, can be serialized as int64 value with its Ticks property. - - - - - - An position of seekable or offset from start of this instance. - - - - - An position of seekable or offset from start of this instance before last operation. - - - - - Starts unpacking of current subtree. - - - to unpack current subtree. - This will not be null. - - - - - Read subtree item from current stream. - - - true, if position is sucessfully move to next entry; - false, if position reaches the tail of the Message Pack stream. - - - This method only be called from . - - - - - An interface which is implemented by the objects which know how to unpack themselves using specified . - - - - - - - - Unpacks this object contents from the specified . - - The that this object will read from. - - is null. - - - Failed to deserialize this object. - - - - In general, objet's state is serialized as array or map. - If so, reading array/map header and then read individual fields (note that every state has their key string when the object serialized as map). - You should accept both of array and map for the object itself, and allow string and underlying numerics for enum values as "torelant reader". - - - On the other hand, value types may be serialized as single value. - For example, can be serialized as int64 value with its Ticks property. - - - - - - Defines known ext type code for MessagePack for CLI. - - - Note that values in this class are not guaranteed as interoperable with other implementations. - These are just known by MessagePack for CLI implementation. - - - - - Gets the ext type code which represents multidimensional array. - - - 0x1. - - - - - Defines known ext type name for MessagePack for CLI. - - - Note that values in this class are not guaranteed as interoperable with other implementations. - These are just known by MessagePack for CLI implementation. - - - - - Gets the ext type name which represents multidimensional array. - - - "MultidimensionalArray". - - - - - Exception occurs when serialized stream contains structures or features which will never be supported by MsgPack/CLI implementation. - - - - - Initializes a new instance of the class with the default error message. - - - - - Initializes a new instance of the class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - - The error message that explains the reason for the exception. - - The exception that is the cause of the current exception, or a null if no inner exception is specified. - - - - - Initializes a new instance of the class with serialized data. - - - The that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - The parameter is null. - - - The class name is null or is zero (0). - - - - - Define common convert rountines specific to MessagePack. - - - - - Encode specified string by default encoding. - - String value. - Encoded . - - is null. - - - - - Decode specified byte[] by default encoding. - - Byte[] value. - Decoded . - - is null. - - - contains non-UTF-8 bits. - - - - - Convert specified to . - - - value which is unpacked from packed message and may represent date-time value. - - - . Offset of this value always 0. - - - - - Convert specified to . - - - value which is unpacked from packed message and may represent date-time value. - - - . This value is always UTC. - - - - - Convert specified to as MessagePack defacto-standard. - - . - - UTC epoc time from 1970/1/1 0:00:00, in milliseconds. - - - - - Convert specified to as MessagePack defacto-standard. - - . - - UTC epoc time from 1970/1/1 0:00:00, in milliseconds. - - - - - Represents Message Pack extended type object. - - - - - A type code of this object. - - - - - Gets a type code of this object. - - - A type code. Note that values over are reserved for MsgPack spec itself. - - - - - A binary value portion of this object. - - - - - Gets a binary value portion of this object. - - - A binary value portion of this object. This value will not be null. - - - - - Gets a copy of the binary value portion of this object. - - - A copy of the binary value portion of this object. This value will not be null. - - - - - Gets a value indicating whether this instance is valid. - - - true if this instance is valid; otherwise, false. - - - - - Initializes a new instance of the struct. - - A type code of this extension object. - A binary value portion. - - The is over 127. Higher values are reserved for MessagePack format specification. - - The is null. - - - - Creates a new instance of the struct. - - A type code of this extension object. - A binary value portion. - The is null. - - This method allows reserved type code. It means that this method does not throw exception when the is reserved value (greater then 0x7F). - - - - - Returns a that represents this instance. - - - A that represents this instance. - - - - - Returns a hash code for this instance. - - - A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - - - - - Determines whether the specified is equal to this instance. - - The to compare with this instance. - - true if the specified is equal to this instance; otherwise, false. - - - - - Determines whether the specified is equal to this instance. - - The to compare with this instance. - - true if the specified is equal to this instance; otherwise, false. - - - - - Determines whether the specified s are equal. - - A . - A . - - true if the specified s are equal; otherwise, false. - - - - - Determines whether the specified s are not equal. - - A . - A . - - true if the specified s are not equal; otherwise, false. - - - - - Represents deserialized object of MsgPack. - - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Initializes a new instance of the [] type which wraps [] instance with specified manner. - - A bytes array to be wrapped. - - This constructor invokes with false, that means if you pass tha bytes array which is valid utf-8, resulting object can be , - and its should be . - - - - - Initializes a new instance of the [] type which wraps [] instance with specified manner. - - A bytes array to be wrapped. - true if always should be binary; false, otherwise. - - When the is true, then resulting object represents binary even if the is valid utf-8 sequence, - that is, its should be []. - On the other hand, when contrast, the is false, and if the is valid utf-8, - then the resulting object can be , - and its should be . - - - - - Initializes a new instance of the type which wraps instance. - - A value to be wrapped. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert this instance to [] instance. - - [] instance corresponds to this instance. - - - - Convert this instance to instance. - - instance corresponds to this instance. - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert []instance to instance. - - [] instance. - instance corresponds to . - - - - Convert instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Convert this instance to [] instance. - - instance. - [] instance corresponds to . - - - - Convert this instance to instance. - - instance. - instance corresponds to . - - - - Instance represents nil. This is equal to default value. - - - - - Get whether this instance represents nil. - - If this instance represents nil object, then true. - - - - Initializes a new instance wraps . - - - The collection to be copied. - - - - - Initializes a new instance wraps . - - - The collection to be copied or used. - - - true if the is immutable collection; - othereise, false. - - - When the collection is truely immutable or dedicated, you can specify true to the . - When is true, this constructor does not copy its contents, - or copies its contents otherwise. - - Note that both of IReadOnlyList and is NOT immutable - because the modification to the underlying collection will be reflected to the read-only collection. - - - - - - Initializes a new instance wraps . - - - The dictitonary to be copied. - - - - - Initializes a new instance wraps . - - - The dictitonary to be copied or used. - - - true if the is immutable collection; - othereise, false. - - - When the collection is truely immutable or dedicated, you can specify true to the . - When is true, this constructor does not copy its contents, - or copies its contents otherwise. - - Note that both of IReadOnlyDictionary and ReadOnlyDictionary is NOT immutable - because the modification to the underlying collection will be reflected to the read-only collection. - - - - - - Initializes a new instance wraps . - - which represents byte array or UTF-8 encoded string. - - - - Compare two instances are equal. - - instance. - - If is and its value is equal to this instance, then true. - Otherwise false. - - - - - Compare two instances are equal. - - instance. - - Whether value of is equal to this instance or not. - - - - - Get hash code of this instance. - - Hash code of this instance. - - - - Returns a string that represents the current object. - - - A string that represents the current object. - - - - DO NOT use this value programmically. - The purpose of this method is informational, so format of this value subject to change. - - - - - - Determine whether the underlying value of this instance is specified type or not. - - Target type. - If the underlying value of this instance is then true, otherwise false. - - - - Determine whether the underlying value of this instance is specified type or not. - - Target type. - If the underlying value of this instance is then true, otherwise false. - is null. - - - - Get the value indicates whether this instance wraps raw binary (or string) or not. - - This instance wraps raw binary (or string) then true. - - - - Get the value indicates whether this instance wraps list (array) or not. - - This instance wraps list (array) then true. - - - - Get the value indicates whether this instance wraps list (array) or not. - - This instance wraps list (array) then true. - - - - Get the value indicates whether this instance wraps dictionary (map) or not. - - This instance wraps dictionary (map) then true. - - - - Get the value indicates whether this instance wraps dictionary (map) or not. - - This instance wraps dictionary (map) then true. - - - - Get underlying type of this instance. - - Underlying . - - - - Packs this instance itself using specified . - - . - Packing options. This value can be null. - is null. - - - - Gets the underlying value as string encoded with specified . - - - The string. - Note that some returns null if the binary is not valid encoded string. - - - - - Get underlying value as UTF8 string. - - Underlying raw binary. - - - - Get underlying value as UTF-16 string. - - Underlying string. - - This method detects BOM. If BOM is not exist, them bytes should be Big-Endian UTF-16. - - - - - Get underlying value as UTF-16 charcter array. - - Underlying string. - - - - Get underlying value as . - - Underlying . - - - - Get underlying value as . - - Underlying . - - - - Get underlying value as . - - Underlying . - - - - Wraps specified object as recursively. - - Object to be wrapped. - wrapps . - - is not primitive value type, list of , - dictionary of , , [], or null. - - - - - Get boxed underlying value for this object. - - Boxed underlying value for this object. - - - - Compare two instances are equal. - - instance. - instance. - - Whether value of and are equal each other or not. - - - - - Compare two instances are not equal. - - instance. - instance. - - Whether value of and are not equal each other or are equal. - - - - - Convert [] instance to instance. - - [] instance. - instance corresponds to . - - - - Implements for . - - - This dictionary handles type semantics for the key. - Additionally, this dictionary implements 'freezing' feature. - For details, see , , and . - - - - - Gets a value indicating whether this instance is frozen. - - - true if this instance is frozen; otherwise, false. - - - This operation is an O(1) operation. - - - - - Gets the number of elements contained in the . - - - The number of elements contained in the . - - - This operation is an O(1) operation. - - - - - Gets or sets the element with the specified key. - - - The element with the specified key. - - Key for geting or seting value. - - is . - - - The property is retrieved and is not found. - - - The property is set and this instance is frozen. - - - - Note that tiny integers are considered equal regardless of its CLI , - and UTF-8 encoded bytes are considered equals to . - - - This method approaches an O(1) operation. - - - - - - Gets an containing the keys of the . - - - An containing the keys of the object. - This value will not be null. - - - This operation is an O(1) operation. - - - - - Gets an containing the values of the . - - - An containing the values of the object. - This value will not be null. - - - This operation is an O(1) operation. - - - - - Initializes an empty new instance of the class with default capacity. - - - This operation is an O(1) operation. - - - - - Initializes an empty new instance of the class with specified initial capacity. - - The initial capacity. - - is negative. - - - This operation is an O(1) operation. - - - - - Initializes a new instance of the class. - - The dictionary to be copied from. - - is null. - - - Failed to copy from . - - - This constructor takes O(N) time, N is of . - Initial capacity will be of . - - - - - Determines whether the contains an element with the specified key. - - The key to locate in the . - - is . - - - true if the contains an element with the key; otherwise, false. - - - This method approaches an O(1) operation. - - - - - Determines whether the contains an element with the specified value. - - The value to locate in the . - - true if the contains an element with the value; otherwise, false. - - - This method approaches an O(N) operation where N is . - - - - - Gets the value associated with the specified key. - - - The key whose value to get. - - - When this method returns, the value associated with the specified key, if the key is found; - otherwise, the default value for the type of the parameter. - This parameter is passed uninitialized. - - - true if this dictionary contains an element with the specified key; otherwise, false. - - - is . - - - - Note that tiny integers are considered equal regardless of its CLI , - and UTF-8 encoded bytes are considered equals to . - - - This method approaches an O(1) operation. - - - - - - Adds the specified key and value to the dictionary. - - - The key of the element to add. - - - The value of the element to add. The value can be null for reference types. - - - An element with the same key already does not exist in the dictionary and sucess to add then newly added node; - otherwise null. - - - already exists in this dictionary. - Note that tiny integers are considered equal regardless of its CLI , - and UTF-8 encoded bytes are considered equals to . - - - is . - - - If is less than the capacity, this method approaches an O(1) operation. - If the capacity must be increased to accommodate the new element, - this method becomes an O(N) operation, where N is . - - - - - Removes the element with the specified key from the . - - The key of the element to remove. - - true if the element is successfully removed; otherwise, false. - This method also returns false if was not found in the original . - - - is . - - - This method approaches an O(1) operation. - - - - - Removes all items from the . - - - This method approaches an O(N) operation, where N is . - - - - - Returns an enumerator that iterates through the . - - - Returns an enumerator that iterates through the . - - - This method is an O(1) operation. - - - - - Freezes this instance. - - - This instance itself. - This value will not be null and its is true. - - - This method freezes this instance itself. - This operation is an O(1) operation. - - - - - Gets a copy of this instance as frozen instance. - - - New instance which contains same items as this instance. - This value will not be null and its is true. - - - This method does not freeze this instance itself. - This operation is an O(N) operation where O(N) of items. - - - - - Enumerates the elements of a in order. - - - - - Gets the element at the current position of the enumerator. - - - The element in the underlying collection at the current position of the enumerator. - - - - - Gets the element at the current position of the enumerator. - - - The element in the collection at the current position of the enumerator, as an . - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Releases all resources used by the this instance. - - - - - Advances the enumerator to the next element of the underlying collection. - - - true if the enumerator was successfully advanced to the next element; - false if the enumerator has passed the end of the collection. - - - The collection was modified after the enumerator was created. - - - - - Sets the enumerator to its initial position, which is before the first element in the collection. - - - The collection was modified after the enumerator was created. - - - - - Enumerates the elements of a in order. - - - - - Gets the element at the current position of the enumerator. - - - The element in the collection at the current position of the enumerator, as an . - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Gets the element at the current position of the enumerator. - - - The element in the dictionary at the current position of the enumerator, as a . - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Gets the key of the element at the current position of the enumerator. - - - The key of the element in the dictionary at the current position of the enumerator. - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Gets the value of the element at the current position of the enumerator. - - - The value of the element in the dictionary at the current position of the enumerator. - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Advances the enumerator to the next element of the underlying collection. - - - true if the enumerator was successfully advanced to the next element; - false if the enumerator has passed the end of the collection. - - - The collection was modified after the enumerator was created. - - - - - Sets the enumerator to its initial position, which is before the first element in the collection. - - - The collection was modified after the enumerator was created. - - - - - Represents the set of keys. - - - - - Gets the number of elements contained in the . - - - The number of elements contained in the . - - - - - Copies the entire collection to a compatible one-dimensional array, starting at the beginning of the target array. - - - The one-dimensional that is the destination of the elements copied from this dictionary. - The must have zero-based indexing. - - - - - Copies the entire collection to a compatible one-dimensional array, - starting at the specified index of the target array. - - - The one-dimensional that is the destination of the elements copied from this dictionary. - The must have zero-based indexing. - - - The zero-based index in at which copying begins. - - - - - Copies a range of elements from this collection to a compatible one-dimensional array, - starting at the specified index of the target array. - - - The zero-based index in the source dictionary at which copying begins. - - - The one-dimensional that is the destination of the elements copied from this dictionary. - The must have zero-based indexing. - - - The zero-based index in at which copying begins. - - - The number of elements to copy. - - - - - Determines whether this collection contains a specific value. - - - The object to locate in this collection. - - true if is found in this collection; otherwise, false. - - - - - Determines whether this set is proper subset of the specified collection. - - - The collection to compare to the current set. - - - true if this set is proper subset of the specified collection; otherwise, false. - - - is Nothing. - - - - - Determines whether this set is proper superset of the specified collection. - - - The collection to compare to the current set. - - - true if this set is proper superset of the specified collection; otherwise, false. - - - is Nothing. - - - - - Determines whether this set is subset of the specified collection. - - - The collection to compare to the current set. - - - true if this set is subset of the specified collection; otherwise, false. - - - is Nothing. - - - - - Determines whether this set is superset of the specified collection. - - - The collection to compare to the current set. - - - true if this set is superset of the specified collection; otherwise, false. - - - is Nothing. - - - - - Determines whether the current set and a specified collection share common elements. - - - The collection to compare to the current set. - - - true if this set and share at least one common element; otherwise, false. - - - is Nothing. - - - - - Determines whether this set and the specified collection contain the same elements. - - - The collection to compare to the current set. - - - true if this set is equal to ; otherwise, false. - - - is Nothing. - - - - - Returns an enumerator that iterates through this collction. - - - Returns an enumerator that iterates through this collction. - - - - - Enumerates the elements of a . - - - - - Gets the element at the current position of the enumerator. - - - The element in the underlying collection at the current position of the enumerator. - - - - - Gets the element at the current position of the enumerator. - - - The element in the collection at the current position of the enumerator, as an . - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Releases all resources used by the this instance. - - - - - Advances the enumerator to the next element of the underlying collection. - - - true if the enumerator was successfully advanced to the next element; - false if the enumerator has passed the end of the collection. - - - The collection was modified after the enumerator was created. - - - - - Sets the enumerator to its initial position, which is before the first element in the collection. - - - The collection was modified after the enumerator was created. - - - - - Represents the collection of values in a . - - - - - Gets the number of elements contained in the . - - - The number of elements contained in the . - - - - - Copies the entire collection to a compatible one-dimensional array, starting at the beginning of the target array. - - - The one-dimensional that is the destination of the elements copied from this dictionary. - The must have zero-based indexing. - - - - - Copies the entire collection to a compatible one-dimensional array, - starting at the specified index of the target array. - - - The one-dimensional that is the destination of the elements copied from this dictionary. - The must have zero-based indexing. - - - The zero-based index in at which copying begins. - - - - - Copies a range of elements from this collection to a compatible one-dimensional array, - starting at the specified index of the target array. - - - The zero-based index in the source dictionary at which copying begins. - - - The one-dimensional that is the destination of the elements copied from this dictionary. - The must have zero-based indexing. - - - The zero-based index in at which copying begins. - - - The number of elements to copy. - - - - - Determines whether this collection contains a specific value. - - - The object to locate in this collection. - - true if is found in this collection; otherwise, false. - - - - - Returns an enumerator that iterates through this collction. - - - Returns an enumerator that iterates through this collction. - - - - - Enumerates the elements of a . - - - - - Gets the element at the current position of the enumerator. - - - The element in the underlying collection at the current position of the enumerator. - - - - - Gets the element at the current position of the enumerator. - - - The element in the collection at the current position of the enumerator, as an . - - - The enumerator is positioned before the first element of the collection or after the last element. - - - - - Releases all resources used by the this instance. - - - - - Advances the enumerator to the next element of the underlying collection. - - - true if the enumerator was successfully advanced to the next element; - false if the enumerator has passed the end of the collection. - - - The collection was modified after the enumerator was created. - - - - - Sets the enumerator to its initial position, which is before the first element in the collection. - - - The collection was modified after the enumerator was created. - - - - - Implements of . - - - - - Initializes a new instance of the class. - - - - - Determines whether two objects of type are equal. - - The first object to compare. - The second object to compare. - - true if the specified objects are equal; otherwise, false. - - - - - Returns a hash code for the specified . - - The . - - A hash code for , suitable for use in hashing algorithms and data structures like a hash table. - - - - - Encapselates and its serialized UTF-8 bytes. - - - - - Represents unpacking error when message type is unknown or unavailable. - - - - - Initializes a new instance of the class with the default error message. - - - - - Initializes a new instance of the class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - - The error message that explains the reason for the exception. - - The exception that is the cause of the current exception, or a null if no inner exception is specified. - - - - - Initializes a new instance of the class with serialized data. - - - The that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - The parameter is null. - - - The class name is null or is zero (0). - - - - - Implements serialization feature of MsgPack. - - - - - Gets or sets the default for all instances. - - - The default . - The default value is . - - - - Note that modification of this value will affect all new instances from the point. - Existent instances are not afectted by the modification. - - - This property is intended to be set in application initialization code. - - - Note that the default value is , not . - - - - - - Get whether this class supports seek operation and quering property. - - If this class supports seek operation and quering property then true. - - - - Get current position of underlying stream. - - Opaque position value of underlying stream. - - A class of this instance does not support seek. - - - - - Gets a compatibility options for this instance. - - - The compatibility options. - - - - - Initializes a new instance of the class with . - - - - - Initializes a new instance of the class with specified . - - A which specifies compatibility options. - - - - Create standard Safe instancde wrapping specified with . - - object. This stream will be closed when is called. - Safe . This will not be null. - is null. - - You can specify any derived class like FileStream, , - NetworkStream, UnmanagedMemoryStream, or so. - - - - - Create standard Safe instancde wrapping specified with specified . - - object. This stream will be closed when is called. - A which specifies compatibility options. - Safe . This will not be null. - is null. - - You can specify any derived class like FileStream, , - NetworkStream, UnmanagedMemoryStream, or so. - - - - - Create standard Safe instancde wrapping specified with . - - object. - - true to close when this instance is disposed; - false, otherwise. - - Safe . This will not be null. - is null. - - You can specify any derived class like FileStream, , - NetworkStream, UnmanagedMemoryStream, or so. - - - - - Create standard Safe instancde wrapping specified with specified . - - object. - A which specifies compatibility options. - - true to close when this instance is disposed; - false, otherwise. - - Safe . This will not be null. - is null. - - You can specify any derived class like FileStream, , - NetworkStream, UnmanagedMemoryStream, or so. - - - - - Create standard Safe instancde wrapping specified with specified . - - object. - A which specifies compatibility options. - which specifies stream handling options. - Safe . This will not be null. - is null. - - You can specify any derived class like FileStream, , - NetworkStream, UnmanagedMemoryStream, or so. - - - - - Clean up internal resources. - - - - - When overridden by derived class, release all unmanaged resources, optionally release managed resources. - - If true, release managed resources too. - - - - When overridden by derived class, change current position to specified offset. - - Offset. You shoud not specify the value which causes underflow or overflow. - - A class of this instance does not support seek. - - - - - When overridden by derived class, writes specified byte to stream using implementation specific manner. - - A byte to be written. - - - - Writes specified bytes to stream using implementation specific most efficient manner. - - Collection of bytes to be written. - - - - Writes specified bytes to stream using implementation specific most efficient manner. - - Bytes to be written. - If the can be treat as immutable (that is, can be used safely without copying) then true. - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - - - - Try packs value to current stream as tiny fix num. - - Maybe tiny value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Try packs value to current stream as tiny fix num. - - Maybe tiny value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs a null value to current stream. - - This instance. - This instance has been disposed. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Pack nullable value. - - Value to serialize. - This instance. - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - This instance has been disposed. - - - - Try packs value to current stream strictly. - - Maybe value. - If has be packed successfully then true, otherwise false (normally, larger type required). - - - - Packs value to current stream. - - value. - This instance. - - - - Packs value to current stream. - - value. - This instance. - - - - Bookkeep array length or list items count to be packed on current stream. - - Array length or list items count. - This instance. - This instance has been disposed. - - - - Bookkeep array length or list items count to be packed on current stream. - - Array length or list items count. - - - - Bookkeep dictionary (map) items count to be packed on current stream. - - Dictionary (map) items count. - This instance. - This instance has been disposed. - - - - Bookkeep dictionary (map) items count to be packed on current stream. - - Dictionary (map) items count. - - - - Bookkeep byte length to be packed on current stream as the bytes might represent well formed encoded string. - - A length of byte array. - This instance. - This instance has been disposed. - - This method effectively acts as alias of for compatibility. - - - - - Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string. - - A length of encoded byte array. - This instance. - This instance has been disposed. - - - - Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string. - - A length of byte array. - This instance. - This instance has been disposed. - - - - Bookkeep byte length to be packed on current stream as the bytes might represent well formed encoded string. - - A length of byte array. - - This method acts as alias of for compatibility. - - - - - Bookkeep byte length to be packed on current stream as the bytes should represent well formed encoded string. - - A length of encoded byte array. - - - - Bookkeep byte length to be packed on current stream as the bytes should not represent well formed encoded string. - - A length of byte array. - - - - Packs specified byte sequence(it may or may not be string to current stream. - - Source bytes its size is not known. - This instance. - This instance has been disposed. - - This method use str types (previously known as raw types) for compability. - - - - - Packs specified byte collection(it may or may not be string to current stream. - - Source bytes its size is known. - This instance. - This instance has been disposed. - - This method use str types (previously known as raw types) for compability. - - - - - Packs specified byte array(it may or may not be string to current stream. - - A byte array. - This instance. - This instance has been disposed. - - This method use str types (previously known as raw types) for compability. - - - - - Packs specified byte sequence(it should not be string to current stream. - - Source bytes its size is not known. - This instance. - This instance has been disposed. - - This method use bin types unless contains . - - - - - Packs specified byte collection(it should not be string to current stream. - - Source bytes its size is known. - This instance. - This instance has been disposed. - - This method use bin types unless contains . - - - - - Packs specified byte array(it should not be string to current stream. - - A byte array. - This instance. - This instance has been disposed. - - This method use bin types unless contains . - - - - - Packs specified charactor sequence to current stream with UTF-8 . - - Source chars its size is not known. - This instance. - This instance has been disposed. - - - - Packs specified charactor sequence to current stream with specified . - - Source chars its size is not known. - to be used. - This instance. - is null. - This instance has been disposed. - - - - Packs specified charactor sequence to current stream with specified . - - Source chars its size is not known. - to be used. - is null. - - - - Packs specified string to current stream with UTF-8 . - - Source string. - This instance. - This instance has been disposed. - - - - Packs specified string to current stream with specified . - - Source string. - to be used. - This instance. - is null. - This instance has been disposed. - - - - Packs specified string to current stream with specified . - - Source string. - to be used. - is null. - - - - Packs specified byte array to current stream without any header. - - Source byte array. - This instance. - This instance has been disposed. - - If you forget to write header first, then resulting stream will be corrupsed. - - - - - Packs specified byte sequence to current stream without any header. - - Source byte array. - This instance. - This instance has been disposed. - - If you forget to write header first, then resulting stream will be corrupsed. - - - - - Bookkeep collection count to be packed on current stream. - - Collection count to be written. - This instance. - This instance has been disposed. - - - - Bookkeep dictionary count to be packed on current stream. - - Dictionary count to be written. - This instance. - This instance has been disposed. - - - - Packs an extended type value. - - A type code of the extended type value. - A binary value portion of the extended type value. - This instance. - is null. - property contains . - This instance has been disposed. - - - - Packs an extended type value. - - A to be packed. - This instance. - of is false. - property contains . - This instance has been disposed. - - - - Defines compatibility options for . - - - - - No compatibility options. s use newest behavior. - - - - - Packs byte array as raw(str) value, and also prohibits usage of str8 type for legacy unpacker implementations. - - - - - Prohibits usage of any ext types for legacy unpacker implementations. - - - - - s should be use classic behavior. That is, do not use str8 and any ext types, and byte arrays must be packed as raw. - - - - - Defines extension method to pack or unpack various objects. - - - - - Packs specified value with the default context. - - The type of the value. - The . - The value to be serialized. - . - - is null. - - - Cannot serialize . - - - - - Packs specified value with the specified context. - - The type of the value. - The . - The value to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize . - - - - - Packs specified collection with the default context. - - The type of items of the collection. - The . - The collection to be serialized. - . - - is null. - - - Cannot serialize . - - - - - Packs specified collection with the specified context. - - The type of items of the collection. - The . - The collection to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize . - - - - - Packs specified collection with the default context. - - The type of items of the collection. - The . - The collection to be serialized. - . - - is null. - - - Cannot serialize . - - - - - Packs specified collection with the specified context. - - The type of items of the collection. - The . - The collection to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize . - - - - - Packs specified dictionary with the default context. - - The type of keys of the dictionary. - The type of values of the dictionary. - The . - The dictionary to be serialized. - . - - is null. - - - Cannot serialize . - - - - - Packs specified dictionary with the specified context. - - The type of keys of the dictionary. - The type of values of the dictionary. - The . - The dictionary to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize . - - - - - Packs specified dictionary with the default context. - - The type of keys of the dictionary. - The type of values of the dictionary. - The . - The dictionary to be serialized. - . - - is null. - - - Cannot serialize . - - - - - Packs specified dictionary with the specified context. - - The type of keys of the dictionary. - The type of values of the dictionary. - The . - The dictionary to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize . - - - - - Packs specified collection with the default context. - - The type of the value. - The . - The collection to be serialized. - . - - is null. - - - Cannot serialize the item of . - - - - - Packs specified value with the specified context. - - The type of the value. - The . - The collection to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize the item of . - - - - - Packs specified value with the default context. - - The . - The value to be serialized. - . - - is null. - - - Cannot serialize . - - - - - Packs specified value with the specified context. - - The . - The value to be serialized. - The holds shared serializers. - . - - is null. - Or is null. - - - Cannot serialize . - - - - - Unpacks specified type value with the default context. - - The type of the deserializing object. - The . - The deserialized object. - - is null. - - - Cannot deserialize object. - - - - - Unpacks specified type value with the specified context. - - The type of the deserializing object. - The . - The holds shared serializers. - The deserialized object. - - is null. - Or is null. - - - Cannot deserialize object. - - - - - Represents options for stream on / creation. - - - - - Gets or sets a value indicating whether stream should be wrapped with buffering stream. - - - true if stream should be wrapped with buffering stream; otherwise, false. - - - - This option is important to improve asynchronous operation performance because deserialization tend to be chatty, - so many tiny asynchrnous operation are issued and then numerous context switching may occurred. - Wrapping with buffering stream mitigate context switching because it should avoid asynchronous operation - as long as it has buffered value. - - - Current built-in implementation uses for buffering, - and avoid buffering for following in-memory or stream with buffering feature: - - itself. - . - . - which has own internal buffer. - - - - Logically, it is preferred that you should wrap with yourself for underlying stream - for wrapper stream such as , , etc. - - - - - - - Gets or sets the size of the buffer of wrapping stream in bytes used when is true. - - - The size of the buffer of wrapping stream in bytes used when is true. - The default is 64K. - If you attempt to set 0 or negative value, then the value will be set to 1. - - - - - Gets or sets a value indicating whether / will dispose underlying stream when their Dispose(Boolean) method are called with true value. - - - true if / will dispose underlying stream when their Dispose(Boolean) method are called with true value; - otherwise, false. - - - - - Initializes a new instance of the class. - - - - - Represents options of packing. - - - - - Get encoding for string. - - - for string. Default is UTF-8 encoding without BOM. - - - - - Initializes a new instance of the class. - - - - - Indicates type of action delegates. - - - - - Represents information of the cached delegate instance which should be stored in readonly instance field. - - - - - Represents constructor which may not have built metadata. - - - - - void PackUnderlyingValueTo(Packer, TEnum) - - - - - TEnum UnpackFromUnderlyingValue(MessagePackObject) - - - - - Represents field which may not have built metadata. - - - - - Defines a common interface for code construct which abstracts code constructs used in serializer builders. - - - - - Gets the context type of this construct. - - - The context type of this construct. - This value will not be null, but might be . - - - A context type represents evaluation context for IL emitting or expression type for Expression Tree. - - - - - Defines a common interface for serializer builder. - - - - - Builds the serializer and returns its new instance. - - The context information. - The substitution type if the target type is abstract type. null when the target type is not abstract type. - The schema which contains schema for collection items, dictionary keys, or tuple items. This value may be null. - - Newly created serializer object. - This value will not be null. - - - - - Defines common interface for context objects of serializer code generation. - - - - - Generates codes for this context. - - A collection which correspond to genereated codes. - - - - Gets the serialization context which holds various serialization configuration. - - - The serialization context. This value will not be null. - - - - - Defines a common interface for serializer builder which supports code generation. - - - - - Builds the serializer code using specified code generation context. - - - The which holds configuration and stores generated code constructs. - - The substitution type if builder's target type is abstract type. null when builder's target type is not abstract type. - The schema which contains schema for collection items, dictionary keys, or tuple items. This value must not be null. - - is null. - - - This class does not support code generation. - - - - - Represents method which may not have built metadata. - - - - - Defines common features for serializer builder. - - The type of the context which holds global information for generating serializer. - The type of the construct which abstracts code constructs. - - - - Emits anonymous null reference literal. - - The generation context. - The type of null reference. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant value. - - The generation context. - The constant value. - The generated construct. - - - - Emits the constant enum value. - - The generation context. - The type of the enum. - The constant value. - The generated construct. - is not enum. - - - - Emits the constant default(T) value of value type. - - The generation context. - The type of the valueType. - The generated construct. - - - - Emits the loading this reference expression. - - The generation context. - The generated construct. - - - - Emits the box expression. - - The generation context. - Type of the value to be boxed. - The value to be boxed. - The generated construct. - - - - Emits the cast or unbox expression. - - The generation context. - Type of the value to be casted or be unboxed. - The value to be casted or be unboxed. - The generated construct. - - - - Emits the not expression. - - The generation context. - The boolean expression to be . - The generated construct. - - - - Emits the equals expression. - - The generation context. - The left expression. - The right expression. - The generated construct. - - - - Emits the not equals expression. - - The generation context. - The left expression. - The right expression. - The generated construct. - - - - Emits the greater than expression. - - The generation context. - The left expression. - The right expression. - The generated construct. - - - - Emits the less than expression. - - The generation context. - The left expression. - The right expression. - The generated construct. - - - - Emits the unary increment expression. - - The generation context. - The int32 value to be incremented. - The generated construct. - - - - Emits the elementType-of expression. - - The generation context. - The elementType. - The generated construct. - - - - Emits the 'methodof' expression. - - The generation context. - The method to be retrieved. - The generated construct. - - - - Emits the 'fieldof' expression. - - The generation context. - The field to be retrieved. - The generated construct. - - - - Emits the sequential statements. Note that the context elementType is void. - - The generation context. - The type of context. - The statements. - The generated construct. - - - - Emits the sequential statements. Note that the context elementType is void. - - The generation context. - The type of context. - The statements. - The generated construct. - - - - Creates the argument reference. - - The generation context. - The type of the parameter for debugging puropose. - The name of the parameter. - The index of the parameters. - - The generated construct which represents an argument reference. - - - - - Declares the local variable. - - The generation context. - The type of the variable. - The name of the variable for debugging puropose. - - The generated construct which represents local variable declaration AND initialization, and reference. - - - - - Emits the statement which loads value from the local variable. - - The generation context. - The variable to be loaded. - The generated construct. - - - - Emits the statement which stores specified value to the local variable. - - The generation context. - The variable to be stored. - The value to be stored. null for context value. - The generated construct. - - - - Emits the create new object expression. - - The generation context. - The variable which will store created value type object. - The constructor. - The arguments. - - The generated construct which represents new obj instruction. - Note that created object remains in context. - - - - - Emits the create new array expression. - - The generation context. - The elementType of the array element. - The length of the array. - The generated code construct. - - - - Emits the create new array expression. - - The generation context. - The elementType of the array element. - The length of the array. - The initial elements of the array. - The generated code construct. - - - - Emits the get array element expression. - - The generation context. - The array to be gotten. - The index of the array element to be gotten. - The generated code construct. - - - - Emits the set array element statement. - - The generation context. - The array to be set. - The index of the array element to be set. - The value to be set. - The generated code construct. - - - - Emits the conditional expression (cond?then:else). - - The generation context. - The expression which represents conditional. - The expression which is used when condition is true. - The expression which is used when condition is false. - The conditional expression. - - - - Emits the conditional expression (cond?then:else) which has short circuit and expression. - - The generation context. - The expression which represents short circuit and expression. - The expression which is used when condition is true. - The expression which is used when condition is false. - The conditional expression. - - - - Emits the return statement - - The generation context. - The expression to be returned. - The return statement. - - - - Emits the try-finally expression. - - The generation context. - The try expression. - The finally statement. - The generated construct which elementType is elementType of . - - - - Emits the for-each loop. - - The generation context. - The traits of the collection. - The collection reference. - The loop body emitter which takes item reference then returns loop body construct. - The for each loop. - - - - Emits the invoke void method. - - The generation context. - The instance for instance method invocation. null for static method. - The method to be invoked. - The arguments to be passed. - - The generated construct. - - - The derived class must emits codes which discard return non-void value. - - - - - Emits the invoke non-void method. - - The generation context. - The instance for instance method invocation. null for static method. - The method to be invoked. - The arguments to be passed. - - The generated construct which represents method call instruction. - Note that returned value remains in context. - - - - - Emits the invoke non-void method. - - The generation context. - The instance for instance method invocation. null for static method. - The method to be invoked. - The arguments to be passed. - - The generated construct which represents method call instruction. - Note that returned value remains in context. - - - - - Emits the invoke non-void delegate. - - The generation context. - The return type of the delegate. - The delegate to be invocation. - The arguments to be passed. - - The generated construct which represents delegate invocation instruction. - Note that returned value remains in context. - - - - - Emits specified body as individual private method and returns delegate for it. - - The generation context. - The name of the private method. - The type of return value. - The delegate to the factory which returns body of the private method. - The parameters of the private method. - - The generated construct which represents delegate creation instruction to call the private method. - Note that returned value remains in context. - - - - - Emits delegate instantiation for specified named private instance or static method. - - The generation context. - The information of the private method. - - The generated construct which represents delegate creation instruction to call the specified private method. - Note that returned value remains in context. - - - - - Emits getting cached delegate for specified named static method. - - The generation context. - The information of the static method. - - The generated construct which represents delegate creation instruction to call the specified method. - Note that returned value remains in context. - - - - - Emits the get member(field or property) value expression. - - The generation context. - The instance which stores instance member value. - The member to be accessed. - The generated construct. - - - - Emits the get property value expression. - - The generation context. - The instance which stores instance member value. - The property to be accessed. - The generated construct. - - - - Emits the get field value expression. - - The generation context. - The instance which stores instance member value. - The field to be accessed. - The generated construct. - - - - Emits the set member(property or field) value statement. - - The generation context. - The instance which stores instance member value. - The member to be accessed. - The value to be stored. - The generated construct. - - This method generates collection.Add(value) constructs for a read-only member. - - - - - Emits the set property value statement. - - The generation context. - The instance which stores instance member value. - The property to be accessed. - The value to be stored. - The generated construct. - - - - Emits the set indexer property statement. - - The generation context. - The instance which stores instance member value. - The type which defines the property. - The name of the property to be accessed. - The key to be stored. - The value to be stored. - The generated construct. - - - - Emits the set field value statement. - - The generation context. - The instance which stores instance member value. - The field to be accessed. - The value to be stored. - The generated construct. - - - - Emits the set field value statement. - - The generation context. - The instance which stores instance member value. - The nested type definition of the instance which stores instance member value. - The name of the field to be accessed. - The value to be stored. - The generated construct. - - - - Emits the pack item statements. - - The generation context. - The packer. - Type of the item. - The nil implication of the member. - Name of the member. - The item to be packed. - The metadata of packing member. null for non-object member (collection or tuple items). - The schema for collection items. null for non-collection items and non-schema items. - true for async. - The generated code construct. - - - - Emits the pack item expression. - - The generation context. - The packer. - Type of the item. - The item to be packed. - The metadata of packing member. null for non-object member (collection or tuple items). - The schema for collection items. null for non-collection items and non-schema items. - true for async. - The generated code construct. - - - - Emits the append collection item. - - The code generation context. - The read only collection member metadata. null for collection item. - The traits of the collection. - The collection to be appended. - The unpacked item. - - - - - - - Emits the invariant with . - - The generation context. - The format string literal. - The arguments to be used. - The generated construct. - - - - Emits the get serializer expression. - - The generation context. - Type of the target of the serializer. - The metadata of the packing/unpacking member. - The schema for collection items. null for non-collection items and non-schema items. - The generated code construct. - - The serializer reference methodology is implication specific. - - - - - Retrieves a default constructor of the specified elementType. - - The target elementType. - A default constructor of the . - - - - Determines the collection constructor arguments. - - The context. - The constructor. - - An array of constructs representing constructor arguments. - - - The has unsupported signature. - - - - - Gets the construt for constructor argument. - - The context. - The parameter of the constructor parameter. - The construt for constructor argument. - - - - Emits the construct to get equality comparer via . - - The context. - - The construct to get equality comparer via . - - - - - Emits construction sequence. - - The context. - The local variable which the schema to be stored. - The which contains emitting data. - - Constructs to emit construct a copy of . - - - - - Gets the type of the serialization target. - - - The type of the serialization target. - - - - - Gets the cache of . - - - The cache of . - - - - - Gets the base class of the generating serializer. - - - The base class of the generating serializer. - - - - - Initializes a new instance of the class. - - The type of serialization target. - The collection traits of the serialization target. - - - - Builds the serializer and returns its new instance. - - The context information. - The substitution type if is abstract type. null when is not abstract type. - The schema which contains schema for collection items, dictionary keys, or tuple items. This value may be null. - - Newly created serializer object. - This value will not be null. - - - - - Creates the code generation context for serializer instance creation. - - The serialization context. - - The code generation context for serializer instance creation. - This value will not be null. - - - - - Builds the serializer and returns its new instance. - - The context information. This value will not be null. - The substitution type if is abstract type. null when is not abstract type. - The schema which contains schema for collection items, dictionary keys, or tuple items. This value may be null. - The parsed serialization target information. - - Newly created serializer object. - This value will not be null. - - - - - Creates the serializer type and returns its constructor. - - The code generation context. - The parsed serialization target information. - The polymorphism schema of this. - - which refers newly created constructor. - This value will not be null. - - - - - Creates the enum serializer type and returns its constructor. - - The code generation context. - - which refers newly created constructor. - This value will not be null. - - - - - Builds the serializer code using specified code generation context. - - - The which holds configuration and stores generated code constructs. - - The substitution type if is abstract type. null when is not abstract type. - The schema which contains schema for collection items, dictionary keys, or tuple items. This value must not be null. - - is null. - - - This class does not support code generation. - - - - - In derived class, builds the serializer code using specified code generation context. - - - The which holds configuration and stores generated code constructs. - This value will not be null. - - The substitution type if is abstract type. null when is not abstract type. - The schema which contains schema for collection items, dictionary keys, or tuple items. This value must not be null. - - This class does not support code generation. - - - - - Represents dictionary key to remember fields which store dependent serializer instance. - - - - - Type of serializing/deserializing type. - - - - - Enum serialization method for specific member. - - - - - DateTime conversion method for specific member. - - - - - for specific member. null for non-polymorphic member. - - - - - Comparable . - - - must use to distinct between shared serializer and non-sharable serializer because of its polymorphism. - - - - - Defines common interfaces and features for context objects for serializer generation. - - The contextType of the code construct for serializer builder. - - - - Gets the code construct which represents 'context' parameter of generated methods. - - - The code construct which represents 'context' parameter of generated methods. - Its type is , and it holds dependent serializers. - This value will not be null. - - - - - Gets the serialization context which holds various serialization configuration. - - - The serialization context. This value will not be null. - - - - - Gets the code construct which represents the argument for the packer. - - - The code construct which represents the argument for the packer. - This value will not be null. - - - - - Gets the code construct which represents the argument for the packing target object tree root. - - - The code construct which represents the argument for the packing target object tree root. - This value will not be null. - - - - - Gets the code construct which represents the argument for the unpacker. - - - The code construct which represents the argument for the unpacker. - This value will not be null. - - - - - Gets the code construct which represents the argument for the collection which will hold unpacked items. - - - The code construct which represents the argument for the collection which will hold unpacked items. - This value will not be null. - - - - - Gets the code construct which represents the argument for the collection which will be added new unpacked item. - - - The code construct which represents the argument for the collection which will be added new unpacked item. - This value will not be null. - - - - - Gets the code construct which represents the argument for the item to be added to the collection. - - - The code construct which represents the argument for the item to be added to the collection. - This value will not be null. - - - - - Gets the code construct which represents the argument for the key to be added to the dictionary. - - - The code construct which represents the argument for the key to be added to the dictionary. - This value will not be null. - - - - - Gets the code construct which represents the argument for the value to be added to the dictionary. - - - The code construct which represents the argument for the key to be added to the dictionary. - This value will not be null. - - - - - Gets the code construct which represents the argument for the initial capacity of the new collection. - - - The code construct which represents the argument for the initial capacity of the new collection. - This value will not be null. - - - - - Gets the code construct which represents the unpacking context for unpacking operations. - - - The code construct which represents the the unpacking context for unpacking operations. - This value is initialized in . - - - - - Gets the code construct which represents the unpacking context for unpacking operations. - - - The code construct which represents the the unpacking context for unpacking operations. - This value is initialized in . - - - - - Gets the code construct which represents the unpacking context for CreateObjectFromContext method. - - - The code construct which represents the the unpacking context for CreateObjectFromContext method. - This value is initialized in . - - - - - Gets the code construct which represents the index of unpacking item in the source array or map. - - - The code construct which represents the index of unpacking item in the source array or map. - This value will not be null. - - - - - Gets the code construct which represents the count of unpacking items in the source array or map. - - - The code construct which represents the count of unpacking items in the source array or map. - This value will not be null. - - - - - Gets the configured nil-implication for collection items. - - - The configured nil-implication for collection items. - - - - - Gets the configured nil-implication for dictionary keys. - - - The configured nil-implication for dictionary keys. - - - - - Gets the configured nil-implication for tuple items. - - - The configured nil-implication for tuple items. - - - - - Gets the declared method. - - The name of the method. - - The . This value will not be null. - - The specified method has not been declared yet. - - - - Determines whether specified named private method is already declared or not. - - The name of the method. - true, if specified named method is already declared; fale, otherwise. - - - - Gets the declared field. - - The name of the field. - - The . This value will not be null. - - The specified field has not been declared yet. - - - - Gets the type of the unpacking context. - - - The type of the unpacking context. This value is null until called after last . - - - - - Gets or sets a value indicating whether an UnpackTo method call is emitted or not. - - - true if an UnpackTo method call is emitted; otherwise, false. - - - - - Initializes a new instance of the class. - - The serialization context. - - - - Resets internal states for specified target type. - - Type of the serialization target. - Type of base class of the target. - - - - Resets internal states for specified target type. - - Type of the serialization target. - Type of base class of the target. - - - - Gets a unique name of a local variable. - - The prefix of the variable. - A unique name of a local variable. - - - - Begins implementing overriding method. - - The name of the method. - - - - Ends implementing overriding method. - - The name of the method. - The construct which represents whole method body. - - The method definition of the overridden method. - - - - - Ends implementing overriding method. - - The name of the method. - The construct which represents whole method body. - - The method definition of the overridden method. - - - - - Begins implementing private method. - - The name of the method. - true for static method. - The type of the method return value. - The name and type pairs of the method parameters. - - - - Ends current implementing private method. - - The name of the method. - The construct which represents whole method body. - - The method definition of the private method. - - - - - Ends current implementing private method. - - The name of the method. - The construct which represents whole method body. - - The method definition of the private method. - - - - - Declares new private field. - - The name. - The type. - - - - - Declares new private field. - - The name. - The type. - - - - - Defines the unpacking context type. - - The fields must be declared. - - The type definition of the unpacking context. - Note that this type will be existing property bag or generated private type. - - - The constructor of the context. - - - - - Defines the unpacking context type. - - The fields must be declared. - - The type definition of the unpacking context. - Note that this type will be existing property bag or generated private type. - - - The constructor of the context. - - The typed parameter for unpacking operations. - The typed parameter for unpacking operations. - The typed parameter for CreateObjectFromContext method. - - - - Defines the unpacking context type with result object type. - - The unpacking context type. - - - - Defines the unpacking context type with result object type. - - - The type definition of the unpacking context. - Note that this type will be existing property bag or generated private type. - - The typed parameter for unpacking operations. - The typed parameter for unpacking operations. - The typed parameter for CreateObjectFromContext method. - - - - Defines the unpacked item parameter in set value methods. - - Type of the value. - The parameter construct. - - - - Represents type which may not have built metadata. - - - - - Gets the current . - - - The current . - - - - - Gets a unique name of a local variable. - - The prefix of the variable. - A unique name of a local variable. - - - - Gets a value indicating whether the generated serializers will be internal to MsgPack library itself. - - - true if the generated serializers are internal to MsgPack library itself; otherwise, false. - - - When you use MsgPack in Unity3D, you can import the library in source code form to your assets. - And, you may also import generated serializers together, then the generated serializers and MsgPack library will be same assembly ultimately. - It causes compilation error because some of overriding members have accessbility FamilyOrAssembly(protected internal in C#), - so the generated source code must have the accessibility when and only when they will be same assembly as MsgPack library itself. - - - - - Gets or sets a value indicating whether conditional expression is used, that is, helper method is required or not. - - - true if conditional expression is used; otherwise, false. - - - - - Resets internal states for new type. - - Type of the target. - Type of base class of the target. - - - - Generates codes for this context. - - A collection which correspond to genereated codes. - - - - Creates the for on-the-fly code generation for execution. - - - The newly created for on-the-fly code generation for execution. - - - - - Code DOM based implementation of . - This type supports pre-generation. - - - - - Provides common implementation of - for collection types which implement or IReadOnlyCollection{T}. - - The type of the collection. - The type of the item of collection. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - is not serializable etc. - - - - - When overridden in derived class, returns count of the collection. - - A collection. This value will not be null. - The count of the . - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. This value will not be null. - Deserialized object. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is abstract type. - - - This method invokes , and then fill deserialized items to resultong collection. - - - - - Provides common implementation of - for collection types which implement . - - The type of the collection. - The type of the item of collection. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Returns count of the collection. - - A collection. This value will not be null. - The count of the . - - - - Adds the deserialized item to the collection on specific manner - to implement . - - The collection to be added. - The item to be added. - - - - Provides common features for generic dictionary serializers. - - The type of the dictionary. - The type of the key of dictionary. - The type of the value of dictionary. - - This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. - If you cannot use this class, you can implement your own serializer which inherits and implements . - - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - is not serializable etc. - - - - - When overridden in derived class, returns count of the dictionary. - - A collection. This value will not be null. - The count of the . - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. This value will not be null. - Deserialized object. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is abstract type. - - - This method invokes , and then fill deserialized items to resultong collection. - - - - - Creates a new collection instance with specified initial capacity. - - - The initial capacy of creating collection. - Note that this parameter may 0 for non-empty collection. - - - New collection instance. This value will not be null. - - - An author of could implement unpacker for non-MessagePack format, - so implementer of this interface should not rely on that reflects actual items count. - For example, JSON unpacker cannot supply collection items count efficiently. - - - - - - Deserializes collection items with specified and stores them to . - - which unpacks values of resulting object tree. This value will not be null. - Collection that the items to be stored. This value will not be null. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is not collection. - - - - - When implemented by derive class, - adds the deserialized item to the collection on specific manner - to implement . - - The dictionary to be added. - The key to be added. - The value to be added. - - This implementation always throws it. - - - - - Provides basic features for generic serializers. - - The type of the dictionary. - The type of the key of dictionary. - The type of the value of dictionary. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Returns count of the dictionary. - - A collection. This value will not be null. - The count of the . - - - - Adds the deserialized item to the collection on specific manner - to implement . - - The dictionary to be added. - The key to be added. - The value to be added. - - This implementation always throws it. - - - - - Provides basic features for non-dictionary generic collection serializers. - - The type of the collection. - The type of the item of the collection. - - This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. - If you cannot use this class, you can implement your own serializer which inherits and implements . - - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Creates a new collection instance with specified initial capacity. - - - The initial capacy of creating collection. - Note that this parameter may 0 for non-empty collection. - - - New collection instance. This value will not be null. - - - An author of could implement unpacker for non-MessagePack format, - so implementer of this interface should not rely on that reflects actual items count. - For example, JSON unpacker cannot supply collection items count efficiently. - - - - - - Deserializes collection items with specified and stores them to . - - which unpacks values of resulting object tree. This value will not be null. - Collection that the items to be stored. This value will not be null. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is not collection. - - - - - Deserializes collection items with specified and stores them to . - - The which unpacks values of resulting object tree. This value will not be null. - The collection that the items to be stored. This value will not be null. - The count of items of the collection in the msgpack stream. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - - - When implemented by derive class, - adds the deserialized item to the collection on specific manner - to implement . - - The collection to be added. - The item to be added. - - This implementation always throws it. - - - - - Provides common implementation of - for collection types which do not implement . - - The type of the collection. - The type of the item of collection. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - is not serializable etc. - - - - - Defines common interface for serializers which can genereate new empty instance. - - - All custom manually implemented or automatically generated serializers which treat collection (that is, they return objects implementing except few exceptions like ). - - - - - Creates a new collection instance with specified initial capacity. - - - The initial capacy of creating collection. - Note that this parameter may 0 for non-empty collection. - - New collection instance. This value will not be null. - - An author of could implement unpacker for non-MessagePack format, - so implementer of this interface should not rely on that reflects actual items count. - For example, JSON unpacker cannot supply collection items count efficiently. - - - - - Provides common implementation of - for collection types which implement . - - The type of the collection. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - is not serializable etc. - - - - - Provides basic features for non-generic dictionary serializers. - - The type of the dictionary. - - This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. - If you cannot use this class, you can implement your own serializer which inherits and implements . - - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - is not serializable etc. - - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. This value will not be null. - Deserialized object. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is abstract type. - - - This method invokes , and then fill deserialized items to resultong collection. - - - - - Creates a new collection instance with specified initial capacity. - - - The initial capacy of creating collection. - Note that this parameter may 0 for non-empty collection. - - - New collection instance. This value will not be null. - - - An author of could implement unpacker for non-MessagePack format, - so implementer of this interface should not rely on that reflects actual items count. - For example, JSON unpacker cannot supply collection items count efficiently. - - - - - - Deserializes collection items with specified and stores them to . - - which unpacks values of resulting object tree. This value will not be null. - Collection that the items to be stored. This value will not be null. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is not collection. - - - - - Provides basic features for non-dictionary non-generic collection serializers. - - The type of the collection. - - This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. - If you cannot use this class, you can implement your own serializer which inherits and implements . - - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Creates a new collection instance with specified initial capacity. - - - The initial capacy of creating collection. - Note that this parameter may 0 for non-empty collection. - - - New collection instance. This value will not be null. - - - An author of could implement unpacker for non-MessagePack format, - so implementer of this interface should not rely on that reflects actual items count. - For example, JSON unpacker cannot supply collection items count efficiently. - - - - - - Deserializes collection items with specified and stores them to . - - The which unpacks values of resulting object tree. This value will not be null. - The collection that the items to be stored. This value will not be null. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is not collection. - - - - - Deserializes collection items with specified and stores them to . - - The which unpacks values of resulting object tree. This value will not be null. - The collection that the items to be stored. This value will not be null. - The count of items of the collection in the msgpack stream. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - - - When implemented by derive class, - adds the deserialized item to the collection on specific manner - to implement . - - The collection to be added. - The item to be added. - - This implementation always throws it. - - - - - Provides common implementation of - for collection types which implement . - - The type of the collection. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - is not serializable etc. - - - - - Provides common implementation of - for collection types which implement . - - The type of the collection. - - - - Initializes a new instance of the class. - - A which owns this serializer. - - The schema for collection itself or its items for the member this instance will be used to. - null will be considered as . - - - is null. - - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. This value will not be null. - Deserialized object. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - is abstract type. - - - This method invokes , and then fill deserialized items to resultong collection. - - - - - Adds the deserialized item to the collection on specific manner - to implement . - - The collection to be added. - The item to be added. - - - - Represents member's data contract. - - - - - Gets the name of the member. - - - The name of the member. - - - - - Gets the ID of the member. - - - The ID of the member. Default is -1. - - - - - Gets the nil implication. - - - The nil implication. - - - - - Initializes a new instance of the struct. - - The target member. - - - - Initializes a new instance of the struct. - - The target member. - The name of member. - The implication of the nil value for the member. - The ID of the member. This value cannot be negative and must be unique in the type. - - - - Initializes a new instance of the struct from . - - The target member. - The MessagePack member attribute. - - - - Defines behavior of built-in serializers to conversion of value. - - - - - Uses context, that is, Gregorian 0000-01-01 based, 100 nano seconds resolution. This value also preserves . - - - As of 0.6, this value has been become default. This option prevents accidental data loss. - - - - - Uses Unix epoc context, that is, Gregirian 1970-01-01 based, milliseconds resolution. - - - Many binding such as Java uses this resolution, so this option gives maximom interoperability. - - - - - Defines behavior of built-in serializers to conversion of value for specific member. - - - - - Uses systems default value. - - - The systems default . - - - - - Uses context, that is, Gregorian 0000-01-01 based, 100 nano seconds resolution. This value also preserves . - - - As of 0.6, this value has been become default. This option prevents accidental data loss. - - - - - Uses Unix epoc context, that is, Gregirian 1970-01-01 based, milliseconds resolution. - - - Many binding such as Java uses this resolution, so this option gives maximom interoperability. - - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - Helper methods for date time message pack serializer. - - - - - Determines for the target. - - Context information. - The method argued by the member. - Determined for the target. - - is null. - - - - - Repository of known concrete collection type for abstract collection type. - - - - - Gets the default type for the collection. - - Type of the abstract collection. - - Type of default concrete collection. - If concrete collection type of , then returns null. - - - is null. - - - By default, following types are registered: - - - Abstract Collection Type - Concrete Default Collection Type - - - - - - - - - - - ISet{T} (.NET 4 or lator) - - - - - - - - - - - - - of . - - - - of . - - - - of . - - - - - - - - - - - Registers the default type of the collection. - - Type of the abstract collection. - Default concrete type of the . - - is null. - Or is null. - - - is not collection type. - Or is abstract class or interface. - Or is open generic type but is closed generic type. - Or is closed generic type but is open generic type. - Or does not have same arity for . - Or is not assignable to - or the constructed type from will not be assignable to the constructed type from . - - - If you want to overwrite default type for collection interfaces, you can use this method. - Note that this method only supports collection interface, that is subtype of the interface. - - If you register invalid type for , then runtime exception will be occurred. - For example, you register of and pair, but it will cause runtime error. - - - - - - - Unregisters the default type of the collection. - - Type of the abstract collection. - - true if default collection type is removed successfully; - otherwise, false. - - - - - Implements non-generic or common portion of abstract collection serializers. - - - - - Provides runtime selection ability for serialization. - - - - - serializer using Unix Epoc or native representation. - - - - - Provides runtime selection ability for serialization. - - - - - Provides runtime selection ability for serialization. - - - - - Defines serializer factory for well known structured types. - - - - - Determines whether the specified type is supported from this class. - - The type to be determined. - The known of the . - true to prefer reflection based collection serializers instead of dyhnamic generated serializers. - true when the is supported; otherwise, false. - - - - Defines non-generic factory method for built-in serializers which require generic type argument. - - - - - Defines non-generic factory method for 'universal' serializers which use general collection features. - - - - - Invokes in deserializaton manner. - - . - A deserialized value. - is not expected type. - - - - serializer using native representation. - - - - - serializer using native representation. - - - - - Provides default implementation for . - - The type of keys of the . - The type of values of the . - - - - Provides default implementation for . - - The type of items of the . - - - - serializer using Unix Epoc representation. - - - - - serializer using native representation. - - - - - Determines emitter strategy. - - - - - Caches serializers for the members (de)serialization. - It is default. - - - - - Uses code DOM code generation to (de)serialization. - It requires a long time but prevents runtime code generation at all. - - - - - Uses reflection to (de)serialization. - It requires additional resources but may work on most environment. - - - - - An for . - - - - - Create new for specified . - - The target type of the serializer. - The collection traits of . - The base class of the serializer. - . - - - - Generates codes for this context. - - A collection which correspond to genereated codes. - - - - A code generation context for . - - - - - Gets or sets the to emit IL for current method. - - - The to emit IL for current method. - - - - - Gets the . - - - The . - - - - - Gets the type of the serializer. - - Type of the serialization target. - Type of the serializer. - - - - Initializes a new instance of the class. - - The serialization context. - Type of the serialization target. - - The factory for to be used. - - - - - An implementation of with . - - - - - Initializes a new instance of the class for instance creation. - - The type of serialization target. - The collection traits of the serialization target. - - - - Represents code construct for s. - - - - - Gets the context type of this construct. - - - The context type of this construct. - This value will not be null, but might be . - - - A context type represents the type of the evaluation context. - - - - - Gets a value indicating whether this instance is terminating. - - - true if this instruction terminates method; otherwise, false. - - - - - Initializes a new instance of the class. - - The type. - - - - Evaluates this construct that is executing this construct as instruction. - - The . - - This construct does not have eval semantics. - - - - - Loads value from the storage represented by this construct. - - The . - - true, if value type value should be pushed its address instead of bits; otherwise, false. - - - This construct does not have load value semantics. - - - - - Stores value to the storage represented by this construct. - - The . - - This construct does not have store value semantics. - - - - - Evaluates this construct as branch instruction. - - The . - The which points the head of 'else' instructions. - - This construct does not have branch semantics. - - - - - Represents IL method generation context. - - - - - Defines common features and interfaces for . - - - - - Get the appropriate for the current configuration. - - - The appropriate for the current configuration. - This value will not be null. - - - - - Get the appropriate for specified options. - - . - - The appropriate for specified options. - This value will not be null. - - - - - Get the singleton instance for can-collect mode. - - - - - Get the singleton instance for can-dump mode. - - - - - Get the singleton instance for fast mode. - - - - - Get the dumpable with specified brandnew assembly builder. - - An assembly builder which will store all generated types. - - The appropriate to generate pre-cimplied serializers. - This value will not be null. - - - - - Creates new which corresponds to the specified . - - The specification of the serializer. - Type of the base class of the serializer. - New which corresponds to the specified . - - - - Creates new which corresponds to the specified . - - The . - The specification of the serializer. - New which corresponds to the specified . - - - - Defines common features for emitters. - - - - - Initializes a new instance of the class. - - The host . - The specification of the serializer. - Type of the base class of the serializer. - Set to true when is debuggable. - - - - Regisgters specified field to the current emitting session. - - The name of the field. - The type of the field. - . - - - - Gets the IL generator to implement specified method override. - - The name of the method. - - The IL generator to implement specified method override. - This value will not be null. - - - - - Gets the IL generator to implement specified private instance method. - - The name of the method. - true for static method. - The type of the method return value. - The types of the method parameters. - - The IL generator to implement specified method override. - This value will not be null. - - - - - Initializes a new instance of the class for enum. - - A . - The host . - The specification of the serializer. - Set to true when is debuggable. - - - - Creates the serializer type built now and returns its new instance. - - The to holds serializers. - The which determines serialization form of the enums. - - Newly built instance. - This value will not be null. - - - - - Creates instance constructor delegates. - - A delegate for serializer constructor. - - - - Regisgters of target type usage to the current emitting session. - - The type of the member to be serialized/deserialized. - The enum serialization method of the member to be serialized/deserialized. - The date time conversion method of the member to be serialized/deserialized. - The schema for polymorphism support. - The delegate to provide constructs to emit schema regeneration codes. - . - - - - Regisgters usage to the current emitting session. - - The to be registered. - - to emit serializer retrieval instructions. - The 1st argument should be to emit instructions. - The 2nd argument should be argument index of the serializer holder, normally 0 (this pointer). - This value will not be null. - - - - - Regisgters usage to the current emitting session. - - The to be registered. - - to emit serializer retrieval instructions. - The 1st argument should be to emit instructions. - The 2nd argument should be argument index of the serializer holder, normally 0 (this pointer). - This value will not be null. - - - - - Creates the serializer type built now and returns its new instance. - - The to holds serializers. - The builder which implements actions initialization emit. - The information of the target. - The for this instance. - - Newly built instance. - This value will not be null. - - - - - Creates the serializer type built now and returns its constructor. - - The context. - The builder which implements actions initialization emit. - The information of the target - - Newly built type constructor. - This value will not be null. - - - - - Represents individual enum typed member serialization method. - - - - - Respects setting in enum type itself or system default. - - - - - Enums are serialized with their name. It is more torelant to versioning but less efficient. - - - - - Enums are serialized with their underlying value. It is more efficient but less torelant to versioning. - - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - Helper methods for enum message pack serializer. - - - - - Determines for the target. - - Context information. - The target enum type. - The method argued by the member. - Determined for the target. - - is null. - Or is null. - - - - - Implements for enums. - This class accepts as a provider parameter. - - - - - Initializes a new instance of the class. - - A type of the enum. - The serializer implements . - - - - Gets a serializer instance for specified parameter. - - A serialization context which holds global settings. - A provider specific parameter. - - A serializer object for specified parameter. - - - - - Defines basic features for enum object serializers. - - The type of enum type itself. - - This class supports auto-detect on deserialization. So the constructor parameter only affects serialization behavior. - - - - - Initializes a new instance of the class. - - A which owns this serializer. - The which determines serialization form of the enums. - TEnum is not enum type. - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - - - Packs enum value as its underlying value. - - The packer. - The enum value to be packed. - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. This value will not be null. - Deserialized object. - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - Failed to deserialize object due to invalid unpacker state, stream content, or so. - - - - - Unpacks enum value from underlying integral value. - - The message pack object which represents some integral value. - - An enum value. - - The type of integral value is not compatible with underlying type of the enum. - - - - Represents enum type serialization method. - - - - - Enums are serialized with their name. It is more torelant to versioning but less efficient. - - - - - Enums are serialized with their underlying value. It is more efficient but less torelant to versioning. - - - - - Implements mapping table between known ext type codes and names. - - - Well-known (pre-defined) ext type names are defined in , and their default mapped codes are found in . - - - - - - Gets a mapped byte to the specified ext type name. - - The name of the ext type. - - The byte code for specified ext type in the current context. - - is null. - is empty. - is not registered as known ext type name. - - - - Adds the known ext type mapping. - - The name of the ext type. - The ext type code to be mapped. - - true if AND were not registered and then newly registered; false, otherwise. - - is null. - is empty. - is greater than 0x7F. - - - - Removes the mapping with specified name. - - The name of the ext type. - - true if was registered and has been removed successfully; false, otherwise. - - is null. - is empty. - - - - Removes the mapping with specified code. - - The type code of the ext type. - - true if was registered and has been removed successfully; false, otherwise. - - is greater than 0x7F. - - - - Clears all mappings. - - - - - Returns an enumerator that iterates through the collection. - - - A that can be used to iterate through the collection. - - - This method causes internal collection copying, so this makes O(n) time. - - - - - Represents customizable enum serializer. - - - - - Gets a copy with specified method. - - Enum serialization method. - This instance or copied instance corresponds to the specified serialization method. - - - - Utilities related to member/type ID. - - - - - Defines non-generic message pack serializer interface. - - - - - Serialize specified object with specified . - - which packs values in . - Object to be serialized. - - is null. - - - is not compatible for this serializer. - - - Failed to serialize object. - - - The type of is not serializable even if it can be deserialized. - - - - - - Deserialize object with specified . - - which unpacks values of resulting object tree. - The deserialized object. - - is null. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - The type of deserializing is not serializable even if it can be serialized. - - - - - - Deserialize collection items with specified and stores them to . - - which unpacks values of resulting object tree. - Collection that the items to be stored. - - is null. - Or is null. - - - is not compatible for this serializer. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - The type of deserializing is not mutable collection. - - - - - - Defines non-generic message pack serializer interface for byte array which contains a single object. - - - - - Serialize specified object to the array of . - - Object to be serialized. - An array of which stores serialized value. - - Failed to serialize object. - - - The type of is not serializable even if it can be deserialized. - - - - - - Deserialize a single object from the array of which contains a serialized object. - - An array of serialized value to be stored. - The deserialized object. - - is null. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - The type of deserializing is not serializable even if it can be serialized. - - - - - This method assumes that contains single serialized object dedicatedly, - so this method does not return any information related to actual consumed bytes. - - - This method is a counter part of . - - - - - - Defines common interface for parameter of method and its template methods. - - - - - Defines common interface for parameter of method and its template methods. - - - - - Defines internal common interface for serializer generator configuration objects. - - - - - Gets or sets the output directory for generating artifacts. - - - The output directory for generating artifacts. - Specifying null causes reset to the default location. - - Specified value is not valid for directory path. - - - - Gets or sets the serialization method to pack object. - - - A value of . - - Specified value is not valid . - - - - Gets or sets the default enum serialization method for generating enum type serializers. - - - A value of . - - Specified value is not valid . - - - - Gets or sets a value indicating whether recursively generates dependent types which do not have built-in serializer or not. - - - true if recursively generates dependent types which do not have built-in serializer; otherwise, false. - - - - - Gets or sets a value indicating whether prefer reflection based collection serializers instead of dyhnamic generated serializers. - - - true if prefer reflection based collection serializers instead of dyhnamic generated serializers; otherwise, false. - - - - - Gets or sets a value indicating whether creating Nullable of T serializers for value type serializers. - - - true if creates Nullable of T serializers for value type serializers; otherwise, false. - - - - - Validates this instance state. - - This object is not in valid state. - - - - Lazy initialized serializer which delegates actual work for the other serializer implementation. - - - The type of target type. - - - This serializer is intended to support self-composit structure like directories or XML nodes. - - - - - Initializes a new instance of the class. - - - The serialization context to support lazy retrieval. - - A provider parameter to be passed in future. - - - - Marks that this or typed member has special characteristics on MessagePack serialization. - - - If this attributes is used for incompatible typed members, this attribute will be ignored. - - - - - Gets or sets the default serialization method for this enum typed member. - - - The default serialization method for this enum typed member. - Note that the method for the enum type will be overrided with this. - - - - - Initializes a new instance of the class. - - - - - Marks this constructor used as deserialization constructor. - - - - This attribute only used once per type. - If there are multiple constructors marked with this attribute in the type, will be onccured in serializer generation. - - - Marking with this attribute is not required to generate serializer which uses constructor in deserialization, but this attribute is available in following purposes: - - - - Indicating force constructor deserialization instead of member deserialization. - The serializer generation prefer member (that is using property setters and fields) deserialization as possible. - You can indicate to forcibly use constructor even when there are any setters/writable fields. - - - If you do not specify this attribute in this case, member deserialization strategy will be used. - - - - - Clarify the constructor which wil be used in deserialization when there are multiple constructors declared in the type. - Although the serializer generator avoids default constructor and non-public constructors, it cannot resolve target constructor when there are multiple candidates (that is, public, parameterized constructors). - - - If you do not specify this attribute in this case, serializer generator throws . - - - - - - - - - Initializes a new instance of the class. - - - - - Marks that this enum type has special characteristics on MessagePack serialization. - - - Enum types which are not marked with this attribute will be serialized as value. - - - - - Gets or sets the default serialization method for this enum type. - - - The default serialization method for this enum type. - Note that the method for individual enum typed members will be overrided with . - - - - - Initializes a new instance of the class. - - - - - Marks that this enum typed member has special characteristics on MessagePack serialization. - - - If this attributes is used for non-enum typed members, this attribute will be ignored. - - - - - Gets or sets the default serialization method for this enum typed member. - - - The default serialization method for this enum typed member. - Note that the method for the enum type will be overrided with this. - - - - - Initializes a new instance of the class. - - - - - Marks the field or the property should not be serialized/deserialized with MessagePack for CLI serialization mechanism. - - - - - Initializes a new instance of the class. - - - - - Marks that the runtime type of this member should be encoded with closed type codes for polymorphism. - - - - When you apply this attribute to a member, the member - will be serialized as 2 element array as [ <type-code>, <actual-value (array or map)>] format - where the type-code is utf-8 encoded string representing type in your application (system) context. - When you interop with other launages, the deserializer will be able to deserialize object which is actual type when serialized with interoperability. - - You must use one-to-one relationship between type-code and the type. - - - - - - Gets a type code to be bound. - - - A type code to be bound. - - - - - Gets the type of the binding for . - - - The binding for . - - - - - Initializes a new instance of the class. - - A string type code to be bound. - The binding for . - - - - Marks that the runtime type of items/values of this collection/dictionary should be encoded with closed type codes for polymorphism. - - - - When you apply this attribute to a member, the items/values of the collection/dictionary - will be serialized as 2 element array as [ <type-code>, <actual-value (array or map)>] format - where the type-code is utf-8 encoded string representing type in your application (system) context. - When you interop with other launages, the deserializer will be able to deserialize object which is actual type when serialized with interoperability. - - You must use one-to-one relationship between type-code and the type. - - - - - - Gets a type code to be bound. - - - A type code to be bound. - - - - - Gets the type of the binding for . - - - The binding for . - - - - - Initializes a new instance of the class. - - A string type code to be bound. - The binding for . - - - - Marks that the runtime type of keys of this dictionary should be encoded with closed type codes for polymorphism. - - - - When you apply this attribute to a member, the keys of the dictionary - will be serialized as 2 element array as [ <type-code>, <actual-value (array or map)>] format - where the type-code is utf-8 encoded string representing type in your application (system) context. - When you interop with other launages, the deserializer will be able to deserialize object which is actual type when serialized with interoperability. - - You must use one-to-one relationship between type-code and the type. - - - - - - Gets a type code to be bound. - - - A type code to be bound. - - - - - Gets the type of the binding for . - - - The binding for . - - - - - Initializes a new instance of the class. - - A string type code to be bound. - The binding for . - - - - Marks that the runtime type of specified item of the tuple should be encoded with closed type codes for polymorphism. - - - - When you apply this attribute to a member, the item of tuple, - will be serialized as 2 element array as [ <type-code>, <actual-value (array or map)>] format - where the type-code is utf-8 encoded string representing type in your application (system) context. - When you interop with other launages, the deserializer will be able to deserialize object which is actual type when serialized with interoperability. - - You must use one-to-one relationship between type-code and the type. - - - - - - Gets a type code to be bound. - - - A type code to be bound. - - - - - Gets the type of the binding for . - - - The binding for . - - - - - Gets the target tuple item's number. - - - The 1-based target tuple item's number. - - - - If this value is not valid for the tuple, this whole instance should be ignored. - - - If same values are specified multiply, the result is undefined. - - - - - - Initializes a new instance of the class. - - The 1-based target item number of the tuple. The attribute which has invalid value should be ignored. - A string type code to be bound. - The binding for . - - - - Marks a field or a property to be serialized with MessagePack Serializer and defines some required informations to serialize. - - - - - Gets the ID of the member. - - - The ID of the member. - - - - - Gets or sets the name of this member. - - - The name which will be used in map key on serialized MessagePack stream. - - - - - Gets or sets the implication of the nil value. - - - The implication of the nil value. - Default value is . - - - - - Initializes a new instance of the class. - - - The ID of the member. This value cannot be negative and must be unique in the type. - - - - - Marks that the runtime type of this member should be encoded with type information for polymorphism. - - - - When you apply this attribute to a member, the member will be serialized with .NET specific type information, - so deserializer will be able to deserialize object which is actual type when serialized instead of interoperability. - Because non-.NET enviroments (Java, Ruby, Go, etc.) cannot interpret .NET native type identifier, - you should not use this attribute when the serialized stream will be possible to be used from non-.NET environment. - The typed object will be encoded as 2 elements array as follows, so your deserializer can skip type information as needed: - [ <type-info>, <actual-value (array or map)>] - In this point, type-info will be encoded as compressed assembly qualified name as follows: - [ <compressed type full name>, <assembly simple name>, <version binary>, <culture string>, <public key token binary>] - If the type full name starts with its assembly simple name, then the prefix matched to assembly simple name will be omitted - (as a result, compressed type name starts with dot). - - You should use this attribute CAREFULLY when you deserialize data from outside, because this feature can inject arbitary process in your code through - constructor and some virtual methods if exist. - It is highly recommended avoid using type as member's declaring type, - you should specify your base class which and derived typed are fully controled under your organization instead. - It mitigate chance of potential exploits. - - - - - - Initializes a new instance of the class. - - - - - Marks that the runtime type of items/values of this collection/dictionary should be encoded with type information for polymorphism. - - - - When you apply this attribute to a member, the items/values of the collection/dictionary will be serialized with .NET specific type information, - so deserializer will be able to deserialize object which is actual type when serialized instead of interoperability. - Because non-.NET enviroments (Java, Ruby, Go, etc.) cannot interpret .NET native type identifier, - you should not use this attribute when the serialized stream will be possible to be used from non-.NET environment. - The typed object will be encoded as 2 elements array as follows, so your deserializer can skip type information as needed: - [ <type-info>, <actual-value (array or map)>] - In this point, type-info will be encoded as compressed assembly qualified name as follows: - [ <compressed type full name>, <assembly simple name>, <version binary>, <culture string>, <public key token binary>] - If the type full name starts with its assembly simple name, then the prefix matched to assembly simple name will be omitted - (as a result, compressed type name starts with dot). - - You should use this attribute CAREFULLY when you deserialize data from outside, because this feature can inject arbitary process in your code through - constructor and some virtual methods if exist. - It is highly recommended avoid using type as member's declaring type, - you should specify your base class which and derived typed are fully controled under your organization instead. - It mitigate chance of potential exploits. - - - - - - Initializes a new instance of the class. - - - - - Marks that the runtime type of keys of this dictionary should be encoded with type information for polymorphism. - - - - When you apply this attribute to a member, the keys of the dictionary will be serialized with .NET specific type information, - so deserializer will be able to deserialize object which is actual type when serialized instead of interoperability. - Because non-.NET enviroments (Java, Ruby, Go, etc.) cannot interpret .NET native type identifier, - you should not use this attribute when the serialized stream will be possible to be used from non-.NET environment. - The typed object will be encoded as 2 elements array as follows, so your deserializer can skip type information as needed: - [ <type-info>, <actual-value (array or map)>] - In this point, type-info will be encoded as compressed assembly qualified name as follows: - [ <compressed type full name>, <assembly simple name>, <version binary>, <culture string>, <public key token binary>] - If the type full name starts with its assembly simple name, then the prefix matched to assembly simple name will be omitted - (as a result, compressed type name starts with dot). - - You should use this attribute CAREFULLY when you deserialize data from outside, because this feature can inject arbitary process in your code through - constructor and some virtual methods if exist. - It is highly recommended avoid using type as member's declaring type, - you should specify your base class which and derived typed are fully controled under your organization instead. - It mitigate chance of potential exploits. - - - - - - Initializes a new instance of the class. - - - - - Marks that the runtime type of specified item of the tuple should be encoded with type information for polymorphism. - - - - When you apply this attribute to a member, the item of tuple will be serialized with .NET specific type information, - so deserializer will be able to deserialize object which is actual type when serialized instead of interoperability. - Because non-.NET enviroments (Java, Ruby, Go, etc.) cannot interpret .NET native type identifier, - you should not use this attribute when the serialized stream will be possible to be used from non-.NET environment. - The typed object will be encoded as 2 elements array as follows, so your deserializer can skip type information as needed: - [ <type-info>, <actual-value (array or map)>] - In this point, type-info will be encoded as compressed assembly qualified name as follows: - [ <compressed type full name>, <assembly simple name>, <version binary>, <culture string>, <public key token binary>] - If the type full name starts with its assembly simple name, then the prefix matched to assembly simple name will be omitted - (as a result, compressed type name starts with dot). - - You should use this attribute CAREFULLY when you deserialize data from outside, because this feature can inject arbitary process in your code through - constructor and some virtual methods if exist. - It is highly recommended avoid using type as member's declaring type, - you should specify your base class which and derived typed are fully controled under your organization instead. - It mitigate chance of potential exploits. - - - - - - Gets the target tuple item's number. - - - The 1-based target tuple item's number. - - - - If this value is not valid for the tuple, this whole instance should be ignored. - - - If same values are specified multiply, the result is undefined. - - - - - - Initializes a new instance of the class. - - The 1-based target item number of the tuple. The attribute which has invalid value should be ignored. - - - - Defines non-generic interface of serializers and provides entry points for usage. - - - You cannot derived from this class directly, use instead. - This class is intended to guarantee backward compatibilities of non generic API. - - - - - Gets a which owns this serializer. - - - A which owns this serializer. - - - - - Gets the packer compatibility options for this instance. - - - The packer compatibility options for this instance - - - - - Gets the capability flags for this instance. - - - The capability flags for this instance. - - - - - Initializes a new instance of the class. - - A which owns this serializer. - The for new packer creation. - The capability flags for this instance. - - - - Serialize specified object with specified . - - which packs values in . - Object to be serialized. - - - - - Deserialize object with specified . - - which unpacks values of resulting object tree. - - The deserialized object. - - - - - - Deserialize collection items with specified and stores them to . - - which unpacks values of resulting object tree. - Collection that the items to be stored. - - - - - Serialize specified object to the array of . - - Object to be serialized. - - An array of which stores serialized value. - - - - - - Deserialize a single object from the array of which contains a serialized object. - - An array of serialized value to be stored. - - The deserialized object. - - - - This method assumes that contains single serialized object dedicatedly, - so this method does not return any information related to actual consumed bytes. - - - This method is a counter part of . - - - - - - - Creates new instance with . - - Target type. - - New instance to serialize/deserialize the object tree which the top is . - - - - - Creates new instance with specified . - - Target type. - - to store known/created serializers. - - - New instance to serialize/deserialize the object tree which the top is . - - - is null. - - - - - Gets existing or new instance with default context (). - - Target type. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - This method simply invokes with for the context. - - - - - Gets existing or new instance with default context (). - - Target type. - A provider specific parameter. See remarks section for details. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - This method simply invokes with for the context. - - - - - Gets existing or new instance with specified . - - Target type. - - to store known/created serializers. - - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - is null. - - - This method simply invokes with null for the providerParameter. - - - - - Gets existing or new instance with specified . - - Target type. - - to store known/created serializers. - - A provider specific parameter. See remarks section for details. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - is null. - - - - This method simply invokes , so see the method description for details. - - - Currently, only following provider parameters are supported. - - - Target type - Provider parameter - - - or its descendants. - . The returning instance corresponds to this value for serialization. - - - null is valid value for and it indeicates default behavior of parameter. - - - - - - Creates new instance with . - - Target type. - - New instance to serialize/deserialize the object tree which the top is . - - - is null. - - - To avoid boxing and strongly typed API is prefered, use instead when possible. - - - - - Creates new instance with specified . - - Target type. - - to store known/created serializers. - - - New instance to serialize/deserialize the object tree which the top is . - - - is null. - Or, is null. - - - To avoid boxing and strongly typed API is prefered, use instead when possible. - - - - - Gets existing or new instance with default context (). - - Target type. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - is null. - - - - This method simply invokes , so see the method description for details. - - - Although is preferred, - this method can be used from non-generic type or methods. - - - - - - Gets existing or new instance with default context (). - - Target type. - A provider specific parameter. See remarks section for details. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - is null. - - - - This method simply invokes , so see the method description for details. - - - Although is preferred, - this method can be used from non-generic type or methods. - - - - - - Gets existing or new instance with specified . - - Target type. - - to store known/created serializers. - - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - is null. - Or, is null. - - - - This method simply invokes , so see the method description for details. - - - Although is preferred, - this method can be used from non-generic type or methods. - - - - - - Gets existing or new instance with specified . - - Target type. - - to store known/created serializers. - - A provider specific parameter. See remarks section for details. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - is null. - Or, is null. - - - - This method simply invokes , so see the method description for details. - - - Although is preferred, - this method can be used from non-generic type or methods. - - - - - - Directly deserialize specified MessagePack as tree. - - The stream which contains deserializing data. - A which is root of the deserialized MessagePack object tree. - - is null. - - - This method is convinient wrapper for for . - - You cannot override this method behavior because this method uses private instead of default context which is able to be accessed via . - - - - - - Try to prepare specified type for some AOT(Ahead-Of-Time) compilation environment. - If the type will be used in collection or dictionary, use and/or instead. - - The type to be prepared. Normally, this should be value type. - - - Currently, this method only works in Unity build. - This method does not any work for other environments(and should be removed on JIT/AOT), but exists to simplify the application compilation. - It is recommended to use this method on start up code to reduce probability of some AOT errors. - - - Please note that this method do not ensure for full linkage for AOT. - - - - - - Try to prepare specified types which will be used as dictionary keys and values for some AOT(Ahead-Of-Time) compilation environment. - If the type will be used in collection use instead. - - The key type to be prepared. Normally, this should be value type. - The value type to be prepared. Normally, this should be value type. - - - Currently, this method only works in Unity build. - This method does not any work for other environments(and should be removed on JIT/AOT), but exists to simplify the application compilation. - It is recommended to use this method on start up code to reduce probability of some AOT errors. - - - Please note that this method do not ensure for full linkage for AOT. - - - Currently, this method prepares and also invokes implicitly. - - - - - - Try to prepare specified type which will be used as collection elements for some AOT(Ahead-Of-Time) compilation environment. - If the type will be used in dictionary, use instead. - - The element type to be prepared. Normally, this should be value type. - - - Currently, this method only works in Unity build. - This method does not any work for other environments(and should be removed on JIT/AOT), but exists to simplify the application compilation. - It is recommended to use this method on start up code to reduce probability of some AOT errors. - - - Please note that this method do not ensure for full linkage for AOT. - - - Currently, this method prepares , , and . - In addition, this method also invokes implicitly. - - - - - - Defines convinient extension methods for interfaces. - - - - - Serializes specified object to the with default . - - object. - Destination . - Object to be serialized. - - is null. - Or is null. - - - Failed to serialize . - - - - - Serializes specified object to the . - - object. - Destination . - Object to be serialized. - A which specifies compatibility options. - - is null. - Or is null. - - - Failed to serialize . - - - - - Deserialize object from the . - - object. - Source . - Deserialized object. - - is null. - Or is null. - - - Failed to deserialize from . - - - - - Defines basic features and interfaces for serializer provider which is stored in repository and controlls returning serializer with its own parameter. - - - - - Initializes a new instance of the class. - - - - - Gets a serializer instance for specified parameter. - - A serialization context which holds global settings. - A provider specific parameter. - A serializer object for specified parameter. - - - - Defines base contract for object serialization. - - Target type. - - - This class implements strongly typed serialization and deserialization. - - - When the underlying stream does not contain strongly typed or contains dynamically typed objects, - you should use directly and take advantage of . - - - - - - - - Initializes a new instance of the class with . - - - This method supports backword compatibility with 0.3. - - - - - Initializes a new instance of the class with default context.. - - The for new packer creation. - - This method supports backword compatibility with 0.4. - - - - - Initializes a new instance of the class. - - A which owns this serializer. - is null. - - - - Initializes a new instance of the class with explicitly specified compatibility option. - - A which owns this serializer. - The for new packer creation. - is null. - - This method also supports backword compatibility with 0.4. - - - - - Initializes a new instance of the class. - - A which owns this serializer. - A serializer calability flags represents capabilities of this instance. - is null. - - - - Initializes a new instance of the class with explicitly specified compatibility option. - - A which owns this serializer. - The for new packer creation. - A serializer calability flags represents capabilities of this instance. - is null. - - This method also supports backword compatibility with 0.4. - - - - - Serializes specified object to the . - - Destination . - Object to be serialized. - - is null. - - - Failed to serialize object. - - - is not serializable even if it can be deserialized. - - - - - - Deserialize object from the . - - Source . - The deserialized object. - - is null. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - is not serializable even if it can be serialized. - - - - - - Serializes specified object with specified . - - which packs values in . - Object to be serialized. - - is null. - - - Failed to serialize object. - - - is not serializable even if it can be deserialized. - - - - - - Serializes specified object with specified . - - which packs values in . This value will not be null. - Object to be serialized. - - Failed to serialize object. - - - is not serializable even if it can be deserialized. - - - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. - The deserialized object. - - is null. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - is not serializable even if it can be serialized. - - - - - - Unpacks the nil value. - - - A valid value of which represents 'null' state. - - - - This method is invoked from method when the current is nil. - - - The implementation of this class returns null for nullable types (that is, all reference types and ); otherwise, throws . - - - Custom serializers can override this method to provide custom nil representation. For example, built-in serializer overrides this method to return instead of null. - - - - - - Deserializes object with specified . - - which unpacks values of resulting object tree. This value will not be null. - The deserialized object. - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - is not serializable even if it can be serialized. - - - - - - Deserializes collection items with specified and stores them to . - - which unpacks values of resulting object tree. - Collection that the items to be stored. - - is null. - Or is null. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - is not mutable collection. - - - - - - Deserializes collection items with specified and stores them to . - - which unpacks values of resulting object tree. This value will not be null. - Collection that the items to be stored. This value will not be null. - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - is not mutable collection. - - - - - - Serializes specified object to the array of . - - Object to be serialized. - An array of which stores serialized value. - - Failed to serialize object. - - - is not serializable even if it can be deserialized. - - - - - - Deserializes a single object from the array of which contains a serialized object. - - An array of serialized value to be stored. - The deserialized object. - - is null. - - - Failed to deserialize object. - - - Failed to deserialize object due to invalid stream. - - - Failed to deserialize object due to invalid stream. - - - The type of deserializing is not serializable even if it can be serialized. - - - - - This method assumes that contains single serialized object dedicatedly, - so this method does not return any information related to actual consumed bytes. - - - This method is a counter part of . - - - - - - generic method. - - - - - generic method. - - - - - generic method. - - - - - generic method. - - - - - Specifies nil implication in serialization/deserialization. - - - - - A nil is interpreted as default value of the member. - - - - This value affects only deserialization. - - - If the unpacking value is nil, the serializer will not set any value to the member. - - - This value corresponds to optional on the IDL. - - - This is default option because the most safe option. - - - - - - A nil is interpreted as null. - - - - This value affects only deserialization. - - - If the unpacking value is nil, the serializer will set null to the member. - If the member is non-nullable value type and the packed value is nil, then will be thrown. - - - This value corresponds to nullable required on the IDL. - - - If the destination end point sends nil for the value type member like type, - you can avoid the exception with change the type of the member to nullable value type. - - - - - - A nil is prohibitted. - - - - This value affects both of serialization and deserialization. - - - If the packing value is null or the unpacking value is nil, - the serializer will throw exception. - - - This value corresponds to required on the IDL. - - - When you specify this value to newly added member, - it means that you BREAK backword compatibility. - - - - - - Defines base features to handle nil implication. - - The type of the actual action for handking. - The type of the condition for packing value nil check. - The type of the implementation specific on-packing methods parameter. - The type of the implementation specific on-unpacked methods parameter. - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - Defines serialization helper APIs. - - - - - Packs object to msgpack array. - - The type of the packing object. - The packer. - The object to be packed. - - Delegates each ones unpack single member in order. - The 1st argument will be and 2nd argument will be . - - The unpacked object. - - is null. - Or, is null. - - - - - Packs object to msgpack map. - - The type of the packing object. - The packer. - The object to be packed. - - Delegates table each ones unpack single member and their keys correspond to unpacking membmer names. - The 1st argument will be and 2nd argument will be . - - - is null. - Or, is null. - - - - - Defines internal protocol betwenn polymorphic serializers and collection serializers to accomplish polymorphism. - - - - - Common interfaces among polymorhic helper attributes. - - - - - Common interfaces among *Known*TypeAttrbutes. - - - - - Common(marker) interfaces among *Runtime*TypeAttrbutes. - - - - - Common interfaces among *TupleItemTypeAttributes. - - - - - Implements polymorphic serializer which uses closed known types and interoperable ext-type feature. - - The base type of the polymorhic member. - - - - Provides polymorphism for serializers. - - - - - - Implements polymorphic serializer which uses open types and non-interoperable ext-type tag and .NET type information. - - The base type of the polymorhic member. - - - - Implements type info encoding for type embedding. - - - - - Represents type info encoding. - - - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - - - A provider parameter to support polymorphism. - - - - - - Creates a new instance of the class for non-collection object which uses type embedding based polymorphism. - - The type of the serialization target. - A new instance of the class for non-collection object which uses type embedding based polymorphism. - is null. - - - - Creates a new instance of the class for non-collection object which uses ext-type code mapping based polymorphism. - - The type of the serialization target. - The code-type mapping which maps between ext-type codes and .NET s. - A new instance of the class for non-collection object which uses ext-type code mapping based polymorphism. - is null. - - - - Creates a new instance of the class for collection object which uses declared type or context specified concrete type. - - The type of the serialization target. - The schema for collection items of the serialization target collection. - A new instance of the class for collection object which uses declared type or context specified concrete type. - is null. - - - - Creates a new instance of the class for collection object which uses type embedding based polymorphism. - - The type of the serialization target. - The schema for collection items of the serialization target collection. - A new instance of the class for collection object which uses type embedding based polymorphism. - is null. - - - - Creates a new instance of the class for collection object which uses ext-type code mapping based polymorphism. - - The type of the serialization target. - The code type mapping which maps between ext-type codes and .NET s. - The schema for collection items of the serialization target collection. - A new instance of the class for collection object which uses ext-type code mapping based polymorphism. - is null. - - - - Creates a new instance of the class for dictionary object which uses declared type or context specified concrete type. - - The type of the serialization target. - The schema for dictionary keys of the serialization target dictionary. - The schema for dictionary values of the serialization target dictionary. - A new instance of the class for dictionary object which uses declared type or context specified concrete type. - is null. - - - - Creates a new instance of the class for dictionary object which uses type embedding based polymorphism. - - The type of the serialization target. - The schema for dictionary keys of the serialization target dictionary. - The schema for dictionary values of the serialization target dictionary. - A new instance of the class for dictionary object which uses type embedding based polymorphism. - is null. - - - - Creates a new instance of the class for dictionary object which uses ext-type code mapping based polymorphism. - - The type of the serialization target. - The code type mapping which maps between ext-type codes and .NET s. - The schema for dictionary keys of the serialization target dictionary. - The schema for dictionary values of the serialization target dictionary. - A new instance of the class for dictionary object which uses ext-type code mapping based polymorphism. - is null. - - - - Gets the type of the serialization target. - - - The type of the serialization target. This value can be null. - - - - - Gets the type of the polymorphism. - - - The type of the polymorphism. - - - - - Gets the code type mapping which maps between ext-type codes and .NET s. - - - The code type mapping which maps between ext-type codes and .NET s. - - - - - Gets the schema for child items of the serialization target collection/tuple. - - - The schema for child items of the serialization target collection/tuple. - - - - - Gets the schema for collection items of the serialization target collection. - - - The schema for collection items of the serialization target collection. - - - - - Gets the schema for dictionary keys of the serialization target collection. - - - The schema for collection items of the serialization target collection. - - - - - Default instance (null object). - - - - - ForPolymorphicObject( Type targetType ) - - - - - ForPolymorphicObject( Type targetType, IDictionary{byte, Type} codeTypeMapping ) - - - - - ForContextSpecifiedCollection( Type targetType, PolymorphismSchema itemsSchema ) - - - - - ForPolymorphicCollection( Type targetType, PolymorphismSchema itemsSchema ) - - - - - ForPolymorphicCollection( Type targetType, IDictionary{byte, Type} codeTypeMapping, PolymorphismSchema itemsSchema ) - - - - - ForContextSpecifiedDictionary( Type targetType, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) - - - - - ForPolymorphicDictionary( Type targetType, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) - - - - - ForPolymorphicDictionary( Type targetType, IDictionary{byte, Type} codeTypeMapping, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema ) - - - - - Represents children items type of - - - - - Leaf, that is no children schema. - - - - - Collection items, so children count is 1. - - - - - Dictionary keys and values, so children count is 2, index 0 is for keys, 1 is for values. - - - - - Specifies or target. - - - - - Applies to member type itself. - This option disables settings. - - - - - Applies to items of collection member type (values for dictionary). - This options causes entire attribute will be ignored for non-collection types. - - - - - Applies to keys of dictionary member type. - This options causes entire attribute will be ignored for non-dictionary types. - - - - - Applies to keys of dictionary member type. - This options causes entire attribute will be ignored for non-dictionary types. - - - - - Defines a type of the polymorphism. - - - - - No polymorphism. - - - - - Knwon ext-type code based polymorphism. - - - - - Non-interoperable type info embedding based polymorphism. - - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - Defines serialization helper reflection APIs. - - - - - Gets a specified even if the method is not publicly exposed. - - The type to be introspected. - The name of the method. - The parameter types of the method. - A object. - - This method is designed for property accessor for serialization, so this never return generic methods and static methods. - - - - - Gets a specified even if the field is not publicly exposed. - - The type to be introspected. - The name of the method. - A object. - - This method is designed for property accessor for serialization, so this never return static fields. - - - - - Implements reflection-based enum serializer for restricted platforms. - - - - - Implements reflection-based object serializer for restricted platforms. - - - - - Helper static methods for reflection serializers. - - - - - Defines non-generic factory method for 'universal' serializers which use general collection features. - - - - - Define utility extension method for generic type. - - - - - Determine whether the source type implements specified generic type or its built type. - - Target type. - Generic interface type. - - true if implements , - or built closed generic interface type; - otherwise false. - - - - - Get name of type without namespace and assembly name of itself and its generic arguments. - - Target type. - Simple name of type. - - - - Get full name of type including namespace and excluding assembly name of itself and its generic arguments. - - Target type. - Full name of type. - - - - Defines utility extension method for reflection API. - - - - - Determines whether specified can be assigned to source . - - The source type. - The type to compare with the source type. - - true if and represent the same type, - or if is in the inheritance hierarchy of , - or if is an interface that implements, - or if is a generic type parameter and represents one of the constraints of . - false if none of these conditions are true, or if is false. - - - - - Get IL friendly attributes string. - - . - IL friendly attributes string delimited by ASCII whitespace. - - - - Get IL friendly attributes string. - - . - IL friendly attributes string delimited by ASCII whitespace. - - - - Get IL friendly attributes string. - - . - IL friendly attributes string delimited by ASCII whitespace. - - - - like IL stream builder with tracing. - - - - - Emit 'call' or 'callvirt' appropriately. - - to be called. - - - - Emit property getter invocation. - Pre condition is there is target instance on the top of evaluation stack when is instance property. - Post condition are that target instance will be removed from the stack for instance property, and property value will be placed on there. - - for target property. - - - - Emit load 'this' pointer instruction (namely 'ldarg.0'). - Post condition is that the loaded value will be added on the evaluation stack. - - - - - Emit apprpriate 'ldarg.*' instruction. - Post condition is that the loaded value will be added on the evaluation stack. - - - Index of argument to be fetched. - - - - - Emit apprpriate 'ldloc.*' instruction. - Post condition is that the loaded value will be added on the evaluation stack. - - - Index of local variable to be fetched. - - - - - Emit array initialization code with initializer. - Pre condition is that the storing value is placed on the top of evaluation stack and its type is valid. - Post condition is that the stored value will be removed from the evaluation stack. - - - Index of local variable which stores the array. - - - - - Emit array initialization code without initializer. - Post condition is evaluation stack will no be modified as previous state. - Note that initialized array is not placed on the top of evaluation stack. - - of array element. This can be generaic parameter. - Size of array. - - - - Emit array element storing instructions. - Post condition is evaluation stack will no be modified as previous state. - - of array element. This can be generaic parameter. - - Delegate to emittion of array loading instruction. - 1st argument is this instance. - Post condition is that exactly one target array will be added on the top of stack and its element type is . - - - Delegate to emittion of array index. - 1st argument is this instance. - Post condition is that int4 or int8 type value will be added on the top of stack and its element type is . - - - - - Emit array element storing instructions. - Post condition is evaluation stack will no be modified as previous state. - - of array element. This can be generaic parameter. - - Delegate to emittion of array loading instruction. - 1st argument is this instance. - Post condition is that exactly one target array will be added on the top of stack and its element type is . - - - Delegate to emittion of array index. - 1st argument is this instance. - Post condition is that int4 or int8 type value will be added on the top of stack and its element type is . - - - Delegate to emittion of storing element loading instruction. - 1st argument is this instance. - Post condition is that exactly one storing element will be added on the top of stack and its type is compatible. - - - - - Emit efficient integer constant loading. - Post condition is that exactly one integer will be added on the top of stack. - - Integer value. - - - - Emit 'typeof' expression. - Post condition is instance for will be placed on the top of evaluation stack. - - Target . - - - - Get for end of method. - - - for end of method. - - - - - Get whether there are any exception blocks in current positon. - - - If there are any exception blocks in current positon then true; otherwise, false. - - - - - Get whether this IL stream is ended with 'ret'. - - - When this IL stream is ended with 'ret' then true; otherwise, false. - - - - - Initializes a new instance of the class. - - The method builder. - The trace writer. - true if the underlying builders are debuggable; othersie false. - - - - Initializes a new instance of the class. - - The constructor builder. - The trace writer. - true if the underlying builders are debuggable; othersie false. - - - - Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - - - - - Emit 'ret' instruction with specified arguments. - - - - - Declare local with name for debugging and without pinning. - Note that this method is not enabled for dynamic method. - - of local variable. - Name of the local variable. - to refer declared local variable. - - - - Begin exception block (try in C#) here. - Note that you do not have to emit leave or laeve.s instrauction at tail of the body. - - will to be end of begun exception block. - - - - Begin finally block. - Note that you do not have to emit endfinally instrauction at tail of the body. - - - - - End current exception block and its last clause. - - - - - Define new with name for tracing. - - Name of label. Note that debugging information will not have this name. - which will be target of branch instructions. - - - - Mark current position using specifieid . - - . - - - - Write trace message. - - The string. - - - - Write trace line break. - - - - - Write trace message followed by line break. - - The string. - - - - Write trace message followed by line break. - - The format string. - Format argument. - - - - Emit 'ldarg.0' instruction with specified arguments. - - - - - Emit 'ldarg.1' instruction with specified arguments. - - - - - Emit 'ldarg.2' instruction with specified arguments. - - - - - Emit 'ldarg.3' instruction with specified arguments. - - - - - Emit 'ldloc.0' instruction with specified arguments. - - - - - Emit 'ldloc.1' instruction with specified arguments. - - - - - Emit 'ldloc.2' instruction with specified arguments. - - - - - Emit 'ldloc.3' instruction with specified arguments. - - - - - Emit 'stloc.0' instruction with specified arguments. - - - - - Emit 'stloc.1' instruction with specified arguments. - - - - - Emit 'stloc.2' instruction with specified arguments. - - - - - Emit 'stloc.3' instruction with specified arguments. - - - - - Emit 'ldarg.s' instruction with specified arguments. - - as value. - - - - Emit 'ldarga.s' instruction with specified arguments. - - as value. - - - - Emit 'ldloc.s' instruction with specified arguments. - - as value. - - - - Emit 'ldloca.s' instruction with specified arguments. - - as value. - - - - Emit 'stloc.s' instruction with specified arguments. - - as value. - - - - Emit 'ldnull' instruction with specified arguments. - - - - - Emit 'ldc.i4.m1' instruction with specified arguments. - - - - - Emit 'ldc.i4.0' instruction with specified arguments. - - - - - Emit 'ldc.i4.1' instruction with specified arguments. - - - - - Emit 'ldc.i4.2' instruction with specified arguments. - - - - - Emit 'ldc.i4.3' instruction with specified arguments. - - - - - Emit 'ldc.i4.4' instruction with specified arguments. - - - - - Emit 'ldc.i4.5' instruction with specified arguments. - - - - - Emit 'ldc.i4.6' instruction with specified arguments. - - - - - Emit 'ldc.i4.7' instruction with specified arguments. - - - - - Emit 'ldc.i4.8' instruction with specified arguments. - - - - - Emit 'ldc.i4.s' instruction with specified arguments. - - as value. - - - - Emit 'ldc.i4' instruction with specified arguments. - - as value. - - - - Emit 'ldc.i8' instruction with specified arguments. - - as value. - - - - Emit 'ldc.r4' instruction with specified arguments. - - as value. - - - - Emit 'ldc.r8' instruction with specified arguments. - - as value. - - - - Emit 'pop' instruction with specified arguments. - - - - - Emit 'call' instruction with specified arguments. - - as target. - - - - Emit 'br' instruction with specified arguments. - - as target. - - - - Emit 'brfalse' instruction with specified arguments. - - as target. - - - - Emit 'brtrue' instruction with specified arguments. - - as target. - - - - Emit 'add' instruction with specified arguments. - - - - - Emit 'and' instruction with specified arguments. - - - - - Emit 'callvirt' instruction with specified arguments. - - as target. - - - - Emit 'ldobj' instruction with specified arguments. - - as type. - - - - Emit 'ldstr' instruction with specified arguments. - - as value. - - - - Emit 'newobj' instruction with specified arguments. - - as constructor. - - - - Emit 'ldfld' instruction with specified arguments. - - as field. - - - - Emit 'ldflda' instruction with specified arguments. - - as field. - - - - Emit 'stfld' instruction with specified arguments. - - as field. - - - - Emit 'stobj' instruction with specified arguments. - - as type. - - - - Emit 'box' instruction with specified arguments. - - as type. - - - - Emit 'newarr' instruction with specified arguments. - - as type. - - - - Emit 'ldelema' instruction with specified arguments. - - as type. - - - - Emit 'ldelem.i1' instruction with specified arguments. - - - - - Emit 'ldelem.u1' instruction with specified arguments. - - - - - Emit 'ldelem.i2' instruction with specified arguments. - - - - - Emit 'ldelem.u2' instruction with specified arguments. - - - - - Emit 'ldelem.i4' instruction with specified arguments. - - - - - Emit 'ldelem.u4' instruction with specified arguments. - - - - - Emit 'ldelem.i8' instruction with specified arguments. - - - - - Emit 'ldelem.r4' instruction with specified arguments. - - - - - Emit 'ldelem.r8' instruction with specified arguments. - - - - - Emit 'ldelem.ref' instruction with specified arguments. - - - - - Emit 'stelem.i1' instruction with specified arguments. - - - - - Emit 'stelem.i2' instruction with specified arguments. - - - - - Emit 'stelem.i4' instruction with specified arguments. - - - - - Emit 'stelem.i8' instruction with specified arguments. - - - - - Emit 'stelem.r4' instruction with specified arguments. - - - - - Emit 'stelem.r8' instruction with specified arguments. - - - - - Emit 'stelem.ref' instruction with specified arguments. - - - - - Emit 'ldelem' instruction with specified arguments. - - as type. - - - - Emit 'stelem' instruction with specified arguments. - - as type. - - - - Emit 'unbox.any' instruction with specified arguments. - - as type. - - - - Emit 'ldtoken' instruction with specified arguments. - - as target. - - - - Emit 'ldtoken' instruction with specified arguments. - - as target. - - - - Emit 'ldtoken' instruction with specified arguments. - - as target. - - - - Emit 'ceq' instruction with specified arguments. - - - - - Emit 'cgt' instruction with specified arguments. - - - - - Emit 'clt' instruction with specified arguments. - - - - - Emit 'ldftn' instruction with specified arguments. - - as method. - - - - Emit 'ldarg' instruction with specified arguments. - - as index. - - - - Emit 'ldarga' instruction with specified arguments. - - as index. - - - - Emit 'ldloc' instruction with specified arguments. - - as index. - - - - Emit 'ldloca' instruction with specified arguments. - - as index. - - - - Emit 'stloc' instruction with specified arguments. - - as index. - - - - Emit 'initobj' instruction with specified arguments. - - as type. - - - - Represents event information for event. - - - - - - Gets the which raises this event. - - - The which raises this event. This value will not be null. - - - A sender parameter of the event handler has same instance for this. - - - - - Gets the target type which is getting serializer. - - - The target type which is getting serializer. This value will not be null. - - - - - Gets the which represents polymorphism information for the current member. - - - The which represents polymorphism information for the current member. This value will not be null. - - - - - Gets the found serializer the event subscriber specified. - - - The found serializer the event subscriber specified. null represents default behavior is wanted. - - - - - Sets the serializer instance which can handle type instance correctly. - - The serializer instance which can handle type instance correctly; null when you cannot provide appropriate serializer instance. - - If you decide to delegate serializer generation to MessagePack for CLI infrastructure, do not call this method in your event handler or specify null for . - - - - - Represents compatibility options of serialization runtime. - - - - - Gets or sets a value indicating whether System.Runtime.Serialization.DataMemberAttribute.Order should be started with 1 instead of 0. - - - true if System.Runtime.Serialization.DataMemberAttribute.Order should be started with 1 instead of 0; otherwise, false. - Default is false. - - - Using this value, you can switch between MessagePack for CLI and ProtoBuf.NET seamlessly. - - - - - Gets or sets the . - - - The . The default is . - - - - Changing this property value does not affect already built serializers -- especially built-in (default) serializers. - You must specify enumeration to the constructor of to - change built-in serializers' behavior. - - - - - - Gets or sets a value indicating whether serializer generator ignores packability interfaces for collections or not. - - - true if serializer generator ignores packability interfaces for collections; otherwise, false. The default is true. - - - Historically, MessagePack for CLI ignored packability interfaces (, , - and ) for collection which implements (except and its kinds). - As of 0.7, the generator respects such interfaces even if the target type is collection. - Although this behavior is desirable and correct, setting this property true turn out the new behavior for backward compatibility. - - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - Represents serialization context information for internal serialization logic. - - - - - Gets or sets the default instance. - - - The default instance. - - The setting value is null. - - - - Gets the current . - - - The current . - - - - - Gets the option settings for serializer generation. - - - The option settings for serializer generation. - This value will not be null. - - - - - Gets the compatibility options. - - - The which stores compatibility options. This value will not be null. - - - - - Gets or sets the to determine serialization strategy. - - - The to determine serialization strategy. - - The setting value is invalid as enum. - - - - Gets or sets the to determine default serialization strategy of enum types. - - - The to determine default serialization strategy of enum types. - - The setting value is invalid as enum. - - A serialization strategy for specific member is determined as following: - - If the member is marked with and its value is not , then it will be used. - Otherwise, if the enum type itself is marked with , then it will be used. - Otherwise, the value of this property will be used. - - Note that the default value of this property is , it is not size efficient but tolerant to unexpected enum definition change. - - - - - Gets or sets the to control code generation. - - The setting value is invalid as enum. - - The . - - - - - Gets the default collection types. - - - The default collection types. This value will not be null. - - - - - Gets or sets a value indicating whether runtime generation is disabled or not. - - - true if runtime generation is disabled; otherwise, false. - - - - - Gets or sets the default conversion methods of built-in serializers. - - - The default conversion methods of built-in serializers. The default is . - - The setting value is invalid as enum. - - As of 0.6, value is serialized as its native representation instead of interoperable UTC milliseconds Unix epoc. - This behavior solves some debugging problem and interop issues, but breaks compability. - If you want to change this behavior, set this value to . - - - - - Occurs when the context have not find appropriate registered nor built-in serializer for specified type. - - - This event will be occured when the context could not found known serializer from: - - - Known built-in serializers for arrays, nullables, and collections, etc. - - - Known default serializers for some known various FCL value types and some reference types. - - - Previously registered or generated serializer. - - - You can instantiate your custom serializer using various properties, - and then call to provide toward the context. - - You can use to get dependent serializers as you like, - but you should never explicitly register new serializer(s) explicitly via the context from the event handler and its dependents. - Instead, you specify the instanciated serializer with once at a time. - Dependent serializer(s) should be registered via next (nested) raise of this event. - - - The context implicitly holds 'lock' for the target type for the requested serializer in the current thread. - So you should not use any synchronization primitives in the event handler and its dependents, - or you may face complex dead lock. - That is, the event handler should be as simple as possible like just instanciate the serializer and set it to the event argument. - - - - - - Configures as new classic instance. - - The previously set context as . - - - - - Creates a new which is configured as same as 0.5. - - - A new which is configured as same as 0.5. - - - There are breaking changes of properties to improve API usability and to prevent accidental failure. - This method returns a which configured as classic style settings as follows: - - - - Default (as of 0.6) - Classic (before 0.6) - - - Packed object members order (if members are not marked with nor System.Runtime.Serialization.DataMemberAttribute and serializer uses ) - As declared (metadata table order) - As lexicographical - - - value - Native representation (100-nano ticks, preserving .) - UTC, milliseconds Unix epoc. - - - - - - - Initializes a new instance of the class with copy of . - - - - - Initializes a new instance of the class with copy of for specified . - - which will be used on built-in serializers. - - - - Gets the with this instance without provider parameter. - - Type of serialization/deserialization target. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - This method automatically register new instance via . - - - - - Gets the with this instance. - - Type of serialization/deserialization target. - A provider specific parameter. See remarks section for details. - - . - If there is exiting one, returns it. - Else the new instance will be created. - - - - This method automatically register new instance via . - - - Currently, only following provider parameters are supported. - - - Target type - Provider parameter - - - or its descendants. - . The returning instance corresponds to this value for serialization. - - - null is valid value for and it indeicates default behavior of parameter. - - - - - - Gets the serializer for the specified . - - Type of the serialization target. - - . - If there is exiting one, returns it. - Else the new instance will be created. - If the platform supports async/await programming model, return type is IAsyncMessagePackSingleObjectSerializer. - - - is null. - - - Although is preferred, - this method can be used from non-generic type or methods. - - - - - Gets the serializer for the specified . - - Type of the serialization target. - A provider specific parameter. See remarks section of for details. - - . - If there is exiting one, returns it. - Else the new instance will be created. - If the platform supports async/await programming model, return type is IAsyncMessagePackSingleObjectSerializer. - - - is null. - - - Although is preferred, - this method can be used from non-generic type or methods. - - - - - Gets the current mapping table of ext type code. - - - The which maps between known ext type names and ext type codes. - - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Defines common exception factory methods. - - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that value type cannot be null on deserialization. - - The name of the member. - The type of the member. - The type that declares the member. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws an exception to notify that value type cannot be null on deserialization. - - The name of the member. - The type of the member. - The type that declares the member. - Always thrown. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that value type cannot be null on deserialization. - - The target type. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that value type cannot serialize. - - The target type. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that value type cannot deserialize. - - The target type. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that value type cannot deserialize. - - The target type. - The name of deserializing member. - The inner exception. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that item is not found on the unpacking stream. - - The index to be unpacking. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws a exception to notify that item is not found on the unpacking stream. - - The index to be unpacking. - The unpacker for pretty message. - Always thrown. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws a exception to notify that item is not found on the unpacking stream. - - The index to be unpacking. - The name of the item to be unpacking. - The unpacker for pretty message. - Always thrown. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that target type is not serializable because it does not have public default constructor. - - The target type. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that target type is not serializable because it does not have both of public default constructor and public constructor with an Int32 parameter. - - The target type. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that required field is not found on the unpacking stream. - - The name of the property. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that unpacking stream ends on unexpectedly position. - - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that target collection type does not declare appropriate Add(T) method. - - The target type. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that unpacker is not in the array header, that is the state is invalid. - - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws an exception to notify that unpacker is not in the array header, that is the state is invalid. - - The unpacker for pretty message. - Always thrown. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that unpacker is not in the array header, that is the state is invalid. - - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws an exception to notify that unpacker is not in the map header, that is the state is invalid. - - The unpacker for pretty message. - Always thrown. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that operation is not supported because cannot be instanciated. - - Type. - instance. It will not be null. - - - - - - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the array length does not match to expected tuple cardinality. - - The expected cardinality of the tuple. - The actual serialized array length. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws an exception to notify that the array length does not match to expected tuple cardinality. - - The expected cardinality of the tuple. - The actual serialized array length. - The unpacker for pretty message. - Always thrown. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the underlying stream is not correct semantically because failed to unpack items count of array/map. - - The inner exception for the debug. The value is implementation specific. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the unpacking collection is too large to represents in the current runtime environment. - - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the member cannot be null or the unpacking value cannot be nil because nil value is explicitly prohibitted. - - The name of the member. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Throws an exception to notify that the member cannot be null or the unpacking value cannot be nil because nil value is explicitly prohibitted. - - The name of the member. - Always thrown. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the unpacking value cannot be nil because the target member is read only and its type is collection. - - The name of the member. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the unpacking collection value is not a collection. - - The name of the member. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that the unpacking array size is not expected length. - - Expected, required for deserialization array length. - Actual array length. - instance. It will not be null. - - - - This is intended to MsgPack for CLI internal use. Do not use this type from application directly. - Returns new exception to notify that it is failed to deserialize member. - - Deserializing type. - The name of the deserializing member. - The exception which caused current error. - instance. It will not be null. - - - - Throws an exception to notify that it is failed to deserialize member. - - Deserializing type. - The name of the deserializing member. - The exception which caused current error. - - - - Represents serialization method for complex types. - - - - - The object will be serialized as array which is ordered by member ID. - This is default and more interoperable option. - - - - - The object will be serialized as map which is ordered by member ID. - This is a bit slower than array, but more stable for forward/backward compatibility. - - - - - Define options of serializer generation. - - - - - The generated method IL can be dumped to the current directory. - It is intended for the runtime, you cannot use this option. - - - - - The entire generated method can be collected by GC when it is no longer used. - - - - - Prefer performance. This options is default. - - - - - Implements serialization target member extraction logics. - - - - - Represents configuration for pre-generated serializer assembly generation. - - - - - Gets or sets the output directory for generated source codes. - - - The output directory for generated source codes. - The default is current directory. - - The specified value is null. - The specified value is empty or too long. - The specified path format is not supported. - - - - Gets or sets the serialization method to pack object. - - - A value of . - - Specified value is not valid . - - - - Gets or sets the default enum serialization method for generating enum type serializers. - - - A value of . - - Specified value is not valid . - - - - Gets or sets the name of the assembly. - This property is required. - - - The name of the assembly. - - - - - Gets or sets a value indicating whether recursively generates dependent types which do not have built-in serializer or not. - - - true if recursively generates dependent types which do not have built-in serializer; otherwise, false. - - - - - Gets or sets a value indicating whether prefer reflection based collection serializers instead of dyhnamic generated serializers. - - - true if prefer reflection based collection serializers instead of dyhnamic generated serializers; otherwise, false. - - - - - Gets or sets a value indicating whether creating Nullable of T serializers for value type serializers. - - - true if creates Nullable of T serializers for value type serializers; otherwise, false. - - - - - Gets or sets the namespace of generated classes. - - - The namespace of generated classes. - The default is "MsgPack.Serialization.GeneratedSerializers". - - Specified value is not valid for namespace. - - - - Initializes a new instance of the class. - - - - - Represents serializer capabilities. - - - - - None. - - - - - Caller can call Pack and PackTo method safely. - If this flag is not set, the serializer may be deserialize only serializer. - - - - - Caller can call Unpack and UnpackFrom method safely. - If this flag is not set, the serializer may be serialize only serializer. - - - - - Caller can call UnpackTo method safely. - If this flag is not set, the serializer should not be for mutable collection type. - - - - - Represents configuration for serializer code generation. - - - - - Gets or sets the namespace of generated classes. - - - The namespace of generated classes. - The default is "MsgPack.Serialization.GeneratedSerializers". - - Specified value is not valid for namespace. - - - - Gets or sets the output directory for generated source codes. - - - The output directory for generated source codes. - The default is current directory. - - The specified value is null. - The specified value is empty or too long. - The specified path format is not supported. - - - - Gets or sets the language identifier for code generation. - - - The language identifier for code generation. - This value must be registered identifier in CodeDOM configuration. - The default is "C#". - - - This value will be passed as-is for an underlying code dom provider. - - - - - - Gets or sets the indentation string for code generation. - - - The indentation string for code generation. - The default is " "(4 U+0020 chars). - - - This value will be passed as-is for an underlying code dom provider. - - - - - - Gets or sets the serialization method to pack object. - - - A value of . - - Specified value is not valid . - - - - Gets or sets the default enum serialization method for generating enum type serializers. - - - A value of . - - Specified value is not valid . - - - - Gets or sets a value indicating whether recursively generates dependent types which do not have built-in serializer or not. - - - true if recursively generates dependent types which do not have built-in serializer; otherwise, false. - - - - - Gets or sets a value indicating whether prefer reflection based collection serializers instead of dyhnamic generated serializers. - - - true if prefer reflection based collection serializers instead of dyhnamic generated serializers; otherwise, false. - - - - - Gets or sets a value indicating whether creating Nullable of T serializers for value type serializers. - - - true if creates Nullable of T serializers for value type serializers; otherwise, false. - - - - - Gets or sets a value indicating whether the generated serializers will be internal to MsgPack library itself. - - - true if the generated serializers are internal to MsgPack library itself; otherwise, false. - - - When you use MsgPack in Unity3D, you can import the library in source code form to your assets. - And, you may also import generated serializers together, then the generated serializers and MsgPack library will be same assembly ultimately. - It causes compilation error because some of overriding members have accessbility FamilyOrAssembly(protected internal in C#), - so the generated source code must have the accessibility when and only when they will be same assembly as MsgPack library itself. - - - - - Initializes a new instance of the class. - - - - - Represents result of serializer code generation for each input target types. - - - - - Gets the file path which contains generated serializer. - - - The file path which contains generated serializer. - - - If the generation method generates source codes, this property indicates each generated source code file. - Else, if the genration method generates an assembly, this property indicates the assembly file. - This property will not be null, and will be valid file path. - - - - - Gets the target type of serializer generation. - - - The target type of serializer generation. - This property will not be null. - - - - - Gets the namespace of the generated serializer. - - - The namespace of the generated serializer. - This value will not be null, but might be empty which represents global namespace. - - - - - Gets the type name of the generated serializer. - - - The type name of the generated serializer. - This property will not be null nor empty. - - - - - Gets the full name of the generated serializer type. - - - The full name of the generated serializer type. - This property will not be null nor empty. - - - - - Holds debugging support information. - - - - - Gets or sets a value indicating whether instruction/expression tracing is enabled or not. - - - true if instruction/expression tracing is enabled; otherwise, false. - - - - - Gets or sets a value indicating whether IL dump is enabled or not. - - - true if IL dump is enabled; otherwise, false. - - - - - Gets or sets a value indicating whether generic serializer for array, , , - or is not used. - - - true if generic serializer is not used; otherwise, false. - - - - - Gets the for IL tracing. - - - The for IL tracing. - This value will not be null. - - - - - Traces the specific event. - - The format string. - The args for formatting. - - - - Flushes the trace data. - - - - - Prepares instruction dump with specified . - - The assembly builder to hold instructions. - - - - Prepares the dump with dedicated internal . - - - - - Creates the new type builder for the serializer. - - The serialization target type. - - PrepareDump() was not called. - - - - Takes dump of instructions. - - - - - Resets debugging states. - - - - - Provides pre-compiled serialier assembly generation. - - - Currently, generated assembly has some restrictions: - - - The type name cannot be customize. It always to be MsgPack.Serialization.EmittingSerializers.Generated.<ESCAPED_TARGET_NAME>Serializer. - Note that the ESCAPED_TARGET_NAME is the string generated by replacing type delimiters with undersecore ('_'). - - - The assembly cannot be used on WinRT because - - - - You should NOT assume at all like class hierarchy of generated type, its implementing interfaces, custom attributes, or dependencies. - They subject to be changed in the future. - If you want to get such fine grained control for them, you should implement own hand made serializers. - - - - - - Gets the type of the root object which will be serialized/deserialized. - - - The first entry of . - This value will be null when the is empty. - - - - - Gets target types will be generated dedicated serializers. - - - A collection which stores target types will be generated dedicated serializers. - - - - - Gets the name of the assembly to be generated. - - - The name of the assembly to be generated. - - - - - Gets or sets the which indicates serialization method to be used. - - - The which indicates serialization method to be used. - - - - - Initializes a new instance of the class. - - Name of the assembly to be generated. - - is null. - - - - - Initializes a new instance of the class. - - Type of the root object which will be serialized/deserialized. - Name of the assembly to be generated. - - is null. - Or is null. - - - - - Generates the serializer assembly and save it to current directory. - - The path of generated files. - Some I/O error is occurred on saving assembly file. - - - - Generates the serializer assembly and save it to specified directory. - - The path of directory where newly generated assembly file will be located. If the directory does not exist, then it will be created. - The path of generated files. - is null. - is not valid. - is too long. - is existent file. - Cannot create specified directory for access control of file system. - Some I/O error is occurred on creating directory or saving assembly file. - - - - Generates an assembly which contains auto-generated serializer types for specified types. - - The which holds required and optional settings. - The target types where serializer types to be generated. - The file path for generated single module assembly file. - is null. Or, is null. - of is not set correctly. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are automatically generated. - - - - - Generates an assembly which contains auto-generated serializer types for specified types. - - The which holds required and optional settings. - The target types where serializer types to be generated. - The file path for generated single module assembly file. - is null. Or, is null. - of is not set correctly. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are automatically generated. - - - - - Generates an assembly which contains auto-generated serializer types for specified types. - - The which holds required and optional settings. - The target types where serializer types to be generated. - - A collection which correspond to codes generated to . - All properties of items will be same and will point to generated DLL file. - - is null. Or, is null. - of is not set correctly. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are automatically generated. - - - - - Generates an assembly which contains auto-generated serializer types for specified types. - - The which holds required and optional settings. - The target types where serializer types to be generated. - - A collection which correspond to codes generated to . - All properties of items will be same and will point to generated DLL file. - - is null. Or, is null. - of is not set correctly. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are automatically generated. - - - - - Generates source codes which implement auto-generated serializer types for specified types with default configuration. - - The target types where serializer types to be generated. - A file path collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with default configuration. - - The target types where serializer types to be generated. - A file path collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with specified configuration. - - The which holds optional settings. Specifying null means using default settings. - The target types where serializer types to be generated. - A file path collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with specified configuration. - - The which holds optional settings. Specifying null means using default settings. - The target types where serializer types to be generated. - A file path collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with default configuration. - - The target types where serializer types to be generated. - A collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with default configuration. - - The target types where serializer types to be generated. - A collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with specified configuration. - - The which holds optional settings. Specifying null means using default settings. - The target types where serializer types to be generated. - A collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Generates source codes which implement auto-generated serializer types for specified types with specified configuration. - - The which holds optional settings. Specifying null means using default settings. - The target types where serializer types to be generated. - A collection which correspond to codes generated to . - is null. - Failed to generate a serializer because of . - - Serializer types for dependent types which are refered from specified are NOT generated. - This method just generate serializer types for specified types. - - - - - Defines options for serializer generation. - - - - - Gets or sets the . - - - The - - - For testing purposes. - - - - - Gets or sets the to control code generation. - - The setting value is invalid as enum. - - The . - - - - - Gets or sets a value indicating whether runtime generation is disabled or not. - - - true if runtime generation is disabled; otherwise, false. - - - - - Represents options for custom or pre-generated serializer registration. - - - - - None of options are applied. - - - - - Overrides existing registration with specified serializer. - - - - - For non-nullable value type, registering nullable companion simulary. - - - - - Repository of known s. - - - - - Initializes a new empty instance of the class. - - - - - Initializes a new instance of the class which has copied serializers. - - The repository which will be copied its contents. - - is null. - - - - - This method does not perform any operation. - - - - - Gets the registered from this repository without provider parameter. - - Type of the object to be marshaled/unmarshaled. - A serialization context. - - . If no appropriate mashalers has benn registered, then null. - - - - - Gets the registered from this repository with specified provider parameter. - - Type of the object to be marshaled/unmarshaled. - A serialization context. - A provider specific parameter. See remarks section of for details. - - . If no appropriate mashalers has benn registered, then null. - - - - - - Registers a . - - The type of serialization target. - instance. - - true if success to register; otherwise, false. - - - is null. - - - This method invokes with . - - If you register serializer for value type, using is recommended because auto-generated deserializers use them to handle nil value. - You can use with to - get equivalant behavior for this method with registering nullable serializer automatically. - - - - - - Registers a . - - The type of serialization target. - instance. - A to control this registration process. - - true if success to register; otherwise, false. - - - is null. - - - - - Registers a forcibley. - - The type of serialization target. - instance. - - is null. - - - This method invokes with . - - If you register serializer for value type, using is recommended because auto-generated deserializers use them to handle nil value. - You can use - with and to - get equivalant behavior for this method with registering nullable serializer automatically. - - - - - - Gets the system default repository bound to default context. - - - The system default repository. - This value will not be null. - Note that the repository is frozen. - - - - - Gets the system default repository bound to default context. - - - The system default repository. - This value will not be null. - Note that the repository is frozen. - - - - - Gets the system default repository bound to default context. - - Not used. - - The system default repository. - This value will not be null. - Note that the repository is frozen. - - - - - Gets the system default repository bound for specified context. - - A which will be bound to default serializers. - is null. - - The system default repository. - This value will not be null. - Note that the repository is frozen. - - - - - Specialized for serializers. - - - - - Represents serializing member information. - - - - - Repository for key type with RWlock scheme. - - - - - This is intened to MsgPack for CLI internal use. Do not use this type from application directly. - Defines serialization helper APIs. - - - - - Unpacks the array to the specified array. - - The type of the array element. - The unpacker to unpack the underlying stream. - The serializer to deserialize array. - The array instance to be filled. - - Failed to deserialization. - - - - - Unpacks the collection with the specified method as colletion of . - - The unpacker to unpack the underlying stream. - The non-generic collection instance to be added unpacked elements. - The delegate which contains the instance method of the . The parameter is unpacked object. - - Failed to deserialization. - - - - - Unpacks the dictionary with the specified method as colletion of . - - The type of elements. - The unpacker to unpack the underlying stream. - The serializer to deserialize elements. - The generic collection instance to be added unpacked elements. - The delegate which contains the instance method of the . The parameter is unpacked object. - - Failed to deserialization. - - - - - Unpacks the collection with the specified method as colletion of . - - The return type of Add method. - The unpacker to unpack the underlying stream. - The non-generic collection instance to be added unpacked elements. - The delegate which contains the instance method of the . The parameter is unpacked object. - - Failed to deserialization. - - - - - Unpacks the dictionary with the specified method as colletion of . - - The type of elements. - The return type of Add method. - The unpacker to unpack the underlying stream. - The serializer to deserialize elements. - The generic collection instance to be added unpacked elements. - The delegate which contains the instance method of the . The parameter is unpacked object. - - Failed to deserialization. - - - - - Unpacks the dictionary with the specified method as colletion of . - - The type of keys. - The type of values. - The unpacker to unpack the underlying stream. - The serializer to deserialize key elements. - The serializer to deserialize value elements. - The generic dictionary instance to be added unpacked elements. - - Failed to deserialization. - - - - - Unpacks the dictionary with the specified method as colletion of . - - The unpacker to unpack the underlying stream. - The non-generic dictionary instance to be added unpacked elements. - - Failed to deserialization. - - - - - Gets the items count as . - - The unpacker. - The items count as . - is null. - The items count is greater than . - - The items count of the collection can be between and , - but most collections do not support so big count. - - - - - Ensures the boxed type is not null thus it cannot be unboxing. - - The type of the member. - The boxed deserializing value. - The name of the member. - The type of the target. - The unboxed value. - - - - Invokes FAMANDASM method directly. - - The type of deserializing object. - The invocation target . - The unpacker to be passed to the method. - A deserialized value. - - - - Retrieves a most appropriate constructor with capacity parameter and comparer parameter or both of them, >or default constructor of the . - - The target collection type to be instanciated. - A constructor of the . - - - - Determines the type is . - - The type should be . - - true, if is open generic type; false, otherwise. - - - - - Gets an with platform safe fashion. - - The type to be compared. - - An instance. - - - - - Gets the delegate which just returns the input ('identity' function). - - The type of input and output. - - delegate which just returns the input. This value will not be null. - - - - - Gets the delegate which returns the input ('identity' function) as output type. - - The type of output. - - delegate which returns the converted input. This value will not be null. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Boolean type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Boolean type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Byte type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Byte type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Int16 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Int16 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Int32 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Int32 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Int64 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Int64 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack SByte type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack SByte type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack UInt16 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack UInt16 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack UInt32 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack UInt32 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack UInt64 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack UInt64 type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Single type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Single type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Double type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack Double type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack string type value from underlying stream. - - - - - Invokes and returns its result. - - The unpacker to be used. - The type of the object which is deserializing now. - The name of the member which is deserializing now. - - An unpacked value. - - - Failed to unpack byte array type value from underlying stream. - - - - - Unpacks the complex object from specified with specified / - - The type of unpacking value. - The unpacker. - The serializer to deserialize complex object. - The current unpacked count for debugging. - - A value read from current stream. - - - - - Unpacks the value type value from MessagePack stream. - - The type of the context object which will store deserialized value. - The type of the value. - The unpacker. - The context which will store deserialized value. - The serializer to deserialize complex object. This parameter should be null when is specified. - The items count to be unpacked. - The unpacked items count. - Type of the target object for debugging message. - Name of the member for debugging message. - The delegate which referes direct reading. This parameter should be null when is specified. - The delegate which takes and unpacked value, and then set the value to the context. - - - - Unpacks the reference type value from MessagePack stream. - - The type of the context object which will store deserialized value. - The type of the value. - The unpacker. - The context which will store deserialized value. - The serializer to deserialize complex object. This parameter should be null when is specified. - The items count to be unpacked. - The unpacked items count. - Type of the target object for debugging message. - Name of the member for debugging message. - The nil implication of current item. - The delegate which referes direct reading. This parameter should be null when is specified. - The delegate which takes and unpacked value, and then set the value to the context. - - - - Unpacks the nullable type value from MessagePack stream. - - The type of the context object which will store deserialized value. - The type of the value. - The unpacker. - The context which will store deserialized value. - The serializer to deserialize complex object. This parameter should be null when is specified. - The items count to be unpacked. - The unpacked items count. - Type of the target object for debugging message. - Name of the member for debugging message. - The nil implication of current item. - The delegate which referes direct reading. This parameter should be null when is specified. - The delegate which takes and unpacked value, and then set the value to the context. - - - - Unpacks the value from MessagePack array. - - The type of the context object which will store deserialized value. - The unpacker. - The context which will store deserialized value. - The items count to be unpacked. - The unpacked items count. - Name of the member for debugging message. - The nil implication of current item. - The delegate which takes and unpacked value, and then set the value to the context. - - - - Unpacks the value from MessagePack map. - - The type of the context object which will store deserialized value. - The unpacker. - The context which will store deserialized value. - The items count to be unpacked. - The unpacked items count. - Name of the member for debugging message. - The nil implication of current item. - The delegate which takes and unpacked value, and then set the value to the context. - - - - Unpacks object from msgpack array. - - The type of the context. - The type of the unpacked object. - The unpacker. - The context which holds intermediate states. This value may be null when the caller implementation allows it. - A delegate to the factory method which creates the result from the context. - The names of the membesr for pretty exception. - - Delegates each ones unpack single member in order. - The 1st argument will be , 2nd argument will be , - and 3rd argument is index of current item. - - - An unpacked object. - - - is null. - Or, is null. - Or, is null. - - - - - Unpacks object from msgpack array. - - The type of the context. - The type of the unpacked object. - The unpacker. - The context which holds intermediate states. This value may be null when the caller implementation allows it. - A delegate to the factory method which creates the result from the context. - - Delegates each ones unpack single member in order. - The key of this dictionary must be member name. - The 1st argument will be , 2nd argument will be , - and 3rd argument is index of current item. - - - An unpacked object. - - - is null. - Or, is null. - Or, is null. - - - - - Unpacks the collection from MessagePack stream. - - The type of the collection to be unpacked. - The unpacker where position is located at array or map header. - The collection count gotten from the . - The collection instance to be added unpacked items. - - A delegate to the bulk operation (typically UnpackToCore call). - The 1st argument will be , 2nd argument will be , - and 3rd argument will be . - If this parameter is null, will be used. - - - A delegate to the operation for each items, which typically unpack value and append it to the . - The 1st argument will be , 2nd argument will be , - and 3rd argument will be index of the current item. - If parameter is not null, this parameter will be ignored. - - - An unpacked collection. - - - - - Implements basic (maybe naive) implementation for common Set<T> operation. - - - - - Basic implementation using managed . - - - - - Defines subtree unpacking unpacker. - - - - - Represents unpacking error when message type is not valid because 0xC1 will never be assigned. - - - - - Initializes a new instance of the class with the default error message. - - - - - Initializes a new instance of the class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - - The error message that explains the reason for the exception. - - The exception that is the cause of the current exception, or a null if no inner exception is specified. - - - - - Initializes a new instance of the class with serialized data. - - - The that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - The parameter is null. - - - The class name is null or is zero (0). - - - - - Implements deserializing feature of MsgPack. - - - implements three mode, that is 'Streaming', 'Skipping' and 'Subtree'. - - - - Streaming - - - When the is called, unpacker go into 'Streaming' mode. - In this mode, unpacker unpacks individual entries as via property. - If the underlying stream is ended unexpectedly, then returns false, and will be null. - Note that if the underlying stream is feeded, that is the is expanded and its is not forwarded, - subsequent invocation will success, and is set as complete entry which reflects feeded binary. - - - If the reading of the entry is completed, that is the is not null, unpacker can transit other mode. - - - - - Skipping - - - When the is called, unpacker go into 'Skipping' mode. - In this mode, unpacker scans the subtree where the root is current item, then returns skipped byte length. - If the underlying stream is ended unexpectedly, it returns null. - Note that if the underlying stream is feeded, that is the is expanded and its is not forwarded, - subsequent invocation will success, and returns length as complete entry which reflects feeded binary. - - If the underlying is cannot be seeked (that is, is false), - DO NOT use this method. - You can buffering the content via instead, for example. - - - - If the skipping of the subtree is completed, that is the return value is not null, unpacker can transit other mode. - - - - - Subtree - - - When the is called, unpacker go into 'Subtree' mode. - In this mode, any operation for this unpacker instance is invalid. - Instead of use this instance itself, you can use subtree unpacker returned from . - The subtree unpacker is the instance which scope is limited to the subtree where the root is the current entry when is called. - The subtree unpacker also have its own mode and state. - - of the subtree unpacker must be called to indicate subtree unpacking is gracefully completed. - When the extra entries are remained in the subtree, these will be skipped on the disposal process. - - - - Once the subtree unpacking is completed gracefully, that is, on the subtree unpacker called, the parant unpacker can transit other mode. - - - - - - - - - Gets a last unpacked data. - - A last unpacked data. - - - In default implementation, this property never returning null even if it had not been unpacked any objects. - - If you use any of direct APIs (methods which return non-), - then this property to be invalidated. - Note that the actual value of invalidated this property is undefined. - - - - - Gets a last unpacked data. - - A last unpacked data. Initial value is . - - If you use any of direct APIs (methods which return non-), - then this property to be invalidated. - Note that the actual value of invalidated this property is undefined. - - - - - Gets a value indicating whether this instance is positioned to array header. - - - true if this instance is positioned to array header; otherwise, false. - - - - - Gets a value indicating whether this instance is positioned to map header. - - - true if this instance is positioned to map header; otherwise, false. - - - - - Gets a value indicating whether this instance is positioned to array or map header. - - - true if this instance is positioned to array or map header; otherwise, false. - - - - - Gets the items count for current array or map. - - - The items count for current array or map. - - - Both of the and are false. - - - - - Verifies the mode. - - The mode to be. - - Already disposed. - - - Is in incompatible mode. - - - - - Verifies this instance is not disposed. - - - - - Gets the underlying stream to handle direct API. - - - This instance does not supoort direct API. - - - - - Gets the previous position before last operation for debugging. - - The offset or position. - true for the is real position of the underlying stream;false if the value is offset from the root unpaker instance was created. - - - - Creates the new from specified stream. - - The stream to be unpacked. This stream will be closed when is called. - instance. - - - - Creates the new from specified stream. - - The stream to be unpacked. - - true to close when this instance is disposed; - false, otherwise. - - instance. - - - - Creates the new from specified stream. - - The stream to be unpacked. - which specifies stream handling options. - instance. - - - - Initializes a new instance of the class. - - - - - Releases all managed resources. - - - - - Releases unmanaged and optionally managed resources. - - true to release both managed and unmanaged resources; false to release only unmanaged resources. - - - - Drains remaining items in current context. - - - This method drains remaining items in context of subtree mode unpacker. - This method does not any effect for other types of unpacker. - - - - - Starts unpacking of current subtree. - - - to unpack current subtree. - This will not be null. - - - This unpacker is not positioned on the header of array nor map. - Or this unpacker already returned for subtree and it has not been closed yet. - - - While subtree unpacker is used, this instance will be 'locked' (called 'subtree' mode) and be unavailable. - When you finish to unpack subtree, you must invoke , - or you faces when you use the parent instance. - Subtree unpacker can only unpack subtree, so you can handle collection deserialization easily. - - - - - Starts unpacking of current subtree. - - - to unpack current subtree. - This will not be null. - - - - - Ends the read subtree. - - - This method only be called from subtree unpacker. - Custom subtree unpacker implementation must call this method from its method. - - - - - Reads next Message Pack entry. - - - true, if position is sucessfully move to next entry; - false, if position reaches the tail of the Message Pack stream. - - - This instance is in 'subtree' mode. - - - The underying stream unexpectedly ended. - - - - - Reads next Message Pack entry. - - - true, if position is sucessfully move to next entry; - false, if position reaches the tail of the Message Pack stream. - - - - - Gets to enumerate from source stream. - - to enumerate from source stream. - - - - Skips the subtree where the root is the current entry, and returns skipped byte length. - - - Skipped byte length. - If the subtree is not completed, then null. - - - - - Skips the subtree where the root is the current entry, and returns skipped byte length. - - - Skipped byte length. - If the subtree is not completed, then null. - - - - - Gets a current item or collection as single from the stream. - - - A read item or collection from the stream. - Or null when stream is ended. - - - - - Gets a current item or collection as single from the stream. - - - A read item or collection from the stream. - - The stream unexpectedly ends. - - - - Unpacks current subtree and returns subtree root as array or map. - - - An unpacked array or map when current position is array or map header. - null when current position is not array nor map header. - - - - - Unpacks current subtree and returns subtree root as array or map. - - - An unpacked array or map when current position is array or map header. - Or when current position is not array nor map header. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next value from current stream. - - - The value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the type. - - - - - Reads next nullable value from current stream. - - - The nullable value read from current stream to be stored when operation is succeeded. - - - The nullable value read from current data source successfully. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not compatible for the nullable type. - - - - - Reads next array length value from current stream. - - - The array length read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not an array. - - - - - Reads next map length value from current stream. - - - The map length read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not a map. - - - - - Reads next byte array value from current stream. - - - The byte array read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not a raw. - - - - - Reads next utf-8 encoded string value from current stream. - - - The decoded utf-8 encoded string read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - A value read from data source is not a raw. - - - - - Reads next value from current stream. - - - The which represents a value read from current stream to be stored when operation is succeeded. - - - true if expected value was read from stream; false if no more data on the stream. - Note that this method throws exception for unexpected state. See exceptions section. - - - Cannot read a value because the underlying stream unexpectedly ends. - - - - - Represents generic unpacking error. - - - - - Initializes a new instance of the class with the default error message. - - - - - Initializes a new instance of the class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - - The error message that explains the reason for the exception. - - The exception that is the cause of the current exception, or a null if no inner exception is specified. - - - - - Initializes a new instance of the class with serialized data. - - - The that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - The parameter is null. - - - The class name is null or is zero (0). - - - - - Defines direct conversion value from/to Message Pack binary stream without intermediate . - - - This class provides convinient way to unpack objects from wellknown seekable stream. - This class does not support stream feeding. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks value from the specified . - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the array from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked the array and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - The items count of the underlying collection body is over . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the array from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked the array and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - The items count of the underlying collection body is over . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the array value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the array value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - The items count of the underlying collection body is over . - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks length of the array from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of nullable which contains unpacked length of the array and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to nullable . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks length of the array from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of nullable which contains unpacked length of the array and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to nullable . - - - When the type of packed value is not known, use instead. - - - - - Unpacks length of the array value from the specified . - - The which contains Message Pack binary stream. - - The unpacked length of the array value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to nullable . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the dictionary from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked the dictionary and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - The items count of the underlying collection body is over . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the dictionary from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked the dictionary and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - The items count of the underlying collection body is over . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the dictionary value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the dictionary value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - The items count of the underlying collection body is over . - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks count of the dictionary entries from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of nullable which contains unpacked count of the dictionary entries and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to nullable . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks count of the dictionary entries from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of nullable which contains unpacked count of the dictionary entries and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to nullable . - - - When the type of packed value is not known, use instead. - - - - - Unpacks count of the dictionary entries value from the specified . - - The which contains Message Pack binary stream. - - The unpacked count of the dictionary entries value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to nullable . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the raw binary from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of [] which contains unpacked the raw binary and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to []. - - - The items count of the underlying collection body is over . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the raw binary from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of [] which contains unpacked the raw binary and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to []. - - - The items count of the underlying collection body is over . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the raw binary value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the raw binary value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to []. - Note that the state of will be unpredictable espicially it is not seekable. - - - The items count of the underlying collection body is over . - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the boolean from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked the boolean and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the boolean from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked the boolean and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the boolean value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the boolean value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the nil from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked the nil and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the nil from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked the nil and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the nil value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the nil value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the which represents the value which has MessagePack type semantics. from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked the which represents the value which has MessagePack type semantics. and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the which represents the value which has MessagePack type semantics. from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked the which represents the value which has MessagePack type semantics. and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the which represents the value which has MessagePack type semantics. value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the which represents the value which has MessagePack type semantics. value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the which represents the extended type value. from the head of specified byte array. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked the which represents the extended type value. and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - The items count of the underlying collection body is over . - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks the which represents the extended type value. from the specified byte array. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked the which represents the extended type value. and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not grator than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - - - The items count of the underlying collection body is over . - - - When the type of packed value is not known, use instead. - - - - - Unpacks the which represents the extended type value. value from the specified . - - The which contains Message Pack binary stream. - - The unpacked the which represents the extended type value. value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not compatible to . - Note that the state of will be unpredictable espicially it is not seekable. - - - The items count of the underlying collection body is over . - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks raw value from the specified as . - - The which contains Message Pack binary stream. - - The which represents raw value stream. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not raw binary. - Note that the state of will be unpredictable espicially it is not seekable. - - - - does not own , so still should be closed. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks raw value from the specified as with UTF-8 encoding. - - The which contains Message Pack binary stream. - - The which represents raw value stream as UTF-8 string. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not raw binary. - Note that the state of will be unpredictable espicially it is not seekable. - - - - if contains invalid sequence as UTF-8 encoding string, - the may occurs on read char. - - - does not own , so still should be closed. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks raw value from the specified as with specified encoding. - - The which contains Message Pack binary stream. - The to decode binary stream. - - The which represents raw value stream as UTF-8 string. - - - is null. - Or, is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not raw binary. - Note that the state of will be unpredictable espicially it is not seekable. - - - - if contains invalid sequence as specified encoding string, - the may occurs on read char. - - - does not own , so still should be closed. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array with UTF-8 encoding. - - The byte array which contains Message Pack binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - Or, the unpacked result in the is invalid as UTF-8 encoded byte stream. - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the head of specified byte array with specified encoding. - - The byte array which contains Message Pack binary stream. - The to decode binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - Or, is null. - - - is empty. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - Or, the unpacked result in the is invalid as UTF-8 encoded byte stream. - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from specified offsetted byte array with UTF-8 encoding. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - - The of which contains unpacked value and processed bytes count. - - - is null. - - - is empty. - Or, the length of is not greater than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - Or, the unpacked result in the is invalid as specified encoding byte stream. - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from specified offsetted byte array with specified encoding. - - The byte array which contains Message Pack binary stream. - The offset to be unpacking start with. - The to decode binary stream. - - The of which contains unpacked value and processed bytes count. - - - is null. - Or, is null. - - - is empty. - Or, the length of is not greater than . - - - is negative value. - - - is not valid MessagePack stream. - - - The unpacked result in the is not compatible to . - Or, the unpacked result in the is invalid as specified encoding byte stream. - - - - Invocation of this method is equivalant to call with offset is 0. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified with UTF-8 encoding. - - The which contains Message Pack binary stream. - - The unpacked value. - - - is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not raw binary. - Or, the unpacked result in the is invalid as UTF-8 encoded byte stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Unpacks value from the specified with specified encoding. - - The which contains Message Pack binary stream. - The to decode binary stream. - - The unpacked value. - - - is null. - Or is null. - - - The of is false. - - - is not valid MessagePack stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - The unpacked result in the is not raw binary. - Or, the unpacked result in the is invalid as specified encoding byte stream. - Note that the state of will be unpredictable espicially it is not seekable. - - - - The processed bytes count can be calculated via of when the is true. - - - When the type of packed value is not known, use instead. - - - - - - Represents result of direct conversion from the byte array. - - Type of value. - - - - Get read bytes count from input byte array. - - - Read bytes count from input byte array. - If this value equals to old offset, then a value of property is not undifined. - - - - - Get retrieved value from the byte array. - - - Retrieved value from the byte array. - If equals to old offset, then a value of this property is not undefined. - - - - - Compare two instances are equal. - - instance. - - If is and its value is equal to this instance, then true. - Otherwise false. - - - - - Compare two instances are equal. - - instance. - - Whether value of is equal to this instance or not. - - - - - Get hash code of this instance. - - Hash code of this instance. - - - - Get string representation of this object. - - String representation of this object. - - - DO NOT use this value programmically. - The purpose of this method is informational, so format of this value subject to change. - - - - - - Compare two instances are equal. - - instance. - instance. - - Whether value of and are equal each other or not. - - - - - Compare two instances are not equal. - - instance. - instance. - - Whether value of and are not equal each other or are equal. - - - - - Represents raw binary as read only . - - - - This object behaves as wrapper of the underlying which contains message pack encoded byte array. - But, this object does not own the stream, so that stream is not closed when this stream is closed. - - - The value of , timeout, and async API depends on the underlying stream. - - - - - - Gets a value indicating whether the current stream supports reading. - - Always true. - - - - Gets a value indicating whether the current stream supports writing. - - Always false. - - - - Gets the length in bytes of the stream. - - - A long value representing the length of the raw binary length. - This value must be between 0 and . - - - Methods were called after the stream was closed. - - - This property never throws even if is false. - - - - - Gets a value that determines whether the current stream can time out. - - - A value that determines whether the current stream can time out. - - - Methods were called after the stream was closed. - - - - - Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. - - - An array of bytes. When this method returns, - the buffer contains the specified byte array with the values between and ( + - 1) - replaced by the bytes read from the current source. - - - The zero-based byte offset in at which to begin storing the data read from the current stream. - - - The maximum number of bytes to be read from the current stream. - - - The total number of bytes read into the buffer. - This can be less than the number of bytes requested if that many bytes are not currently available, - or zero (0) if the end of the stream has been reached. - - - The sum of and is larger than the buffer length. - - - is null. - - - or is negative. - - - An I/O error occurs. - - - Methods were called after the stream was closed. - - - - Arguments might be passed to the underlying without any validation. - - - - - - Overrides so that no action is performed. - - - - - Throws . - - Never used. - - Always thrown. - - - - - Throws . - - Never used. - Never used. - Never used. - - Always thrown. - - - - - Implements which reads raw binary with specific . - - - - - Gets the length of the underlying raw binary length. - - - The length of the underlying raw binary length. - This value will not be negative. - - - - - Common validtion utility. - - - - - Determine specified category is printiable. - - Unicode cateory. - - If all charactors in specified category are printable then true. - Other wise false. - - - This method is conservative, but application cannot print the charactor - because appropriate font is not installed the machine. - - - - - Defines extension methods to achieve compatiblity between .NET 3.5 and .NET 4.0. - - - - - Polyfill for System.Threading.Volatile. - - - - - Compatibility Mock. - - - - - Compatibility Mock. - - - - - Compatibility Mock. - - - - - Compatibility Mock. - - - - diff --git a/tools/mpu/bin/mpu.exe b/tools/mpu/bin/mpu.exe deleted file mode 100644 index f78390eae..000000000 Binary files a/tools/mpu/bin/mpu.exe and /dev/null differ diff --git a/tools/mpu/bin/net35/mpu.exe b/tools/mpu/bin/net35/mpu.exe new file mode 100644 index 000000000..0b0d39274 Binary files /dev/null and b/tools/mpu/bin/net35/mpu.exe differ