From c14ac61e5900b9e4ce2a8009955308f5709ad280 Mon Sep 17 00:00:00 2001 From: oneRain Date: Tue, 30 Mar 2021 10:54:25 +0800 Subject: [PATCH] chore: fixed lib version --- Common/Common/Common.csproj | 4 +- Libs/Google.Protobuf/ByteString.cs | 156 +++---- Libs/Google.Protobuf/ByteStringAsync.cs | 64 --- Libs/Google.Protobuf/Collections/MapField.cs | 129 ++++-- Libs/Google.Protobuf/ExtensionValue.cs | 2 +- Libs/Google.Protobuf/FieldCodec.cs | 6 - Libs/Google.Protobuf/IBufferMessage.cs | 2 + .../Google.Protobuf/LC.Google.Protobuf.csproj | 19 +- .../ParsingPrimitivesMessages.cs | 63 --- Libs/Google.Protobuf/Reflection/Descriptor.cs | 95 ++-- .../Reflection/FileDescriptor.cs | 19 +- Libs/Google.Protobuf/UnsafeByteOperations.cs | 81 ---- Libs/Google.Protobuf/WritingPrimitives.cs | 181 ++------ Libs/Newtonsoft.Json/Bson/BsonBinaryType.cs | 2 - Libs/Newtonsoft.Json/Bson/BsonBinaryWriter.cs | 2 - Libs/Newtonsoft.Json/Bson/BsonObjectId.cs | 2 - Libs/Newtonsoft.Json/Bson/BsonReader.cs | 2 - Libs/Newtonsoft.Json/Bson/BsonToken.cs | 2 - Libs/Newtonsoft.Json/Bson/BsonType.cs | 2 - Libs/Newtonsoft.Json/Bson/BsonWriter.cs | 2 - .../Converters/BinaryConverter.cs | 16 +- .../Converters/BsonObjectIdConverter.cs | 2 - .../Converters/CustomCreationConverter.cs | 4 +- .../Converters/DataSetConverter.cs | 10 +- .../Converters/DataTableConverter.cs | 14 +- .../Converters/DiscriminatedUnionConverter.cs | 80 ++-- .../Converters/EntityKeyMemberConverter.cs | 33 +- .../Converters/ExpandoObjectConverter.cs | 16 +- .../Converters/IsoDateTimeConverter.cs | 24 +- .../Converters/JavaScriptDateTimeConverter.cs | 8 +- .../Converters/KeyValuePairConverter.cs | 20 +- .../Converters/RegexConverter.cs | 16 +- .../Converters/StringEnumConverter.cs | 14 +- .../Converters/UnixDateTimeConverter.cs | 8 +- .../Converters/VersionConverter.cs | 6 +- .../Converters/XmlNodeConverter.cs | 307 +++++++------ Libs/Newtonsoft.Json/DateParseHandling.cs | 6 +- Libs/Newtonsoft.Json/DefaultJsonNameTable.cs | 2 +- Libs/Newtonsoft.Json/IArrayPool.cs | 2 +- .../Newtonsoft.Json/JsonContainerAttribute.cs | 20 +- Libs/Newtonsoft.Json/JsonConvert.cs | 107 +++-- Libs/Newtonsoft.Json/JsonConverter.cs | 18 +- .../Newtonsoft.Json/JsonConverterAttribute.cs | 2 +- Libs/Newtonsoft.Json/JsonException.cs | 2 +- Libs/Newtonsoft.Json/JsonNameTable.cs | 2 +- Libs/Newtonsoft.Json/JsonPosition.cs | 14 +- Libs/Newtonsoft.Json/JsonPropertyAttribute.cs | 10 +- Libs/Newtonsoft.Json/JsonReader.Async.cs | 10 +- Libs/Newtonsoft.Json/JsonReader.cs | 92 ++-- Libs/Newtonsoft.Json/JsonReaderException.cs | 8 +- .../JsonSerializationException.cs | 8 +- Libs/Newtonsoft.Json/JsonSerializer.cs | 91 ++-- .../Newtonsoft.Json/JsonSerializerSettings.cs | 27 +- Libs/Newtonsoft.Json/JsonTextReader.Async.cs | 56 +-- Libs/Newtonsoft.Json/JsonTextReader.cs | 93 +--- Libs/Newtonsoft.Json/JsonTextWriter.Async.cs | 46 +- Libs/Newtonsoft.Json/JsonTextWriter.cs | 39 +- Libs/Newtonsoft.Json/JsonValidatingReader.cs | 2 - Libs/Newtonsoft.Json/JsonWriter.Async.cs | 26 +- Libs/Newtonsoft.Json/JsonWriter.cs | 56 ++- Libs/Newtonsoft.Json/JsonWriterException.cs | 8 +- .../Newtonsoft.Json/LC.Newtonsoft.Json.csproj | 51 ++- Libs/Newtonsoft.Json/Linq/Extensions.cs | 32 +- Libs/Newtonsoft.Json/Linq/JArray.Async.cs | 2 +- Libs/Newtonsoft.Json/Linq/JArray.cs | 17 +- .../Linq/JConstructor.Async.cs | 6 +- Libs/Newtonsoft.Json/Linq/JConstructor.cs | 23 +- Libs/Newtonsoft.Json/Linq/JContainer.Async.cs | 17 +- Libs/Newtonsoft.Json/Linq/JContainer.cs | 146 +++---- Libs/Newtonsoft.Json/Linq/JEnumerable.cs | 2 +- Libs/Newtonsoft.Json/Linq/JObject.Async.cs | 2 +- Libs/Newtonsoft.Json/Linq/JObject.cs | 118 +++-- Libs/Newtonsoft.Json/Linq/JProperty.Async.cs | 4 +- Libs/Newtonsoft.Json/Linq/JProperty.cs | 54 +-- .../Linq/JPropertyDescriptor.cs | 2 +- .../Linq/JPropertyKeyedCollection.cs | 18 +- Libs/Newtonsoft.Json/Linq/JRaw.cs | 2 +- Libs/Newtonsoft.Json/Linq/JToken.Async.cs | 8 +- Libs/Newtonsoft.Json/Linq/JToken.cs | 327 ++++++-------- Libs/Newtonsoft.Json/Linq/JTokenReader.cs | 36 +- Libs/Newtonsoft.Json/Linq/JTokenWriter.cs | 48 +-- Libs/Newtonsoft.Json/Linq/JValue.Async.cs | 6 +- Libs/Newtonsoft.Json/Linq/JValue.cs | 76 ++-- .../Linq/JsonPath/ArrayIndexFilter.cs | 6 +- .../Linq/JsonPath/ArrayMultipleIndexFilter.cs | 11 +- .../Linq/JsonPath/ArraySliceFilter.cs | 6 +- .../Linq/JsonPath/FieldFilter.cs | 19 +- .../Linq/JsonPath/FieldMultipleFilter.cs | 15 +- Libs/Newtonsoft.Json/Linq/JsonPath/JPath.cs | 76 ++-- .../Linq/JsonPath/PathFilter.cs | 15 +- .../Linq/JsonPath/QueryExpression.cs | 70 ++- .../Linq/JsonPath/QueryFilter.cs | 11 +- .../Linq/JsonPath/QueryScanFilter.cs | 13 +- .../Linq/JsonPath/RootFilter.cs | 2 +- .../Linq/JsonPath/ScanFilter.cs | 13 +- .../Linq/JsonPath/ScanMultipleFilter.cs | 16 +- .../Linq/JsonSelectSettings.cs | 28 -- Libs/Newtonsoft.Json/Schema/Extensions.cs | 2 - Libs/Newtonsoft.Json/Schema/JsonSchema.cs | 2 - .../Schema/JsonSchemaBuilder.cs | 4 +- .../Schema/JsonSchemaConstants.cs | 2 - .../Schema/JsonSchemaException.cs | 2 - .../Schema/JsonSchemaGenerator.cs | 10 +- .../Newtonsoft.Json/Schema/JsonSchemaModel.cs | 2 - .../Schema/JsonSchemaModelBuilder.cs | 2 - Libs/Newtonsoft.Json/Schema/JsonSchemaNode.cs | 2 - .../Schema/JsonSchemaNodeCollection.cs | 2 - .../Schema/JsonSchemaResolver.cs | 2 - Libs/Newtonsoft.Json/Schema/JsonSchemaType.cs | 2 - .../Schema/JsonSchemaWriter.cs | 2 - .../Schema/UndefinedSchemaIdHandling.cs | 2 - .../Schema/ValidationEventArgs.cs | 2 - .../Schema/ValidationEventHandler.cs | 2 - .../Serialization/CachedAttributeGetter.cs | 4 +- .../CamelCasePropertyNamesContractResolver.cs | 4 +- .../Serialization/DefaultContractResolver.cs | 142 +++--- .../DefaultSerializationBinder.cs | 24 +- .../Serialization/DiagnosticsTraceWriter.cs | 2 +- .../Serialization/DynamicValueProvider.cs | 8 +- .../Serialization/ErrorContext.cs | 6 +- .../Serialization/ErrorEventArgs.cs | 4 +- .../Serialization/ExpressionValueProvider.cs | 8 +- .../Serialization/ISerializationBinder.cs | 4 +- .../Serialization/ITraceWriter.cs | 2 +- .../Serialization/IValueProvider.cs | 4 +- .../Serialization/JsonArrayContract.cs | 43 +- .../Serialization/JsonContainerContract.cs | 12 +- .../Serialization/JsonContract.cs | 23 +- .../Serialization/JsonDictionaryContract.cs | 72 ++-- .../Serialization/JsonDynamicContract.cs | 16 +- .../Serialization/JsonFormatterConverter.cs | 13 +- .../JsonISerializableContract.cs | 2 +- .../Serialization/JsonObjectContract.cs | 20 +- .../Serialization/JsonProperty.cs | 50 +-- .../Serialization/JsonPropertyCollection.cs | 17 +- .../JsonSerializerInternalBase.cs | 14 +- .../JsonSerializerInternalReader.cs | 405 ++++++++---------- .../JsonSerializerInternalWriter.cs | 127 +++--- .../Serialization/JsonSerializerProxy.cs | 18 +- .../Serialization/JsonTypeReflector.cs | 62 +-- .../Serialization/KebabCaseNamingStrategy.cs | 84 ---- .../Serialization/MemoryTraceWriter.cs | 2 +- .../Serialization/NamingStrategy.cs | 2 +- .../Serialization/ObjectConstructor.cs | 2 +- .../Serialization/ReflectionValueProvider.cs | 4 +- .../SerializationBinderAdapter.cs | 4 +- .../Serialization/TraceJsonReader.cs | 12 +- .../Serialization/TraceJsonWriter.cs | 14 +- Libs/Newtonsoft.Json/SerializationBinder.cs | 4 +- Libs/Newtonsoft.Json/Utilities/AsyncUtils.cs | 20 +- .../Utilities/Base64Encoder.cs | 4 +- .../Utilities/BidirectionalDictionary.cs | 4 +- .../Utilities/CollectionUtils.cs | 31 +- .../Utilities/CollectionWrapper.cs | 38 +- .../Newtonsoft.Json/Utilities/ConvertUtils.cs | 84 ++-- .../Utilities/DateTimeUtils.cs | 36 +- .../Utilities/DictionaryWrapper.cs | 85 ++-- .../Newtonsoft.Json/Utilities/DynamicProxy.cs | 16 +- .../Utilities/DynamicProxyMetaObject.cs | 6 +- .../DynamicReflectionDelegateFactory.cs | 35 +- .../Newtonsoft.Json/Utilities/DynamicUtils.cs | 23 +- Libs/Newtonsoft.Json/Utilities/EnumUtils.cs | 36 +- .../ExpressionReflectionDelegateFactory.cs | 47 +- Libs/Newtonsoft.Json/Utilities/FSharpUtils.cs | 134 +++--- .../Utilities/ImmutableCollectionsUtils.cs | 10 +- .../Utilities/JavaScriptUtils.cs | 47 +- .../LateBoundReflectionDelegateFactory.cs | 10 +- Libs/Newtonsoft.Json/Utilities/LinqBridge.cs | 10 +- .../Newtonsoft.Json/Utilities/MethodBinder.cs | 4 +- Libs/Newtonsoft.Json/Utilities/MethodCall.cs | 2 +- .../Utilities/MiscellaneousUtils.cs | 25 +- .../Utilities/NullableAttributes.cs | 74 ---- .../Utilities/ReflectionDelegateFactory.cs | 14 +- .../Utilities/ReflectionObject.cs | 28 +- .../Utilities/ReflectionUtils.cs | 64 ++- .../Newtonsoft.Json/Utilities/StringBuffer.cs | 20 +- Libs/Newtonsoft.Json/Utilities/StringUtils.cs | 70 ++- .../Utilities/TypeExtensions.cs | 36 +- .../Utilities/ValidationUtils.cs | 4 +- Libs/Newtonsoft.Json/packageIcon.png | Bin 8956 -> 0 bytes Realtime/Realtime/Realtime.csproj | 4 +- csharp-sdk.sln | 28 +- 182 files changed, 2382 insertions(+), 3401 deletions(-) delete mode 100644 Libs/Google.Protobuf/ByteStringAsync.cs delete mode 100644 Libs/Google.Protobuf/UnsafeByteOperations.cs delete mode 100644 Libs/Newtonsoft.Json/Linq/JsonSelectSettings.cs delete mode 100644 Libs/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs delete mode 100644 Libs/Newtonsoft.Json/Utilities/NullableAttributes.cs delete mode 100644 Libs/Newtonsoft.Json/packageIcon.png diff --git a/Common/Common/Common.csproj b/Common/Common/Common.csproj index f94e9ae..8ecbd25 100644 --- a/Common/Common/Common.csproj +++ b/Common/Common/Common.csproj @@ -13,8 +13,6 @@ - - ProjectReference - + diff --git a/Libs/Google.Protobuf/ByteString.cs b/Libs/Google.Protobuf/ByteString.cs index 1d2ccbe..277fde0 100644 --- a/Libs/Google.Protobuf/ByteString.cs +++ b/Libs/Google.Protobuf/ByteString.cs @@ -34,7 +34,6 @@ using System; using System.Collections; using System.Collections.Generic; using System.IO; -using System.Runtime.InteropServices; using System.Security; using System.Text; #if !NET35 @@ -50,36 +49,40 @@ namespace LC.Google.Protobuf /// /// Immutable array of bytes. /// - [SecuritySafeCritical] public sealed class ByteString : IEnumerable, IEquatable { private static readonly ByteString empty = new ByteString(new byte[0]); - private readonly ReadOnlyMemory bytes; + private readonly byte[] bytes; /// - /// Internal use only. Ensure that the provided memory is not mutated and belongs to this instance. + /// Unsafe operations that can cause IO Failure and/or other catastrophic side-effects. /// - internal static ByteString AttachBytes(ReadOnlyMemory bytes) + internal static class Unsafe + { + /// + /// Constructs a new ByteString from the given byte array. The array is + /// *not* copied, and must not be modified after this constructor is called. + /// + internal static ByteString FromBytes(byte[] bytes) + { + return new ByteString(bytes); + } + } + + /// + /// Internal use only. Ensure that the provided array is not mutated and belongs to this instance. + /// + internal static ByteString AttachBytes(byte[] bytes) { return new ByteString(bytes); } /// - /// Internal use only. Ensure that the provided memory is not mutated and belongs to this instance. - /// This method encapsulates converting array to memory. Reduces need for SecuritySafeCritical - /// in .NET Framework. - /// - internal static ByteString AttachBytes(byte[] bytes) - { - return AttachBytes(bytes.AsMemory()); - } - - /// - /// Constructs a new ByteString from the given memory. The memory is + /// Constructs a new ByteString from the given byte array. The array is /// *not* copied, and must not be modified after this constructor is called. /// - private ByteString(ReadOnlyMemory bytes) + private ByteString(byte[] bytes) { this.bytes = bytes; } @@ -108,13 +111,18 @@ namespace LC.Google.Protobuf get { return Length == 0; } } +#if GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY /// /// Provides read-only access to the data of this . /// No data is copied so this is the most efficient way of accessing. /// public ReadOnlySpan Span { - get { return bytes.Span; } + [SecuritySafeCritical] + get + { + return new ReadOnlySpan(bytes); + } } /// @@ -123,8 +131,13 @@ namespace LC.Google.Protobuf /// public ReadOnlyMemory Memory { - get { return bytes; } + [SecuritySafeCritical] + get + { + return new ReadOnlyMemory(bytes); + } } +#endif /// /// Converts this into a byte array. @@ -133,7 +146,7 @@ namespace LC.Google.Protobuf /// A byte array with the same data as this ByteString. public byte[] ToByteArray() { - return bytes.ToArray(); + return (byte[]) bytes.Clone(); } /// @@ -142,16 +155,7 @@ namespace LC.Google.Protobuf /// A base64 representation of this ByteString. public string ToBase64() { - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment segment)) - { - // Fast path. ByteString was created with an array, so pass the underlying array. - return Convert.ToBase64String(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array. Convert memory and pass result to ToBase64String. - return Convert.ToBase64String(bytes.ToArray()); - } + return Convert.ToBase64String(bytes); } /// @@ -195,10 +199,21 @@ namespace LC.Google.Protobuf /// The stream to copy into a ByteString. /// The cancellation token to use when reading from the stream, if any. /// A ByteString with content read from the given stream. - public static Task FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) + public async static Task FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { ProtoPreconditions.CheckNotNull(stream, nameof(stream)); - return ByteStringAsync.FromStreamAsyncCore(stream, cancellationToken); + int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0; + var memoryStream = new MemoryStream(capacity); + // We have to specify the buffer size here, as there's no overload accepting the cancellation token + // alone. But it's documented to use 81920 by default if not specified. + await stream.CopyToAsync(memoryStream, 81920, cancellationToken); +#if NETSTANDARD1_1 || NETSTANDARD2_0 + byte[] bytes = memoryStream.ToArray(); +#else + // Avoid an extra copy if we can. + byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray(); +#endif + return AttachBytes(bytes); } #endif @@ -224,15 +239,18 @@ namespace LC.Google.Protobuf return new ByteString(portion); } +#if GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY /// /// Constructs a from a read only span. The contents /// are copied, so further modifications to the span will not /// be reflected in the returned . /// + [SecuritySafeCritical] public static ByteString CopyFrom(ReadOnlySpan bytes) { return new ByteString(bytes.ToArray()); } +#endif /// /// Creates a new by encoding the specified text with @@ -256,7 +274,7 @@ namespace LC.Google.Protobuf /// public byte this[int index] { - get { return bytes.Span[index]; } + get { return bytes[index]; } } /// @@ -270,18 +288,7 @@ namespace LC.Google.Protobuf /// The result of decoding the binary data with the given decoding. public string ToString(Encoding encoding) { - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment segment)) - { - // Fast path. ByteString was created with an array. - return encoding.GetString(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array. Convert memory and pass result to GetString. - // TODO: Consider using GetString overload that takes a pointer. - byte[] array = bytes.ToArray(); - return encoding.GetString(array, 0, array.Length); - } + return encoding.GetString(bytes, 0, bytes.Length); } /// @@ -301,10 +308,9 @@ namespace LC.Google.Protobuf /// Returns an iterator over the bytes in this . /// /// An iterator over the bytes in this object. - [SecuritySafeCritical] public IEnumerator GetEnumerator() { - return MemoryMarshal.ToEnumerable(bytes).GetEnumerator(); + return ((IEnumerable) bytes).GetEnumerator(); } /// @@ -322,17 +328,7 @@ namespace LC.Google.Protobuf public CodedInputStream CreateCodedInput() { // We trust CodedInputStream not to reveal the provided byte array or modify it - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment segment) && segment.Count == bytes.Length) - { - // Fast path. ByteString was created with a complete array. - return new CodedInputStream(segment.Array); - } - else - { - // Slow path. BytesString is not an array, or is a slice of an array. - // Convert memory and pass result to WriteRawBytes. - return new CodedInputStream(bytes.ToArray()); - } + return new CodedInputStream(bytes); } /// @@ -351,8 +347,18 @@ namespace LC.Google.Protobuf { return false; } - - return lhs.bytes.Span.SequenceEqual(rhs.bytes.Span); + if (lhs.bytes.Length != rhs.bytes.Length) + { + return false; + } + for (int i = 0; i < lhs.Length; i++) + { + if (rhs.bytes[i] != lhs.bytes[i]) + { + return false; + } + } + return true; } /// @@ -371,7 +377,6 @@ namespace LC.Google.Protobuf /// /// The object to compare this with. /// true if refers to an equal ; false otherwise. - [SecuritySafeCritical] public override bool Equals(object obj) { return this == (obj as ByteString); @@ -382,15 +387,12 @@ namespace LC.Google.Protobuf /// will return the same hash code. /// /// A hash code for this object. - [SecuritySafeCritical] public override int GetHashCode() { - ReadOnlySpan b = bytes.Span; - int ret = 23; - for (int i = 0; i < b.Length; i++) + foreach (byte b in bytes) { - ret = (ret * 31) + b[i]; + ret = (ret * 31) + b; } return ret; } @@ -405,12 +407,20 @@ namespace LC.Google.Protobuf return this == other; } + /// + /// Used internally by CodedOutputStream to avoid creating a copy for the write + /// + internal void WriteRawBytesTo(CodedOutputStream outputStream) + { + outputStream.WriteRawBytes(bytes, 0, bytes.Length); + } + /// /// Copies the entire byte array to the destination array provided at the offset specified. /// public void CopyTo(byte[] array, int position) { - bytes.CopyTo(array.AsMemory(position)); + ByteArray.Copy(bytes, 0, array, position, bytes.Length); } /// @@ -418,17 +428,7 @@ namespace LC.Google.Protobuf /// public void WriteTo(Stream outputStream) { - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment segment)) - { - // Fast path. ByteString was created with an array, so pass the underlying array. - outputStream.Write(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array. Convert memory and pass result to WriteRawBytes. - var array = bytes.ToArray(); - outputStream.Write(array, 0, array.Length); - } + outputStream.Write(bytes, 0, bytes.Length); } } } \ No newline at end of file diff --git a/Libs/Google.Protobuf/ByteStringAsync.cs b/Libs/Google.Protobuf/ByteStringAsync.cs deleted file mode 100644 index 68c4d7f..0000000 --- a/Libs/Google.Protobuf/ByteStringAsync.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace LC.Google.Protobuf -{ - /// - /// SecuritySafeCritical attribute can not be placed on types with async methods. - /// This class has ByteString's async methods so it can be marked with SecuritySafeCritical. - /// - internal static class ByteStringAsync - { -#if !NET35 - internal static async Task FromStreamAsyncCore(Stream stream, CancellationToken cancellationToken) - { - int capacity = stream.CanSeek ? checked((int)(stream.Length - stream.Position)) : 0; - var memoryStream = new MemoryStream(capacity); - // We have to specify the buffer size here, as there's no overload accepting the cancellation token - // alone. But it's documented to use 81920 by default if not specified. - await stream.CopyToAsync(memoryStream, 81920, cancellationToken); -#if NETSTANDARD1_1 - byte[] bytes = memoryStream.ToArray(); -#else - // Avoid an extra copy if we can. - byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray(); -#endif - return ByteString.AttachBytes(bytes); - } -#endif - } -} \ No newline at end of file diff --git a/Libs/Google.Protobuf/Collections/MapField.cs b/Libs/Google.Protobuf/Collections/MapField.cs index 07ada24..c1923b6 100644 --- a/Libs/Google.Protobuf/Collections/MapField.cs +++ b/Libs/Google.Protobuf/Collections/MapField.cs @@ -448,10 +448,12 @@ namespace LC.Google.Protobuf.Collections [SecuritySafeCritical] public void AddEntriesFrom(ref ParseContext ctx, Codec codec) { + var adapter = new Codec.MessageAdapter(codec); do { - KeyValuePair entry = ParsingPrimitivesMessages.ReadMapEntry(ref ctx, codec); - this[entry.Key] = entry.Value; + adapter.Reset(); + ctx.ReadMessage(adapter); + this[adapter.Key] = adapter.Value; } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, codec.MapTag)); } @@ -483,13 +485,13 @@ namespace LC.Google.Protobuf.Collections [SecuritySafeCritical] public void WriteTo(ref WriteContext ctx, Codec codec) { + var message = new Codec.MessageAdapter(codec); foreach (var entry in list) { + message.Key = entry.Key; + message.Value = entry.Value; ctx.WriteTag(codec.MapTag); - - WritingPrimitives.WriteLength(ref ctx.buffer, ref ctx.state, CalculateEntrySize(codec, entry)); - codec.KeyCodec.WriteTagAndValue(ref ctx, entry.Key); - codec.ValueCodec.WriteTagAndValue(ref ctx, entry.Value); + ctx.WriteMessage(message); } } @@ -504,22 +506,18 @@ namespace LC.Google.Protobuf.Collections { return 0; } + var message = new Codec.MessageAdapter(codec); int size = 0; foreach (var entry in list) { - int entrySize = CalculateEntrySize(codec, entry); - + message.Key = entry.Key; + message.Value = entry.Value; size += CodedOutputStream.ComputeRawVarint32Size(codec.MapTag); - size += CodedOutputStream.ComputeLengthSize(entrySize) + entrySize; + size += CodedOutputStream.ComputeMessageSize(message); } return size; } - private static int CalculateEntrySize(Codec codec, KeyValuePair entry) - { - return codec.KeyCodec.CalculateSizeWithTag(entry.Key) + codec.ValueCodec.CalculateSizeWithTag(entry.Value); - } - /// /// Returns a string representation of this repeated field, in the same /// way as it would be represented by the default JSON formatter. @@ -656,20 +654,101 @@ namespace LC.Google.Protobuf.Collections this.mapTag = mapTag; } - /// - /// The key codec. - /// - internal FieldCodec KeyCodec => keyCodec; - - /// - /// The value codec. - /// - internal FieldCodec ValueCodec => valueCodec; - /// /// The tag used in the enclosing message to indicate map entries. /// - internal uint MapTag => mapTag; + internal uint MapTag { get { return mapTag; } } + + /// + /// A mutable message class, used for parsing and serializing. This + /// delegates the work to a codec, but implements the interface + /// for interop with and . + /// This is nested inside Codec as it's tightly coupled to the associated codec, + /// and it's simpler if it has direct access to all its fields. + /// + internal class MessageAdapter : IMessage, IBufferMessage + { + private static readonly byte[] ZeroLengthMessageStreamData = new byte[] { 0 }; + + private readonly Codec codec; + internal TKey Key { get; set; } + internal TValue Value { get; set; } + + internal MessageAdapter(Codec codec) + { + this.codec = codec; + } + + internal void Reset() + { + Key = codec.keyCodec.DefaultValue; + Value = codec.valueCodec.DefaultValue; + } + + public void MergeFrom(CodedInputStream input) + { + // Message adapter is an internal class and we know that all the parsing will happen via InternalMergeFrom. + throw new NotImplementedException(); + } + + [SecuritySafeCritical] + public void InternalMergeFrom(ref ParseContext ctx) + { + uint tag; + while ((tag = ctx.ReadTag()) != 0) + { + if (tag == codec.keyCodec.Tag) + { + Key = codec.keyCodec.Read(ref ctx); + } + else if (tag == codec.valueCodec.Tag) + { + Value = codec.valueCodec.Read(ref ctx); + } + else + { + ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state); + } + } + + // Corner case: a map entry with a key but no value, where the value type is a message. + // Read it as if we'd seen input with no data (i.e. create a "default" message). + if (Value == null) + { + if (ctx.state.CodedInputStream != null) + { + // the decoded message might not support parsing from ParseContext, so + // we need to allow fallback to the legacy MergeFrom(CodedInputStream) parsing. + Value = codec.valueCodec.Read(new CodedInputStream(ZeroLengthMessageStreamData)); + } + else + { + ParseContext.Initialize(new ReadOnlySequence(ZeroLengthMessageStreamData), out ParseContext zeroLengthCtx); + Value = codec.valueCodec.Read(ref zeroLengthCtx); + } + } + } + + public void WriteTo(CodedOutputStream output) + { + // Message adapter is an internal class and we know that all the writing will happen via InternalWriteTo. + throw new NotImplementedException(); + } + + [SecuritySafeCritical] + public void InternalWriteTo(ref WriteContext ctx) + { + codec.keyCodec.WriteTagAndValue(ref ctx, Key); + codec.valueCodec.WriteTagAndValue(ref ctx, Value); + } + + public int CalculateSize() + { + return codec.keyCodec.CalculateSizeWithTag(Key) + codec.valueCodec.CalculateSizeWithTag(Value); + } + + MessageDescriptor IMessage.Descriptor { get { return null; } } + } } private class MapView : ICollection, ICollection diff --git a/Libs/Google.Protobuf/ExtensionValue.cs b/Libs/Google.Protobuf/ExtensionValue.cs index 2b35159..cc24a22 100644 --- a/Libs/Google.Protobuf/ExtensionValue.cs +++ b/Libs/Google.Protobuf/ExtensionValue.cs @@ -59,7 +59,7 @@ namespace LC.Google.Protobuf public int CalculateSize() { - return codec.CalculateUnconditionalSizeWithTag(field); + return codec.CalculateSizeWithTag(field); } public IExtensionValue Clone() diff --git a/Libs/Google.Protobuf/FieldCodec.cs b/Libs/Google.Protobuf/FieldCodec.cs index b2447ac..c5b3c3b 100644 --- a/Libs/Google.Protobuf/FieldCodec.cs +++ b/Libs/Google.Protobuf/FieldCodec.cs @@ -876,12 +876,6 @@ namespace LC.Google.Protobuf /// public int CalculateSizeWithTag(T value) => IsDefault(value) ? 0 : ValueSizeCalculator(value) + tagSize; - /// - /// Calculates the size required to write the given value, with a tag, even - /// if the value is the default. - /// - internal int CalculateUnconditionalSizeWithTag(T value) => ValueSizeCalculator(value) + tagSize; - private bool IsDefault(T value) => EqualityComparer.Equals(value, DefaultValue); } } diff --git a/Libs/Google.Protobuf/IBufferMessage.cs b/Libs/Google.Protobuf/IBufferMessage.cs index 7bd62d4..6c6a5b7 100644 --- a/Libs/Google.Protobuf/IBufferMessage.cs +++ b/Libs/Google.Protobuf/IBufferMessage.cs @@ -32,6 +32,7 @@ namespace LC.Google.Protobuf { +#if GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY /// /// Interface for a Protocol Buffers message, supporting /// parsing from and writing to . @@ -50,4 +51,5 @@ namespace LC.Google.Protobuf /// void InternalWriteTo(ref WriteContext ctx); } +#endif } diff --git a/Libs/Google.Protobuf/LC.Google.Protobuf.csproj b/Libs/Google.Protobuf/LC.Google.Protobuf.csproj index b725648..e3c71bc 100644 --- a/Libs/Google.Protobuf/LC.Google.Protobuf.csproj +++ b/Libs/Google.Protobuf/LC.Google.Protobuf.csproj @@ -1,10 +1,10 @@ - + C# runtime library for Protocol Buffers - Google's data interchange format. Copyright 2015, Google Inc. Google Protocol Buffers - 3.15.6 + 3.14.0 7.2 Google Inc. @@ -12,32 +12,35 @@ true ./keys/Google.Protobuf.snk true + true Protocol;Buffers;Binary;Serialization;Format;Google;proto;proto3 C# proto3 support https://github.com/protocolbuffers/protobuf https://github.com/protocolbuffers/protobuf/blob/master/LICENSE git https://github.com/protocolbuffers/protobuf.git + $(DefineConstants);GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY True $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb 0.7.1 - LC.Google.Protobuf + LC.Google.Protobuf $(DefineConstants);GOOGLE_PROTOBUF_SUPPORT_FAST_STRING - - $(DefineConstants);GOOGLE_PROTOBUF_SUPPORT_FAST_STRING;GOOGLE_PROTOBUF_SIMD - - + - + + + + + diff --git a/Libs/Google.Protobuf/ParsingPrimitivesMessages.cs b/Libs/Google.Protobuf/ParsingPrimitivesMessages.cs index b11caa1..c685c6c 100644 --- a/Libs/Google.Protobuf/ParsingPrimitivesMessages.cs +++ b/Libs/Google.Protobuf/ParsingPrimitivesMessages.cs @@ -32,11 +32,9 @@ using System; using System.Buffers; -using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Security; -using LC.Google.Protobuf.Collections; namespace LC.Google.Protobuf { @@ -46,8 +44,6 @@ namespace LC.Google.Protobuf [SecuritySafeCritical] internal static class ParsingPrimitivesMessages { - private static readonly byte[] ZeroLengthMessageStreamData = new byte[] { 0 }; - public static void SkipLastField(ref ReadOnlySpan buffer, ref ParserInternalState state) { if (state.lastTag == 0) @@ -138,65 +134,6 @@ namespace LC.Google.Protobuf SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit); } - public static KeyValuePair ReadMapEntry(ref ParseContext ctx, MapField.Codec codec) - { - int length = ParsingPrimitives.ParseLength(ref ctx.buffer, ref ctx.state); - if (ctx.state.recursionDepth >= ctx.state.recursionLimit) - { - throw InvalidProtocolBufferException.RecursionLimitExceeded(); - } - int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length); - ++ctx.state.recursionDepth; - - TKey key = codec.KeyCodec.DefaultValue; - TValue value = codec.ValueCodec.DefaultValue; - - uint tag; - while ((tag = ctx.ReadTag()) != 0) - { - if (tag == codec.KeyCodec.Tag) - { - key = codec.KeyCodec.Read(ref ctx); - } - else if (tag == codec.ValueCodec.Tag) - { - value = codec.ValueCodec.Read(ref ctx); - } - else - { - SkipLastField(ref ctx.buffer, ref ctx.state); - } - } - - // Corner case: a map entry with a key but no value, where the value type is a message. - // Read it as if we'd seen input with no data (i.e. create a "default" message). - if (value == null) - { - if (ctx.state.CodedInputStream != null) - { - // the decoded message might not support parsing from ParseContext, so - // we need to allow fallback to the legacy MergeFrom(CodedInputStream) parsing. - value = codec.ValueCodec.Read(new CodedInputStream(ZeroLengthMessageStreamData)); - } - else - { - ParseContext.Initialize(new ReadOnlySequence(ZeroLengthMessageStreamData), out ParseContext zeroLengthCtx); - value = codec.ValueCodec.Read(ref zeroLengthCtx); - } - } - - CheckReadEndOfStreamTag(ref ctx.state); - // Check that we've read exactly as much data as expected. - if (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) - { - throw InvalidProtocolBufferException.TruncatedMessage(); - } - --ctx.state.recursionDepth; - SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit); - - return new KeyValuePair(key, value); - } - public static void ReadGroup(ref ParseContext ctx, IMessage message) { if (ctx.state.recursionDepth >= ctx.state.recursionLimit) diff --git a/Libs/Google.Protobuf/Reflection/Descriptor.cs b/Libs/Google.Protobuf/Reflection/Descriptor.cs index 3afa27f..328346b 100644 --- a/Libs/Google.Protobuf/Reflection/Descriptor.cs +++ b/Libs/Google.Protobuf/Reflection/Descriptor.cs @@ -107,58 +107,57 @@ namespace LC.Google.Protobuf.Reflection { "eV9wYWNrYWdlGC0gASgJEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMo", "CzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIjoKDE9w", "dGltaXplTW9kZRIJCgVTUEVFRBABEg0KCUNPREVfU0laRRACEhAKDExJVEVf", - "UlVOVElNRRADKgkI6AcQgICAgAJKBAgmECcihAIKDk1lc3NhZ2VPcHRpb25z", + "UlVOVElNRRADKgkI6AcQgICAgAJKBAgmECci8gEKDk1lc3NhZ2VPcHRpb25z", "EiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9ybWF0GAEgASgIOgVmYWxzZRIuCh9u", "b19zdGFuZGFyZF9kZXNjcmlwdG9yX2FjY2Vzc29yGAIgASgIOgVmYWxzZRIZ", "CgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIRCgltYXBfZW50cnkYByABKAgS", "QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv", - "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAQQBUoECAUQ", - "BkoECAYQB0oECAgQCUoECAkQCiKeAwoMRmllbGRPcHRpb25zEjoKBWN0eXBl", - "GAEgASgOMiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToG", - "U1RSSU5HEg4KBnBhY2tlZBgCIAEoCBI/CgZqc3R5cGUYBiABKA4yJC5nb29n", - "bGUucHJvdG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFMEhMK", - "BGxhenkYBSABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNl", - "EhMKBHdlYWsYCiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9u", - "GOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9u", - "Ii8KBUNUeXBlEgoKBlNUUklORxAAEggKBENPUkQQARIQCgxTVFJJTkdfUElF", - "Q0UQAiI1CgZKU1R5cGUSDQoJSlNfTk9STUFMEAASDQoJSlNfU1RSSU5HEAES", - "DQoJSlNfTlVNQkVSEAIqCQjoBxCAgICAAkoECAQQBSJeCgxPbmVvZk9wdGlv", - "bnMSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnBy", - "b3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoLRW51", - "bU9wdGlvbnMSEwoLYWxsb3dfYWxpYXMYAiABKAgSGQoKZGVwcmVjYXRlZBgD", - "IAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQu", - "Z29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICA", - "AkoECAUQBiJ9ChBFbnVtVmFsdWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQYASAB", - "KAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdv", - "b2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi", - "ewoOU2VydmljZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2US", - "QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv", - "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKtAgoNTWV0aG9k", - "T3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJfChFpZGVtcG90", - "ZW5jeV9sZXZlbBgiIAEoDjIvLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRp", - "b25zLklkZW1wb3RlbmN5TGV2ZWw6E0lERU1QT1RFTkNZX1VOS05PV04SQwoU", - "dW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVm", - "LlVuaW50ZXJwcmV0ZWRPcHRpb24iUAoQSWRlbXBvdGVuY3lMZXZlbBIXChNJ", - "REVNUE9URU5DWV9VTktOT1dOEAASEwoPTk9fU0lERV9FRkZFQ1RTEAESDgoK", - "SURFTVBPVEVOVBACKgkI6AcQgICAgAIingIKE1VuaW50ZXJwcmV0ZWRPcHRp", - "b24SOwoEbmFtZRgCIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJl", - "dGVkT3B0aW9uLk5hbWVQYXJ0EhgKEGlkZW50aWZpZXJfdmFsdWUYAyABKAkS", - "GgoScG9zaXRpdmVfaW50X3ZhbHVlGAQgASgEEhoKEm5lZ2F0aXZlX2ludF92", - "YWx1ZRgFIAEoAxIUCgxkb3VibGVfdmFsdWUYBiABKAESFAoMc3RyaW5nX3Zh", - "bHVlGAcgASgMEhcKD2FnZ3JlZ2F0ZV92YWx1ZRgIIAEoCRozCghOYW1lUGFy", - "dBIRCgluYW1lX3BhcnQYASACKAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigIItUB", - "Cg5Tb3VyY2VDb2RlSW5mbxI6Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2dsZS5w", - "cm90b2J1Zi5Tb3VyY2VDb2RlSW5mby5Mb2NhdGlvbhqGAQoITG9jYXRpb24S", - "EAoEcGF0aBgBIAMoBUICEAESEAoEc3BhbhgCIAMoBUICEAESGAoQbGVhZGlu", - "Z19jb21tZW50cxgDIAEoCRIZChF0cmFpbGluZ19jb21tZW50cxgEIAEoCRIh", - "ChlsZWFkaW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJIqcBChFHZW5lcmF0", - "ZWRDb2RlSW5mbxJBCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3Rv", - "YnVmLkdlbmVyYXRlZENvZGVJbmZvLkFubm90YXRpb24aTwoKQW5ub3RhdGlv", - "bhIQCgRwYXRoGAEgAygFQgIQARITCgtzb3VyY2VfZmlsZRgCIAEoCRINCgVi", - "ZWdpbhgDIAEoBRILCgNlbmQYBCABKAVCfgoTY29tLmdvb2dsZS5wcm90b2J1", - "ZkIQRGVzY3JpcHRvclByb3Rvc0gBWi1nb29nbGUuZ29sYW5nLm9yZy9wcm90", - "b2J1Zi90eXBlcy9kZXNjcmlwdG9ycGL4AQGiAgNHUEKqAhpHb29nbGUuUHJv", - "dG9idWYuUmVmbGVjdGlvbg==")); + "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAgQCUoECAkQ", + "CiKeAwoMRmllbGRPcHRpb25zEjoKBWN0eXBlGAEgASgOMiMuZ29vZ2xlLnBy", + "b3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToGU1RSSU5HEg4KBnBhY2tlZBgC", + "IAEoCBI/CgZqc3R5cGUYBiABKA4yJC5nb29nbGUucHJvdG9idWYuRmllbGRP", + "cHRpb25zLkpTVHlwZToJSlNfTk9STUFMEhMKBGxhenkYBSABKAg6BWZhbHNl", + "EhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEhMKBHdlYWsYCiABKAg6BWZh", + "bHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5w", + "cm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIi8KBUNUeXBlEgoKBlNUUklO", + "RxAAEggKBENPUkQQARIQCgxTVFJJTkdfUElFQ0UQAiI1CgZKU1R5cGUSDQoJ", + "SlNfTk9STUFMEAASDQoJSlNfU1RSSU5HEAESDQoJSlNfTlVNQkVSEAIqCQjo", + "BxCAgICAAkoECAQQBSJeCgxPbmVvZk9wdGlvbnMSQwoUdW5pbnRlcnByZXRl", + "ZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0", + "ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoLRW51bU9wdGlvbnMSEwoLYWxsb3df", + "YWxpYXMYAiABKAgSGQoKZGVwcmVjYXRlZBgDIAEoCDoFZmFsc2USQwoUdW5p", + "bnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVu", + "aW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAUQBiJ9ChBFbnVtVmFs", + "dWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQYASABKAg6BWZhbHNlEkMKFHVuaW50", + "ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5Vbmlu", + "dGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIiewoOU2VydmljZU9wdGlvbnMS", + "GQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9v", + "cHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRP", + "cHRpb24qCQjoBxCAgICAAiKtAgoNTWV0aG9kT3B0aW9ucxIZCgpkZXByZWNh", + "dGVkGCEgASgIOgVmYWxzZRJfChFpZGVtcG90ZW5jeV9sZXZlbBgiIAEoDjIv", + "Lmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zLklkZW1wb3RlbmN5TGV2", + "ZWw6E0lERU1QT1RFTkNZX1VOS05PV04SQwoUdW5pbnRlcnByZXRlZF9vcHRp", + "b24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRp", + "b24iUAoQSWRlbXBvdGVuY3lMZXZlbBIXChNJREVNUE9URU5DWV9VTktOT1dO", + "EAASEwoPTk9fU0lERV9FRkZFQ1RTEAESDgoKSURFTVBPVEVOVBACKgkI6AcQ", + "gICAgAIingIKE1VuaW50ZXJwcmV0ZWRPcHRpb24SOwoEbmFtZRgCIAMoCzIt", + "Lmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uLk5hbWVQYXJ0", + "EhgKEGlkZW50aWZpZXJfdmFsdWUYAyABKAkSGgoScG9zaXRpdmVfaW50X3Zh", + "bHVlGAQgASgEEhoKEm5lZ2F0aXZlX2ludF92YWx1ZRgFIAEoAxIUCgxkb3Vi", + "bGVfdmFsdWUYBiABKAESFAoMc3RyaW5nX3ZhbHVlGAcgASgMEhcKD2FnZ3Jl", + "Z2F0ZV92YWx1ZRgIIAEoCRozCghOYW1lUGFydBIRCgluYW1lX3BhcnQYASAC", + "KAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigIItUBCg5Tb3VyY2VDb2RlSW5mbxI6", + "Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb2Rl", + "SW5mby5Mb2NhdGlvbhqGAQoITG9jYXRpb24SEAoEcGF0aBgBIAMoBUICEAES", + "EAoEc3BhbhgCIAMoBUICEAESGAoQbGVhZGluZ19jb21tZW50cxgDIAEoCRIZ", + "ChF0cmFpbGluZ19jb21tZW50cxgEIAEoCRIhChlsZWFkaW5nX2RldGFjaGVk", + "X2NvbW1lbnRzGAYgAygJIqcBChFHZW5lcmF0ZWRDb2RlSW5mbxJBCgphbm5v", + "dGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3RvYnVmLkdlbmVyYXRlZENvZGVJ", + "bmZvLkFubm90YXRpb24aTwoKQW5ub3RhdGlvbhIQCgRwYXRoGAEgAygFQgIQ", + "ARITCgtzb3VyY2VfZmlsZRgCIAEoCRINCgViZWdpbhgDIAEoBRILCgNlbmQY", + "BCABKAVCfgoTY29tLmdvb2dsZS5wcm90b2J1ZkIQRGVzY3JpcHRvclByb3Rv", + "c0gBWi1nb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9kZXNjcmlw", + "dG9ycGL4AQGiAgNHUEKqAhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbg==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { diff --git a/Libs/Google.Protobuf/Reflection/FileDescriptor.cs b/Libs/Google.Protobuf/Reflection/FileDescriptor.cs index 6724ef5..58a31c1 100644 --- a/Libs/Google.Protobuf/Reflection/FileDescriptor.cs +++ b/Libs/Google.Protobuf/Reflection/FileDescriptor.cs @@ -481,21 +481,18 @@ namespace LC.Google.Protobuf.Reflection /// dependencies must come before the descriptor which depends on them. (If A depends on B, and B /// depends on C, then the descriptors must be presented in the order C, B, A.) This is compatible /// with the order in which protoc provides descriptors to plugins. - /// The extension registry to use when parsing, or null if no extensions are required. /// The file descriptors corresponding to . - public static IReadOnlyList BuildFromByteStrings(IEnumerable descriptorData, ExtensionRegistry registry) + public static IReadOnlyList BuildFromByteStrings(IEnumerable descriptorData) { ProtoPreconditions.CheckNotNull(descriptorData, nameof(descriptorData)); - var parser = FileDescriptorProto.Parser.WithExtensionRegistry(registry); - // TODO: See if we can build a single DescriptorPool instead of building lots of them. // This will all behave correctly, but it's less efficient than we'd like. var descriptors = new List(); var descriptorsByName = new Dictionary(); foreach (var data in descriptorData) { - var proto = parser.ParseFrom(data); + var proto = FileDescriptorProto.Parser.ParseFrom(data); var dependencies = new List(); foreach (var dependencyName in proto.Dependency) { @@ -521,18 +518,6 @@ namespace LC.Google.Protobuf.Reflection return new ReadOnlyCollection(descriptors); } - /// - /// Converts the given descriptor binary data into FileDescriptor objects. - /// Note: reflection using the returned FileDescriptors is not currently supported. - /// - /// The binary file descriptor proto data. Must not be null, and any - /// dependencies must come before the descriptor which depends on them. (If A depends on B, and B - /// depends on C, then the descriptors must be presented in the order C, B, A.) This is compatible - /// with the order in which protoc provides descriptors to plugins. - /// The file descriptors corresponding to . - public static IReadOnlyList BuildFromByteStrings(IEnumerable descriptorData) => - BuildFromByteStrings(descriptorData, null); - /// /// Returns a that represents this instance. /// diff --git a/Libs/Google.Protobuf/UnsafeByteOperations.cs b/Libs/Google.Protobuf/UnsafeByteOperations.cs deleted file mode 100644 index 42cc138..0000000 --- a/Libs/Google.Protobuf/UnsafeByteOperations.cs +++ /dev/null @@ -1,81 +0,0 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Security; - -namespace LC.Google.Protobuf -{ - /// - /// Provides a number of unsafe byte operations to be used by advanced applications with high performance - /// requirements. These methods are referred to as "unsafe" due to the fact that they potentially expose - /// the backing buffer of a to the application. - /// - /// - /// - /// The methods in this class should only be called if it is guaranteed that the buffer backing the - /// will never change! Mutation of a can lead to unexpected - /// and undesirable consequences in your application, and will likely be difficult to debug. Proceed with caution! - /// - /// - /// This can have a number of significant side affects that have spooky-action-at-a-distance-like behavior. In - /// particular, if the bytes value changes out from under a Protocol Buffer: - /// - /// - /// - /// serialization may throw - /// - /// - /// serialization may succeed but the wrong bytes may be written out - /// - /// - /// objects that are normally immutable (such as ByteString) are no longer immutable - /// - /// - /// hashCode may be incorrect - /// - /// - /// - [SecuritySafeCritical] - public static class UnsafeByteOperations - { - /// - /// Constructs a new from the given bytes. The bytes are not copied, - /// and must not be modified while the is in use. - /// This API is experimental and subject to change. - /// - public static ByteString UnsafeWrap(ReadOnlyMemory bytes) - { - return ByteString.AttachBytes(bytes); - } - } -} diff --git a/Libs/Google.Protobuf/WritingPrimitives.cs b/Libs/Google.Protobuf/WritingPrimitives.cs index 0babf09..75937b4 100644 --- a/Libs/Google.Protobuf/WritingPrimitives.cs +++ b/Libs/Google.Protobuf/WritingPrimitives.cs @@ -32,14 +32,8 @@ using System; using System.Buffers.Binary; -using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -#if GOOGLE_PROTOBUF_SIMD -using System.Runtime.Intrinsics; -using System.Runtime.Intrinsics.Arm; -using System.Runtime.Intrinsics.X86; -#endif using System.Security; using System.Text; @@ -51,11 +45,8 @@ namespace LC.Google.Protobuf [SecuritySafeCritical] internal static class WritingPrimitives { -#if NET5_0 - internal static Encoding Utf8Encoding => Encoding.UTF8; // allows JIT to devirtualize -#else - internal static readonly Encoding Utf8Encoding = Encoding.UTF8; // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.) -#endif + // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.) + internal static readonly Encoding Utf8Encoding = Encoding.UTF8; #region Writing of values (not including tags) @@ -172,34 +163,39 @@ namespace LC.Google.Protobuf /// public static void WriteString(ref Span buffer, ref WriterInternalState state, string value) { - const int MaxBytesPerChar = 3; - const int MaxSmallStringLength = 128 / MaxBytesPerChar; - - // The string is small enough that the length will always be a 1 byte varint. - // Also there is enough space to write length + bytes to buffer. - // Write string directly to the buffer, and then write length. - // This saves calling GetByteCount on the string. We get the string length from GetBytes. - if (value.Length <= MaxSmallStringLength && buffer.Length - state.position - 1 >= value.Length * MaxBytesPerChar) - { - int indexOfLengthDelimiter = state.position++; - buffer[indexOfLengthDelimiter] = (byte)WriteStringToBuffer(buffer, ref state, value); - return; - } - - int length = Utf8Encoding.GetByteCount(value); - WriteLength(ref buffer, ref state, length); - // Optimise the case where we have enough space to write // the string directly to the buffer, which should be common. + int length = Utf8Encoding.GetByteCount(value); + WriteLength(ref buffer, ref state, length); if (buffer.Length - state.position >= length) { if (length == value.Length) // Must be all ASCII... { - WriteAsciiStringToBuffer(buffer, ref state, value, length); + for (int i = 0; i < length; i++) + { + buffer[state.position + i] = (byte)value[i]; + } + state.position += length; } else { - WriteStringToBuffer(buffer, ref state, value); +#if NETSTANDARD1_1 + // slowpath when Encoding.GetBytes(Char*, Int32, Byte*, Int32) is not available + byte[] bytes = Utf8Encoding.GetBytes(value); + WriteRawBytes(ref buffer, ref state, bytes); +#else + ReadOnlySpan source = value.AsSpan(); + int bytesUsed; + unsafe + { + fixed (char* sourceChars = &MemoryMarshal.GetReference(source)) + fixed (byte* destinationBytes = &MemoryMarshal.GetReference(buffer.Slice(state.position))) + { + bytesUsed = Utf8Encoding.GetBytes(sourceChars, source.Length, destinationBytes, buffer.Length); + } + } + state.position += bytesUsed; +#endif } } else @@ -213,131 +209,6 @@ namespace LC.Google.Protobuf } } - // Calling this method with non-ASCII content will break. - // Content must be verified to be all ASCII before using this method. - private static void WriteAsciiStringToBuffer(Span buffer, ref WriterInternalState state, string value, int length) - { - ref char sourceChars = ref MemoryMarshal.GetReference(value.AsSpan()); - ref byte destinationBytes = ref MemoryMarshal.GetReference(buffer.Slice(state.position)); - - int currentIndex = 0; - // If 64bit, process 4 chars at a time. - // The logic inside this check will be elided by JIT in 32bit programs. - if (IntPtr.Size == 8) - { - // Need at least 4 chars available to use this optimization. - if (length >= 4) - { - ref byte sourceBytes = ref Unsafe.As(ref sourceChars); - - // Process 4 chars at a time until there are less than 4 remaining. - // We already know all characters are ASCII so there is no need to validate the source. - int lastIndexWhereCanReadFourChars = value.Length - 4; - do - { - NarrowFourUtf16CharsToAsciiAndWriteToBuffer( - ref Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex), - Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref sourceBytes, (IntPtr)(currentIndex * 2)))); - - } while ((currentIndex += 4) <= lastIndexWhereCanReadFourChars); - } - } - - // Process any remaining, 1 char at a time. - // Avoid bounds checking with ref + Unsafe - for (; currentIndex < length; currentIndex++) - { - Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex) = (byte)Unsafe.AddByteOffset(ref sourceChars, (IntPtr)(currentIndex * 2)); - } - - state.position += length; - } - - // Copied with permission from https://github.com/dotnet/runtime/blob/1cdafd27e4afd2c916af5df949c13f8b373c4335/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIUtility.cs#L1119-L1171 - // - /// - /// Given a QWORD which represents a buffer of 4 ASCII chars in machine-endian order, - /// narrows each WORD to a BYTE, then writes the 4-byte result to the output buffer - /// also in machine-endian order. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void NarrowFourUtf16CharsToAsciiAndWriteToBuffer(ref byte outputBuffer, ulong value) - { -#if GOOGLE_PROTOBUF_SIMD - if (Sse2.X64.IsSupported) - { - // Narrows a vector of words [ w0 w1 w2 w3 ] to a vector of bytes - // [ b0 b1 b2 b3 b0 b1 b2 b3 ], then writes 4 bytes (32 bits) to the destination. - - Vector128 vecWide = Sse2.X64.ConvertScalarToVector128UInt64(value).AsInt16(); - Vector128 vecNarrow = Sse2.PackUnsignedSaturate(vecWide, vecWide).AsUInt32(); - Unsafe.WriteUnaligned(ref outputBuffer, Sse2.ConvertToUInt32(vecNarrow)); - } - else if (AdvSimd.IsSupported) - { - // Narrows a vector of words [ w0 w1 w2 w3 ] to a vector of bytes - // [ b0 b1 b2 b3 * * * * ], then writes 4 bytes (32 bits) to the destination. - - Vector128 vecWide = Vector128.CreateScalarUnsafe(value).AsInt16(); - Vector64 lower = AdvSimd.ExtractNarrowingSaturateUnsignedLower(vecWide); - Unsafe.WriteUnaligned(ref outputBuffer, lower.AsUInt32().ToScalar()); - } - else -#endif - { - // Fallback to non-SIMD approach when SIMD is not available. - // This could happen either because the APIs are not available, or hardware doesn't support it. - // Processing 4 chars at a time in this fallback is still faster than casting one char at a time. - if (BitConverter.IsLittleEndian) - { - outputBuffer = (byte)value; - value >>= 16; - Unsafe.Add(ref outputBuffer, 1) = (byte)value; - value >>= 16; - Unsafe.Add(ref outputBuffer, 2) = (byte)value; - value >>= 16; - Unsafe.Add(ref outputBuffer, 3) = (byte)value; - } - else - { - Unsafe.Add(ref outputBuffer, 3) = (byte)value; - value >>= 16; - Unsafe.Add(ref outputBuffer, 2) = (byte)value; - value >>= 16; - Unsafe.Add(ref outputBuffer, 1) = (byte)value; - value >>= 16; - outputBuffer = (byte)value; - } - } - } - - private static int WriteStringToBuffer(Span buffer, ref WriterInternalState state, string value) - { -#if NETSTANDARD1_1 - // slowpath when Encoding.GetBytes(Char*, Int32, Byte*, Int32) is not available - byte[] bytes = Utf8Encoding.GetBytes(value); - WriteRawBytes(ref buffer, ref state, bytes); - return bytes.Length; -#else - ReadOnlySpan source = value.AsSpan(); - int bytesUsed; - unsafe - { - fixed (char* sourceChars = &MemoryMarshal.GetReference(source)) - fixed (byte* destinationBytes = &MemoryMarshal.GetReference(buffer)) - { - bytesUsed = Utf8Encoding.GetBytes( - sourceChars, - source.Length, - destinationBytes + state.position, - buffer.Length - state.position); - } - } - state.position += bytesUsed; - return bytesUsed; -#endif - } - /// /// Write a byte string, without a tag, to the stream. /// The data is length-prefixed. diff --git a/Libs/Newtonsoft.Json/Bson/BsonBinaryType.cs b/Libs/Newtonsoft.Json/Bson/BsonBinaryType.cs index 8c37edf..ee3d455 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonBinaryType.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonBinaryType.cs @@ -25,8 +25,6 @@ using System; -#nullable disable - namespace LC.Newtonsoft.Json.Bson { internal enum BsonBinaryType : byte diff --git a/Libs/Newtonsoft.Json/Bson/BsonBinaryWriter.cs b/Libs/Newtonsoft.Json/Bson/BsonBinaryWriter.cs index 2617ff6..112484e 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonBinaryWriter.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonBinaryWriter.cs @@ -29,8 +29,6 @@ using System.IO; using System.Text; using LC.Newtonsoft.Json.Utilities; -#nullable disable - namespace LC.Newtonsoft.Json.Bson { internal class BsonBinaryWriter diff --git a/Libs/Newtonsoft.Json/Bson/BsonObjectId.cs b/Libs/Newtonsoft.Json/Bson/BsonObjectId.cs index 4244cb2..e8ee9d5 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonObjectId.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonObjectId.cs @@ -26,8 +26,6 @@ using System; using LC.Newtonsoft.Json.Utilities; -#nullable disable - namespace LC.Newtonsoft.Json.Bson { /// diff --git a/Libs/Newtonsoft.Json/Bson/BsonReader.cs b/Libs/Newtonsoft.Json/Bson/BsonReader.cs index 3790513..7134c71 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonReader.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonReader.cs @@ -32,8 +32,6 @@ using LC.Newtonsoft.Json.Serialization; using LC.Newtonsoft.Json.Utilities; using LC.Newtonsoft.Json.Linq; -#nullable disable - namespace LC.Newtonsoft.Json.Bson { /// diff --git a/Libs/Newtonsoft.Json/Bson/BsonToken.cs b/Libs/Newtonsoft.Json/Bson/BsonToken.cs index 73e5014..8926480 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonToken.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonToken.cs @@ -26,8 +26,6 @@ using System.Collections; using System.Collections.Generic; -#nullable disable - namespace LC.Newtonsoft.Json.Bson { internal abstract class BsonToken diff --git a/Libs/Newtonsoft.Json/Bson/BsonType.cs b/Libs/Newtonsoft.Json/Bson/BsonType.cs index 90d7b08..b640014 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonType.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonType.cs @@ -23,8 +23,6 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#nullable disable - namespace LC.Newtonsoft.Json.Bson { internal enum BsonType : sbyte diff --git a/Libs/Newtonsoft.Json/Bson/BsonWriter.cs b/Libs/Newtonsoft.Json/Bson/BsonWriter.cs index 1f059d6..3c80936 100644 --- a/Libs/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Libs/Newtonsoft.Json/Bson/BsonWriter.cs @@ -35,8 +35,6 @@ using LC.Newtonsoft.Json.Utilities; using LC.Newtonsoft.Json.Linq; using System.Globalization; -#nullable disable - namespace LC.Newtonsoft.Json.Bson { /// diff --git a/Libs/Newtonsoft.Json/Converters/BinaryConverter.cs b/Libs/Newtonsoft.Json/Converters/BinaryConverter.cs index 8462478..bc2f128 100644 --- a/Libs/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -28,7 +28,6 @@ using System; using System.Globalization; using LC.Newtonsoft.Json.Utilities; using System.Collections.Generic; -using System.Diagnostics; #if HAVE_ADO_NET using System.Data.SqlTypes; #endif @@ -43,7 +42,7 @@ namespace LC.Newtonsoft.Json.Converters #if HAVE_LINQ private const string BinaryTypeName = "System.Data.Linq.Binary"; private const string BinaryToArrayName = "ToArray"; - private static ReflectionObject? _reflectionObject; + private static ReflectionObject _reflectionObject; #endif /// @@ -52,7 +51,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -71,9 +70,7 @@ namespace LC.Newtonsoft.Json.Converters if (value.GetType().FullName == BinaryTypeName) { EnsureReflectionObject(value.GetType()); - MiscellaneousUtils.Assert(_reflectionObject != null); - - return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!; + return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName); } #endif #if HAVE_ADO_NET @@ -104,7 +101,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -126,7 +123,7 @@ namespace LC.Newtonsoft.Json.Converters { // current token is already at base64 string // unable to call ReadAsBytes so do it the old fashion way - string encodedData = reader.Value!.ToString(); + string encodedData = reader.Value.ToString(); data = Convert.FromBase64String(encodedData); } else @@ -142,9 +139,8 @@ namespace LC.Newtonsoft.Json.Converters if (t.FullName == BinaryTypeName) { EnsureReflectionObject(t); - MiscellaneousUtils.Assert(_reflectionObject != null); - return _reflectionObject.Creator!(data); + return _reflectionObject.Creator(data); } #endif diff --git a/Libs/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs b/Libs/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs index 6e2a3e9..97c0f47 100644 --- a/Libs/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs @@ -28,8 +28,6 @@ using LC.Newtonsoft.Json.Bson; using System.Globalization; using LC.Newtonsoft.Json.Utilities; -#nullable disable - namespace LC.Newtonsoft.Json.Converters { /// diff --git a/Libs/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/Libs/Newtonsoft.Json/Converters/CustomCreationConverter.cs index b08fe59..2cbb828 100644 --- a/Libs/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -41,7 +41,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotSupportedException("CustomCreationConverter should only be used while deserializing."); } @@ -54,7 +54,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { diff --git a/Libs/Newtonsoft.Json/Converters/DataSetConverter.cs b/Libs/Newtonsoft.Json/Converters/DataSetConverter.cs index c4f57bf..278a2f4 100644 --- a/Libs/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -41,7 +41,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -50,7 +50,7 @@ namespace LC.Newtonsoft.Json.Converters } DataSet dataSet = (DataSet)value; - DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; DataTableConverter converter = new DataTableConverter(); @@ -74,7 +74,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -92,10 +92,10 @@ namespace LC.Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.PropertyName) { - DataTable dt = ds.Tables[(string)reader.Value!]; + DataTable dt = ds.Tables[(string)reader.Value]; bool exists = (dt != null); - dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!; + dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer); if (!exists) { diff --git a/Libs/Newtonsoft.Json/Converters/DataTableConverter.cs b/Libs/Newtonsoft.Json/Converters/DataTableConverter.cs index afaec81..704e26a 100644 --- a/Libs/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -45,7 +45,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -54,7 +54,7 @@ namespace LC.Newtonsoft.Json.Converters } DataTable table = (DataTable)value; - DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartArray(); @@ -87,7 +87,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -106,7 +106,7 @@ namespace LC.Newtonsoft.Json.Converters // populate the name from the property name if (reader.TokenType == JsonToken.PropertyName) { - dt.TableName = (string)reader.Value!; + dt.TableName = (string)reader.Value; reader.ReadAndAssert(); @@ -140,7 +140,7 @@ namespace LC.Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.PropertyName) { - string columnName = (string)reader.Value!; + string columnName = (string)reader.Value; reader.ReadAndAssert(); @@ -177,7 +177,7 @@ namespace LC.Newtonsoft.Json.Converters reader.ReadAndAssert(); } - List o = new List(); + List o = new List(); while (reader.TokenType != JsonToken.EndArray) { @@ -218,7 +218,7 @@ namespace LC.Newtonsoft.Json.Converters case JsonToken.String: case JsonToken.Date: case JsonToken.Bytes: - return reader.ValueType!; + return reader.ValueType; case JsonToken.Null: case JsonToken.Undefined: case JsonToken.EndArray: diff --git a/Libs/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs b/Libs/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs index 184ecb5..014623c 100644 --- a/Libs/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs @@ -48,32 +48,17 @@ namespace LC.Newtonsoft.Json.Converters #region UnionDefinition internal class Union { - public readonly FSharpFunction TagReader; - public readonly List Cases; - - public Union(FSharpFunction tagReader, List cases) - { - TagReader = tagReader; - Cases = cases; - } + public List Cases; + public FSharpFunction TagReader { get; set; } } internal class UnionCase { - public readonly int Tag; - public readonly string Name; - public readonly PropertyInfo[] Fields; - public readonly FSharpFunction FieldReader; - public readonly FSharpFunction Constructor; - - public UnionCase(int tag, string name, PropertyInfo[] fields, FSharpFunction fieldReader, FSharpFunction constructor) - { - Tag = tag; - Name = name; - Fields = fields; - FieldReader = fieldReader; - Constructor = constructor; - } + public int Tag; + public string Name; + public PropertyInfo[] Fields; + public FSharpFunction FieldReader; + public FSharpFunction Constructor; } #endregion @@ -89,28 +74,31 @@ namespace LC.Newtonsoft.Json.Converters // need to get declaring type to avoid duplicate Unions in cache // hacky but I can't find an API to get the declaring type without GetUnionCases - object[] cases = (object[])FSharpUtils.Instance.GetUnionCases(null, t, null)!; + object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null); object caseInfo = cases.First(); - Type unionType = (Type)FSharpUtils.Instance.GetUnionCaseInfoDeclaringType(caseInfo)!; + Type unionType = (Type)FSharpUtils.GetUnionCaseInfoDeclaringType(caseInfo); return unionType; } private static Union CreateUnion(Type t) { - Union u = new Union((FSharpFunction)FSharpUtils.Instance.PreComputeUnionTagReader(null, t, null), new List()); + Union u = new Union(); - object[] cases = (object[])FSharpUtils.Instance.GetUnionCases(null, t, null)!; + u.TagReader = (FSharpFunction)FSharpUtils.PreComputeUnionTagReader(null, t, null); + u.Cases = new List(); + + object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null); foreach (object unionCaseInfo in cases) { - UnionCase unionCase = new UnionCase( - (int)FSharpUtils.Instance.GetUnionCaseInfoTag(unionCaseInfo), - (string)FSharpUtils.Instance.GetUnionCaseInfoName(unionCaseInfo), - (PropertyInfo[])FSharpUtils.Instance.GetUnionCaseInfoFields(unionCaseInfo)!, - (FSharpFunction)FSharpUtils.Instance.PreComputeUnionReader(null, unionCaseInfo, null), - (FSharpFunction)FSharpUtils.Instance.PreComputeUnionConstructor(null, unionCaseInfo, null)); + UnionCase unionCase = new UnionCase(); + unionCase.Tag = (int)FSharpUtils.GetUnionCaseInfoTag(unionCaseInfo); + unionCase.Name = (string)FSharpUtils.GetUnionCaseInfoName(unionCaseInfo); + unionCase.Fields = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(unionCaseInfo); + unionCase.FieldReader = (FSharpFunction)FSharpUtils.PreComputeUnionReader(null, unionCaseInfo, null); + unionCase.Constructor = (FSharpFunction)FSharpUtils.PreComputeUnionConstructor(null, unionCaseInfo, null); u.Cases.Add(unionCase); } @@ -124,15 +112,9 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - if (value == null) - { - writer.WriteNull(); - return; - } - - DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; Type unionType = UnionTypeLookupCache.Get(value.GetType()); Union union = UnionCache.Get(unionType); @@ -145,7 +127,7 @@ namespace LC.Newtonsoft.Json.Converters writer.WriteValue(caseInfo.Name); if (caseInfo.Fields != null && caseInfo.Fields.Length > 0) { - object[] fields = (object[])caseInfo.FieldReader.Invoke(value)!; + object[] fields = (object[])caseInfo.FieldReader.Invoke(value); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName); writer.WriteStartArray(); @@ -166,30 +148,30 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } - UnionCase? caseInfo = null; - string? caseName = null; - JArray? fields = null; + UnionCase caseInfo = null; + string caseName = null; + JArray fields = null; // start object reader.ReadAndAssert(); while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadAndAssert(); Union union = UnionCache.Get(objectType); - caseName = reader.Value!.ToString(); + caseName = reader.Value.ToString(); caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName); @@ -221,7 +203,7 @@ namespace LC.Newtonsoft.Json.Converters throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName)); } - object?[] typedFieldValues = new object?[caseInfo.Fields.Length]; + object[] typedFieldValues = new object[caseInfo.Fields.Length]; if (caseInfo.Fields.Length > 0 && fields == null) { @@ -290,7 +272,7 @@ namespace LC.Newtonsoft.Json.Converters return false; } - return (bool)FSharpUtils.Instance.IsUnion(null, objectType, null); + return (bool)FSharpUtils.IsUnion(null, objectType, null); } } } diff --git a/Libs/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/Libs/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index f138b6e..7dbd21a 100644 --- a/Libs/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -28,7 +28,6 @@ using System; using LC.Newtonsoft.Json.Serialization; using System.Globalization; using LC.Newtonsoft.Json.Utilities; -using System.Diagnostics; namespace LC.Newtonsoft.Json.Converters { @@ -43,7 +42,7 @@ namespace LC.Newtonsoft.Json.Converters private const string TypePropertyName = "Type"; private const string ValuePropertyName = "Value"; - private static ReflectionObject? _reflectionObject; + private static ReflectionObject _reflectionObject; /// /// Writes the JSON representation of the object. @@ -51,23 +50,16 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - if (value == null) - { - writer.WriteNull(); - return; - } - EnsureReflectionObject(value.GetType()); - MiscellaneousUtils.Assert(_reflectionObject != null); - DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; - string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName)!; - object? keyValue = _reflectionObject.GetValue(value, ValuePropertyName); + string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName); + object keyValue = _reflectionObject.GetValue(value, ValuePropertyName); - Type? keyValueType = keyValue?.GetType(); + Type keyValueType = keyValue?.GetType(); writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName); @@ -79,7 +71,7 @@ namespace LC.Newtonsoft.Json.Converters if (keyValueType != null) { - if (JsonSerializerInternalWriter.TryConvertToString(keyValue!, keyValueType, out string? valueJson)) + if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out string valueJson)) { writer.WriteValue(valueJson); } @@ -100,7 +92,7 @@ namespace LC.Newtonsoft.Json.Converters { reader.ReadAndAssert(); - if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value?.ToString(), propertyName, StringComparison.OrdinalIgnoreCase)) + if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase)) { throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } @@ -114,20 +106,19 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { EnsureReflectionObject(objectType); - MiscellaneousUtils.Assert(_reflectionObject != null); - object entityKeyMember = _reflectionObject.Creator!(); + object entityKeyMember = _reflectionObject.Creator(); ReadAndAssertProperty(reader, KeyPropertyName); reader.ReadAndAssert(); - _reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value?.ToString()); + _reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value.ToString()); ReadAndAssertProperty(reader, TypePropertyName); reader.ReadAndAssert(); - string? type = reader.Value?.ToString(); + string type = reader.Value.ToString(); Type t = Type.GetType(type); diff --git a/Libs/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs b/Libs/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs index 8c8fef7..bb3cd36 100644 --- a/Libs/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs @@ -46,7 +46,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // can write is set to false } @@ -59,12 +59,12 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return ReadValue(reader); } - private object? ReadValue(JsonReader reader) + private object ReadValue(JsonReader reader) { if (!reader.MoveToContent()) { @@ -89,7 +89,7 @@ namespace LC.Newtonsoft.Json.Converters private object ReadList(JsonReader reader) { - IList list = new List(); + IList list = new List(); while (reader.Read()) { @@ -98,7 +98,7 @@ namespace LC.Newtonsoft.Json.Converters case JsonToken.Comment: break; default: - object? v = ReadValue(reader); + object v = ReadValue(reader); list.Add(v); break; @@ -112,21 +112,21 @@ namespace LC.Newtonsoft.Json.Converters private object ReadObject(JsonReader reader) { - IDictionary expandoObject = new ExpandoObject(); + IDictionary expandoObject = new ExpandoObject(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); } - object? v = ReadValue(reader); + object v = ReadValue(reader); expandoObject[propertyName] = v; break; diff --git a/Libs/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs b/Libs/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs index 92d1a5e..636a401 100644 --- a/Libs/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs @@ -37,8 +37,8 @@ namespace LC.Newtonsoft.Json.Converters private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; - private string? _dateTimeFormat; - private CultureInfo? _culture; + private string _dateTimeFormat; + private CultureInfo _culture; /// /// Gets or sets the date time styles used when converting a date to and from JSON. @@ -54,10 +54,10 @@ namespace LC.Newtonsoft.Json.Converters /// Gets or sets the date time format used when converting a date to and from JSON. /// /// The date time format used when converting a date to and from JSON. - public string? DateTimeFormat + public string DateTimeFormat { get => _dateTimeFormat ?? string.Empty; - set => _dateTimeFormat = (StringUtils.IsNullOrEmpty(value)) ? null : value; + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; } /// @@ -76,7 +76,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { string text; @@ -104,7 +104,7 @@ namespace LC.Newtonsoft.Json.Converters #endif else { - throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)!)); + throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value))); } writer.WriteValue(text); @@ -118,7 +118,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { bool nullable = ReflectionUtils.IsNullableType(objectType); if (reader.TokenType == JsonToken.Null) @@ -142,7 +142,7 @@ namespace LC.Newtonsoft.Json.Converters #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { - return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value!); + return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value); } // converter is expected to return a DateTime @@ -160,9 +160,9 @@ namespace LC.Newtonsoft.Json.Converters throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - string? dateText = reader.Value?.ToString(); + string dateText = reader.Value.ToString(); - if (StringUtils.IsNullOrEmpty(dateText) && nullable) + if (string.IsNullOrEmpty(dateText) && nullable) { return null; } @@ -170,7 +170,7 @@ namespace LC.Newtonsoft.Json.Converters #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { - if (!StringUtils.IsNullOrEmpty(_dateTimeFormat)) + if (!string.IsNullOrEmpty(_dateTimeFormat)) { return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); } @@ -181,7 +181,7 @@ namespace LC.Newtonsoft.Json.Converters } #endif - if (!StringUtils.IsNullOrEmpty(_dateTimeFormat)) + if (!string.IsNullOrEmpty(_dateTimeFormat)) { return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); } diff --git a/Libs/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/Libs/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index 0101751..2d20511 100644 --- a/Libs/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -40,7 +40,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { long ticks; @@ -74,7 +74,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing property value of the JSON that is being converted. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -86,12 +86,12 @@ namespace LC.Newtonsoft.Json.Converters return null; } - if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) + if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) { throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); } - if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string? errorMessage)) + if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string errorMessage)) { throw JsonSerializationException.Create(reader, errorMessage); } diff --git a/Libs/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Libs/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index 085af0c..07afb17 100644 --- a/Libs/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -56,17 +56,11 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - if (value == null) - { - writer.WriteNull(); - return; - } - ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType()); - DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName); @@ -84,7 +78,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -96,8 +90,8 @@ namespace LC.Newtonsoft.Json.Converters return null; } - object? key = null; - object? value = null; + object key = null; + object value = null; reader.ReadAndAssert(); @@ -111,7 +105,7 @@ namespace LC.Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadForTypeAndAssert(keyContract, false); @@ -132,7 +126,7 @@ namespace LC.Newtonsoft.Json.Converters reader.ReadAndAssert(); } - return reflectionObject.Creator!(key, value); + return reflectionObject.Creator(key, value); } /// diff --git a/Libs/Newtonsoft.Json/Converters/RegexConverter.cs b/Libs/Newtonsoft.Json/Converters/RegexConverter.cs index 69ea8d8..1bb8077 100644 --- a/Libs/Newtonsoft.Json/Converters/RegexConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/RegexConverter.cs @@ -47,7 +47,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -84,7 +84,7 @@ namespace LC.Newtonsoft.Json.Converters // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. - string? options = null; + string options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) { @@ -114,7 +114,7 @@ namespace LC.Newtonsoft.Json.Converters private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer) { - DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName); @@ -132,7 +132,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch (reader.TokenType) { @@ -149,7 +149,7 @@ namespace LC.Newtonsoft.Json.Converters private object ReadRegexString(JsonReader reader) { - string regexText = (string)reader.Value!; + string regexText = (string)reader.Value; if (regexText.Length > 0 && regexText[0] == '/') { @@ -171,7 +171,7 @@ namespace LC.Newtonsoft.Json.Converters private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer) { - string? pattern = null; + string pattern = null; RegexOptions? options = null; while (reader.Read()) @@ -179,7 +179,7 @@ namespace LC.Newtonsoft.Json.Converters switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); if (!reader.Read()) { @@ -188,7 +188,7 @@ namespace LC.Newtonsoft.Json.Converters if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase)) { - pattern = (string?)reader.Value; + pattern = (string)reader.Value; } else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase)) { diff --git a/Libs/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Libs/Newtonsoft.Json/Converters/StringEnumConverter.cs index b0b93a0..d0c34fe 100644 --- a/Libs/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -82,7 +82,7 @@ namespace LC.Newtonsoft.Json.Converters /// Gets or sets the naming strategy used to resolve how enum text is written. /// /// The naming strategy used to resolve how enum text is written. - public NamingStrategy? NamingStrategy { get; set; } + public NamingStrategy NamingStrategy { get; set; } /// /// Gets or sets a value indicating whether integer values are allowed when serializing and deserializing. @@ -175,7 +175,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -185,7 +185,7 @@ namespace LC.Newtonsoft.Json.Converters Enum e = (Enum)value; - if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string? enumName)) + if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string enumName)) { if (!AllowIntegerValues) { @@ -209,7 +209,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -228,14 +228,14 @@ namespace LC.Newtonsoft.Json.Converters { if (reader.TokenType == JsonToken.String) { - string? enumText = reader.Value?.ToString(); + string enumText = reader.Value.ToString(); - if (StringUtils.IsNullOrEmpty(enumText) && isNullable) + if (enumText == string.Empty && isNullable) { return null; } - return EnumUtils.ParseEnum(t, NamingStrategy, enumText!, !AllowIntegerValues); + return EnumUtils.ParseEnum(t, NamingStrategy, enumText, !AllowIntegerValues); } if (reader.TokenType == JsonToken.Integer) diff --git a/Libs/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs b/Libs/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs index d69d224..200d878 100644 --- a/Libs/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs @@ -42,7 +42,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { long seconds; @@ -77,7 +77,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing property value of the JSON that is being converted. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { bool nullable = ReflectionUtils.IsNullable(objectType); if (reader.TokenType == JsonToken.Null) @@ -94,11 +94,11 @@ namespace LC.Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Integer) { - seconds = (long)reader.Value!; + seconds = (long)reader.Value; } else if (reader.TokenType == JsonToken.String) { - if (!long.TryParse((string)reader.Value!, out seconds)) + if (!long.TryParse((string)reader.Value, out seconds)) { throw JsonSerializationException.Create(reader, "Cannot convert invalid value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); } diff --git a/Libs/Newtonsoft.Json/Converters/VersionConverter.cs b/Libs/Newtonsoft.Json/Converters/VersionConverter.cs index 449d950..f3d2fe7 100644 --- a/Libs/Newtonsoft.Json/Converters/VersionConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/VersionConverter.cs @@ -40,7 +40,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -64,7 +64,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing property value of the JSON that is being converted. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -76,7 +76,7 @@ namespace LC.Newtonsoft.Json.Converters { try { - Version v = new Version((string)reader.Value!); + Version v = new Version((string)reader.Value); return v; } catch (Exception ex) diff --git a/Libs/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Libs/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 1d8d320..ca9913f 100644 --- a/Libs/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Libs/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -38,7 +38,6 @@ using System.Xml.Linq; #endif using LC.Newtonsoft.Json.Utilities; using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; namespace LC.Newtonsoft.Json.Converters { @@ -54,44 +53,44 @@ namespace LC.Newtonsoft.Json.Converters _document = document; } - public IXmlNode CreateComment(string? data) + public IXmlNode CreateComment(string data) { return new XmlNodeWrapper(_document.CreateComment(data)); } - public IXmlNode CreateTextNode(string? text) + public IXmlNode CreateTextNode(string text) { return new XmlNodeWrapper(_document.CreateTextNode(text)); } - public IXmlNode CreateCDataSection(string? data) + public IXmlNode CreateCDataSection(string data) { return new XmlNodeWrapper(_document.CreateCDataSection(data)); } - public IXmlNode CreateWhitespace(string? text) + public IXmlNode CreateWhitespace(string text) { return new XmlNodeWrapper(_document.CreateWhitespace(text)); } - public IXmlNode CreateSignificantWhitespace(string? text) + public IXmlNode CreateSignificantWhitespace(string text) { return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); } - public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) + public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); } #if HAVE_XML_DOCUMENT_TYPE - public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) + public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null)); } #endif - public IXmlNode CreateProcessingInstruction(string target, string? data) + public IXmlNode CreateProcessingInstruction(string target, string data) { return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); } @@ -106,7 +105,7 @@ namespace LC.Newtonsoft.Json.Converters return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri)); } - public IXmlNode CreateAttribute(string name, string? value) + public IXmlNode CreateAttribute(string name, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name)); attribute.Value = value; @@ -114,7 +113,7 @@ namespace LC.Newtonsoft.Json.Converters return attribute; } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; @@ -122,7 +121,7 @@ namespace LC.Newtonsoft.Json.Converters return attribute; } - public IXmlElement? DocumentElement + public IXmlElement DocumentElement { get { @@ -150,7 +149,7 @@ namespace LC.Newtonsoft.Json.Converters { XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute; - _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode!); + _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode); } public string GetPrefixOfNamespace(string namespaceUri) @@ -205,26 +204,26 @@ namespace LC.Newtonsoft.Json.Converters public string InternalSubset => _documentType.InternalSubset; - public override string? LocalName => "DOCTYPE"; + public override string LocalName => "DOCTYPE"; } #endif internal class XmlNodeWrapper : IXmlNode { private readonly XmlNode _node; - private List? _childNodes; - private List? _attributes; + private List _childNodes; + private List _attributes; public XmlNodeWrapper(XmlNode node) { _node = node; } - public object? WrappedNode => _node; + public object WrappedNode => _node; public XmlNodeType NodeType => _node.NodeType; - public virtual string? LocalName => _node.LocalName; + public virtual string LocalName => _node.LocalName; public List ChildNodes { @@ -310,7 +309,7 @@ namespace LC.Newtonsoft.Json.Converters } } - public IXmlNode? ParentNode + public IXmlNode ParentNode { get { @@ -325,7 +324,7 @@ namespace LC.Newtonsoft.Json.Converters } } - public string? Value + public string Value { get => _node.Value; set => _node.Value = value; @@ -341,7 +340,7 @@ namespace LC.Newtonsoft.Json.Converters return newChild; } - public string? NamespaceUri => _node.NamespaceURI; + public string NamespaceUri => _node.NamespaceURI; } #endif #endregion @@ -349,22 +348,22 @@ namespace LC.Newtonsoft.Json.Converters #region Interfaces internal interface IXmlDocument : IXmlNode { - IXmlNode CreateComment(string? text); - IXmlNode CreateTextNode(string? text); - IXmlNode CreateCDataSection(string? data); - IXmlNode CreateWhitespace(string? text); - IXmlNode CreateSignificantWhitespace(string? text); - IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone); + IXmlNode CreateComment(string text); + IXmlNode CreateTextNode(string text); + IXmlNode CreateCDataSection(string data); + IXmlNode CreateWhitespace(string text); + IXmlNode CreateSignificantWhitespace(string text); + IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); #if HAVE_XML_DOCUMENT_TYPE - IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset); + IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset); #endif - IXmlNode CreateProcessingInstruction(string target, string? data); + IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); - IXmlNode CreateAttribute(string name, string? value); - IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value); + IXmlNode CreateAttribute(string name, string value); + IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); - IXmlElement? DocumentElement { get; } + IXmlElement DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode @@ -392,14 +391,14 @@ namespace LC.Newtonsoft.Json.Converters internal interface IXmlNode { XmlNodeType NodeType { get; } - string? LocalName { get; } + string LocalName { get; } List ChildNodes { get; } List Attributes { get; } - IXmlNode? ParentNode { get; } - string? Value { get; set; } + IXmlNode ParentNode { get; } + string Value { get; set; } IXmlNode AppendChild(IXmlNode newChild); - string? NamespaceUri { get; } - object? WrappedNode { get; } + string NamespaceUri { get; } + object WrappedNode { get; } } #endregion @@ -450,12 +449,12 @@ namespace LC.Newtonsoft.Json.Converters public string InternalSubset => _documentType.InternalSubset; - public override string? LocalName => "DOCTYPE"; + public override string LocalName => "DOCTYPE"; } internal class XDocumentWrapper : XContainerWrapper, IXmlDocument { - private XDocument Document => (XDocument)WrappedNode!; + private XDocument Document => (XDocument)WrappedNode; public XDocumentWrapper(XDocument document) : base(document) @@ -489,42 +488,42 @@ namespace LC.Newtonsoft.Json.Converters } } - public IXmlNode CreateComment(string? text) + public IXmlNode CreateComment(string text) { return new XObjectWrapper(new XComment(text)); } - public IXmlNode CreateTextNode(string? text) + public IXmlNode CreateTextNode(string text) { return new XObjectWrapper(new XText(text)); } - public IXmlNode CreateCDataSection(string? data) + public IXmlNode CreateCDataSection(string data) { return new XObjectWrapper(new XCData(data)); } - public IXmlNode CreateWhitespace(string? text) + public IXmlNode CreateWhitespace(string text) { return new XObjectWrapper(new XText(text)); } - public IXmlNode CreateSignificantWhitespace(string? text) + public IXmlNode CreateSignificantWhitespace(string text) { return new XObjectWrapper(new XText(text)); } - public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) + public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } - public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) + public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); } - public IXmlNode CreateProcessingInstruction(string target, string? data) + public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } @@ -540,18 +539,18 @@ namespace LC.Newtonsoft.Json.Converters return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } - public IXmlNode CreateAttribute(string name, string? value) + public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); } - public IXmlElement? DocumentElement + public IXmlElement DocumentElement { get { @@ -580,20 +579,20 @@ namespace LC.Newtonsoft.Json.Converters internal class XTextWrapper : XObjectWrapper { - private XText Text => (XText)WrappedNode!; + private XText Text => (XText)WrappedNode; public XTextWrapper(XText text) : base(text) { } - public override string? Value + public override string Value { get => Text.Value; set => Text.Value = value; } - public override IXmlNode? ParentNode + public override IXmlNode ParentNode { get { @@ -609,20 +608,20 @@ namespace LC.Newtonsoft.Json.Converters internal class XCommentWrapper : XObjectWrapper { - private XComment Text => (XComment)WrappedNode!; + private XComment Text => (XComment)WrappedNode; public XCommentWrapper(XComment text) : base(text) { } - public override string? Value + public override string Value { get => Text.Value; set => Text.Value = value; } - public override IXmlNode? ParentNode + public override IXmlNode ParentNode { get { @@ -638,16 +637,16 @@ namespace LC.Newtonsoft.Json.Converters internal class XProcessingInstructionWrapper : XObjectWrapper { - private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode!; + private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode; public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) : base(processingInstruction) { } - public override string? LocalName => ProcessingInstruction.Target; + public override string LocalName => ProcessingInstruction.Target; - public override string? Value + public override string Value { get => ProcessingInstruction.Data; set => ProcessingInstruction.Data = value; @@ -656,9 +655,9 @@ namespace LC.Newtonsoft.Json.Converters internal class XContainerWrapper : XObjectWrapper { - private List? _childNodes; + private List _childNodes; - private XContainer Container => (XContainer)WrappedNode!; + private XContainer Container => (XContainer)WrappedNode; public XContainerWrapper(XContainer container) : base(container) @@ -693,7 +692,7 @@ namespace LC.Newtonsoft.Json.Converters protected virtual bool HasChildNodes => Container.LastNode != null; - public override IXmlNode? ParentNode + public override IXmlNode ParentNode { get { @@ -762,26 +761,26 @@ namespace LC.Newtonsoft.Json.Converters internal class XObjectWrapper : IXmlNode { - private readonly XObject? _xmlObject; + private readonly XObject _xmlObject; - public XObjectWrapper(XObject? xmlObject) + public XObjectWrapper(XObject xmlObject) { _xmlObject = xmlObject; } - public object? WrappedNode => _xmlObject; + public object WrappedNode => _xmlObject; - public virtual XmlNodeType NodeType => _xmlObject?.NodeType ?? XmlNodeType.None; + public virtual XmlNodeType NodeType => _xmlObject.NodeType; - public virtual string? LocalName => null; + public virtual string LocalName => null; public virtual List ChildNodes => XmlNodeConverter.EmptyChildNodes; public virtual List Attributes => XmlNodeConverter.EmptyChildNodes; - public virtual IXmlNode? ParentNode => null; + public virtual IXmlNode ParentNode => null; - public virtual string? Value + public virtual string Value { get => null; set => throw new InvalidOperationException(); @@ -792,29 +791,29 @@ namespace LC.Newtonsoft.Json.Converters throw new InvalidOperationException(); } - public virtual string? NamespaceUri => null; + public virtual string NamespaceUri => null; } internal class XAttributeWrapper : XObjectWrapper { - private XAttribute Attribute => (XAttribute)WrappedNode!; + private XAttribute Attribute => (XAttribute)WrappedNode; public XAttributeWrapper(XAttribute attribute) : base(attribute) { } - public override string? Value + public override string Value { get => Attribute.Value; set => Attribute.Value = value; } - public override string? LocalName => Attribute.Name.LocalName; + public override string LocalName => Attribute.Name.LocalName; - public override string? NamespaceUri => Attribute.Name.NamespaceName; + public override string NamespaceUri => Attribute.Name.NamespaceName; - public override IXmlNode? ParentNode + public override IXmlNode ParentNode { get { @@ -830,9 +829,9 @@ namespace LC.Newtonsoft.Json.Converters internal class XElementWrapper : XContainerWrapper, IXmlElement { - private List? _attributes; + private List _attributes; - private XElement Element => (XElement)WrappedNode!; + private XElement Element => (XElement)WrappedNode; public XElementWrapper(XElement element) : base(element) @@ -854,7 +853,7 @@ namespace LC.Newtonsoft.Json.Converters // cache results to prevent multiple reads which kills perf in large documents if (_attributes == null) { - if (!Element.HasAttributes && !HasImplicitNamespaceAttribute(NamespaceUri!)) + if (!Element.HasAttributes && !HasImplicitNamespaceAttribute(NamespaceUri)) { _attributes = XmlNodeConverter.EmptyChildNodes; } @@ -868,7 +867,7 @@ namespace LC.Newtonsoft.Json.Converters // ensure elements created with a namespace but no namespace attribute are converted correctly // e.g. new XElement("{http://example.com}MyElement"); - string namespaceUri = NamespaceUri!; + string namespaceUri = NamespaceUri; if (HasImplicitNamespaceAttribute(namespaceUri)) { _attributes.Insert(0, new XAttributeWrapper(new XAttribute("xmlns", namespaceUri))); @@ -882,9 +881,9 @@ namespace LC.Newtonsoft.Json.Converters private bool HasImplicitNamespaceAttribute(string namespaceUri) { - if (!StringUtils.IsNullOrEmpty(namespaceUri) && namespaceUri != ParentNode?.NamespaceUri) + if (!string.IsNullOrEmpty(namespaceUri) && namespaceUri != ParentNode?.NamespaceUri) { - if (StringUtils.IsNullOrEmpty(GetPrefixOfNamespace(namespaceUri))) + if (string.IsNullOrEmpty(GetPrefixOfNamespace(namespaceUri))) { bool namespaceDeclared = false; @@ -892,7 +891,7 @@ namespace LC.Newtonsoft.Json.Converters { foreach (XAttribute attribute in Element.Attributes()) { - if (attribute.Name.LocalName == "xmlns" && StringUtils.IsNullOrEmpty(attribute.Name.NamespaceName) && attribute.Value == namespaceUri) + if (attribute.Name.LocalName == "xmlns" && string.IsNullOrEmpty(attribute.Name.NamespaceName) && attribute.Value == namespaceUri) { namespaceDeclared = true; } @@ -916,15 +915,15 @@ namespace LC.Newtonsoft.Json.Converters return result; } - public override string? Value + public override string Value { get => Element.Value; set => Element.Value = value; } - public override string? LocalName => Element.Name.LocalName; + public override string LocalName => Element.Name.LocalName; - public override string? NamespaceUri => Element.Name.NamespaceName; + public override string NamespaceUri => Element.Name.NamespaceName; public string GetPrefixOfNamespace(string namespaceUri) { @@ -955,7 +954,7 @@ namespace LC.Newtonsoft.Json.Converters /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produced multiple root elements. /// /// The name of the deserialized root element. - public string? DeserializeRootElementName { get; set; } + public string DeserializeRootElementName { get; set; } /// /// Gets or sets a value to indicate whether to write the Json.NET array attribute. @@ -986,7 +985,7 @@ namespace LC.Newtonsoft.Json.Converters /// The to write to. /// The calling serializer. /// The value. - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { @@ -1032,9 +1031,9 @@ namespace LC.Newtonsoft.Json.Converters private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { - List? parentElements = null; + List parentElements = null; - IXmlNode? parent = node; + IXmlNode parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) @@ -1068,11 +1067,11 @@ namespace LC.Newtonsoft.Json.Converters private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { - string? prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) + string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) ? null : manager.LookupPrefix(node.NamespaceUri); - if (!StringUtils.IsNullOrEmpty(prefix)) + if (!string.IsNullOrEmpty(prefix)) { return prefix + ":" + XmlConvert.DecodeName(node.LocalName); } @@ -1161,9 +1160,9 @@ namespace LC.Newtonsoft.Json.Converters // value of dictionary will be a single IXmlNode when there is one for a name, // or a List when there are multiple - Dictionary? nodesGroupedByName = null; + Dictionary nodesGroupedByName = null; - string? nodeName = null; + string nodeName = null; for (int i = 0; i < node.ChildNodes.Count; i++) { @@ -1209,7 +1208,7 @@ namespace LC.Newtonsoft.Json.Converters { if (!(value is List nodes)) { - nodes = new List {(IXmlNode)value!}; + nodes = new List {(IXmlNode)value}; nodesGroupedByName[currentNodeName] = nodes; } @@ -1220,7 +1219,7 @@ namespace LC.Newtonsoft.Json.Converters if (nodesGroupedByName == null) { - WriteGroupedNodes(writer, manager, writePropertyName, node.ChildNodes, nodeName!); + WriteGroupedNodes(writer, manager, writePropertyName, node.ChildNodes, nodeName); } else { @@ -1316,11 +1315,7 @@ namespace LC.Newtonsoft.Json.Converters string namespacePrefix = (attribute.LocalName != "xmlns") ? XmlConvert.DecodeName(attribute.LocalName) : string.Empty; - string? namespaceUri = attribute.Value; - if (namespaceUri == null) - { - throw new JsonSerializationException("Namespace attribute must have a value."); - } + string namespaceUri = attribute.Value; manager.AddNamespace(namespacePrefix, namespaceUri); } @@ -1405,17 +1400,17 @@ namespace LC.Newtonsoft.Json.Converters writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); - if (!StringUtils.IsNullOrEmpty(declaration.Version)) + if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } - if (!StringUtils.IsNullOrEmpty(declaration.Encoding)) + if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } - if (!StringUtils.IsNullOrEmpty(declaration.Standalone)) + if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); @@ -1428,22 +1423,22 @@ namespace LC.Newtonsoft.Json.Converters writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); - if (!StringUtils.IsNullOrEmpty(documentType.Name)) + if (!string.IsNullOrEmpty(documentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(documentType.Name); } - if (!StringUtils.IsNullOrEmpty(documentType.Public)) + if (!string.IsNullOrEmpty(documentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(documentType.Public); } - if (!StringUtils.IsNullOrEmpty(documentType.System)) + if (!string.IsNullOrEmpty(documentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(documentType.System); } - if (!StringUtils.IsNullOrEmpty(documentType.InternalSubset)) + if (!string.IsNullOrEmpty(documentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(documentType.InternalSubset); @@ -1478,7 +1473,7 @@ namespace LC.Newtonsoft.Json.Converters /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch (reader.TokenType) { @@ -1491,8 +1486,8 @@ namespace LC.Newtonsoft.Json.Converters } XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); - IXmlDocument? document = null; - IXmlNode? rootNode = null; + IXmlDocument document = null; + IXmlNode rootNode = null; #if HAVE_XLINQ if (typeof(XObject).IsAssignableFrom(objectType)) @@ -1537,7 +1532,7 @@ namespace LC.Newtonsoft.Json.Converters throw JsonSerializationException.Create(reader, "Unexpected type when converting XML: " + objectType); } - if (!StringUtils.IsNullOrEmpty(DeserializeRootElementName)) + if (!string.IsNullOrEmpty(DeserializeRootElementName)) { ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); } @@ -1550,7 +1545,7 @@ namespace LC.Newtonsoft.Json.Converters #if HAVE_XLINQ if (objectType == typeof(XElement)) { - XElement element = (XElement)document.DocumentElement!.WrappedNode!; + XElement element = (XElement)document.DocumentElement.WrappedNode; element.Remove(); return element; @@ -1559,7 +1554,7 @@ namespace LC.Newtonsoft.Json.Converters #if HAVE_XML_DOCUMENT if (objectType == typeof(XmlElement)) { - return document.DocumentElement!.WrappedNode; + return document.DocumentElement.WrappedNode; } #endif @@ -1586,7 +1581,7 @@ namespace LC.Newtonsoft.Json.Converters return; default: // processing instructions and the xml declaration start with ? - if (!StringUtils.IsNullOrEmpty(propertyName) && propertyName[0] == '?') + if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { CreateInstruction(reader, document, currentNode, propertyName); return; @@ -1616,13 +1611,13 @@ namespace LC.Newtonsoft.Json.Converters private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { - if (StringUtils.IsNullOrEmpty(propertyName)) + if (string.IsNullOrEmpty(propertyName)) { throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML."); } - Dictionary? attributeNameValues = null; - string? elementPrefix = null; + Dictionary attributeNameValues = null; + string elementPrefix = null; if (!EncodeSpecialCharacters) { @@ -1634,7 +1629,7 @@ namespace LC.Newtonsoft.Json.Converters if (propertyName.StartsWith('@')) { string attributeName = propertyName.Substring(1); - string? attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); + string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); AddAttribute(reader, document, currentNode, propertyName, attributeName, manager, attributePrefix); return; @@ -1671,7 +1666,7 @@ namespace LC.Newtonsoft.Json.Converters CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues); } - private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string? elementPrefix, Dictionary? attributeNameValues) + private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary attributeNameValues) { IXmlElement element = CreateElement(elementName, document, elementPrefix, manager); @@ -1680,12 +1675,12 @@ namespace LC.Newtonsoft.Json.Converters if (attributeNameValues != null) { // add attributes to newly created element - foreach (KeyValuePair nameValue in attributeNameValues) + foreach (KeyValuePair nameValue in attributeNameValues) { string encodedName = XmlConvert.EncodeName(nameValue.Key); - string? attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); + string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); - IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value); + IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value); element.SetAttributeNode(attribute); } @@ -1699,7 +1694,7 @@ namespace LC.Newtonsoft.Json.Converters case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: - string? text = ConvertTokenToXmlValue(reader); + string text = ConvertTokenToXmlValue(reader); if (text != null) { element.AppendChild(document.CreateTextNode(text)); @@ -1723,7 +1718,7 @@ namespace LC.Newtonsoft.Json.Converters } } - private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, string attributeName, XmlNamespaceManager manager, string? attributePrefix) + private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, string attributeName, XmlNamespaceManager manager, string attributePrefix) { if (currentNode.NodeType == XmlNodeType.Document) { @@ -1731,16 +1726,16 @@ namespace LC.Newtonsoft.Json.Converters } string encodedName = XmlConvert.EncodeName(attributeName); - string? attributeValue = ConvertTokenToXmlValue(reader); + string attributeValue = ConvertTokenToXmlValue(reader); - IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) + IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(encodedName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } - private static string? ConvertTokenToXmlValue(JsonReader reader) + private static string ConvertTokenToXmlValue(JsonReader reader) { switch (reader.TokenType) { @@ -1787,7 +1782,7 @@ namespace LC.Newtonsoft.Json.Converters #endif } case JsonToken.Bytes: - return Convert.ToBase64String((byte[])reader.Value!); + return Convert.ToBase64String((byte[])reader.Value); case JsonToken.Null: return null; default: @@ -1797,7 +1792,7 @@ namespace LC.Newtonsoft.Json.Converters private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) { - string? elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); + string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); @@ -1863,9 +1858,9 @@ namespace LC.Newtonsoft.Json.Converters return true; } - private Dictionary? ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) + private Dictionary ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { - Dictionary? attributeNameValues = null; + Dictionary attributeNameValues = null; bool finished = false; // read properties until first non-attribute is encountered @@ -1874,19 +1869,19 @@ namespace LC.Newtonsoft.Json.Converters switch (reader.TokenType) { case JsonToken.PropertyName: - string attributeName = reader.Value!.ToString(); + string attributeName = reader.Value.ToString(); - if (!StringUtils.IsNullOrEmpty(attributeName)) + if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; - string? attributeValue; + string attributeValue; switch (firstChar) { case '@': if (attributeNameValues == null) { - attributeNameValues = new Dictionary(); + attributeNameValues = new Dictionary(); } attributeName = attributeName.Substring(1); @@ -1894,7 +1889,7 @@ namespace LC.Newtonsoft.Json.Converters attributeValue = ConvertTokenToXmlValue(reader); attributeNameValues.Add(attributeName, attributeValue); - if (IsNamespaceAttribute(attributeName, out string? namespacePrefix)) + if (IsNamespaceAttribute(attributeName, out string namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } @@ -1914,7 +1909,7 @@ namespace LC.Newtonsoft.Json.Converters { if (attributeNameValues == null) { - attributeNameValues = new Dictionary(); + attributeNameValues = new Dictionary(); } // ensure that the prefix used is free @@ -1946,7 +1941,7 @@ namespace LC.Newtonsoft.Json.Converters if (attributeNameValues == null) { - attributeNameValues = new Dictionary(); + attributeNameValues = new Dictionary(); } attributeValue = reader.Value?.ToString(); @@ -1984,12 +1979,12 @@ namespace LC.Newtonsoft.Json.Converters { if (propertyName == DeclarationName) { - string? version = null; - string? encoding = null; - string? standalone = null; + string version = null; + string encoding = null; + string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { - switch (reader.Value?.ToString()) + switch (reader.Value.ToString()) { case "@version": reader.ReadAndAssert(); @@ -2021,13 +2016,13 @@ namespace LC.Newtonsoft.Json.Converters #if HAVE_XML_DOCUMENT_TYPE private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode) { - string? name = null; - string? publicId = null; - string? systemId = null; - string? internalSubset = null; + string name = null; + string publicId = null; + string systemId = null; + string internalSubset = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { - switch (reader.Value?.ToString()) + switch (reader.Value.ToString()) { case "@name": reader.ReadAndAssert(); @@ -2055,12 +2050,12 @@ namespace LC.Newtonsoft.Json.Converters } #endif - private IXmlElement CreateElement(string elementName, IXmlDocument document, string? elementPrefix, XmlNamespaceManager manager) + private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string encodeName = EncodeSpecialCharacters ? XmlConvert.EncodeLocalName(elementName) : XmlConvert.EncodeName(elementName); - string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); - IXmlElement element = (!StringUtils.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); + IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); return element; } @@ -2077,7 +2072,7 @@ namespace LC.Newtonsoft.Json.Converters throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifying a DeserializeRootElementName."); } - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); reader.ReadAndAssert(); if (reader.TokenType == JsonToken.StartArray) @@ -2091,8 +2086,8 @@ namespace LC.Newtonsoft.Json.Converters if (count == 1 && WriteArrayAttribute) { - MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string? elementPrefix, out string localName); - string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string elementPrefix, out string localName); + string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); foreach (IXmlNode childNode in currentNode.ChildNodes) { @@ -2110,7 +2105,7 @@ namespace LC.Newtonsoft.Json.Converters } continue; case JsonToken.StartConstructor: - string constructorName = reader.Value!.ToString(); + string constructorName = reader.Value.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { @@ -2118,7 +2113,7 @@ namespace LC.Newtonsoft.Json.Converters } break; case JsonToken.Comment: - currentNode.AppendChild(document.CreateComment((string)reader.Value!)); + currentNode.AppendChild(document.CreateComment((string)reader.Value)); break; case JsonToken.EndObject: case JsonToken.EndArray: @@ -2136,7 +2131,7 @@ namespace LC.Newtonsoft.Json.Converters /// Attribute name to test. /// The attribute name prefix if it has one, otherwise an empty string. /// true if attribute name is for a namespace attribute, otherwise false. - private bool IsNamespaceAttribute(string attributeName, [NotNullWhen(true)]out string? prefix) + private bool IsNamespaceAttribute(string attributeName, out string prefix) { if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) { diff --git a/Libs/Newtonsoft.Json/DateParseHandling.cs b/Libs/Newtonsoft.Json/DateParseHandling.cs index 10bd229..808e6c2 100644 --- a/Libs/Newtonsoft.Json/DateParseHandling.cs +++ b/Libs/Newtonsoft.Json/DateParseHandling.cs @@ -36,14 +36,14 @@ namespace LC.Newtonsoft.Json None = 0, /// - /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . + /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . /// DateTime = 1, #if HAVE_DATE_TIME_OFFSET /// - /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . + /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . /// DateTimeOffset = 2 #endif } -} +} \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/DefaultJsonNameTable.cs b/Libs/Newtonsoft.Json/DefaultJsonNameTable.cs index 9d56e0d..16afe1b 100644 --- a/Libs/Newtonsoft.Json/DefaultJsonNameTable.cs +++ b/Libs/Newtonsoft.Json/DefaultJsonNameTable.cs @@ -59,7 +59,7 @@ namespace LC.Newtonsoft.Json /// The zero-based index into the array specifying the first character of the name. /// The number of characters in the name. /// A string containing the same characters as the specified range of characters in the given array. - public override string? Get(char[] key, int start, int length) + public override string Get(char[] key, int start, int length) { if (length == 0) { diff --git a/Libs/Newtonsoft.Json/IArrayPool.cs b/Libs/Newtonsoft.Json/IArrayPool.cs index b641274..6ab15d8 100644 --- a/Libs/Newtonsoft.Json/IArrayPool.cs +++ b/Libs/Newtonsoft.Json/IArrayPool.cs @@ -17,6 +17,6 @@ /// Return an array to the pool. /// /// The array that is being returned. - void Return(T[]? array); + void Return(T[] array); } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/JsonContainerAttribute.cs b/Libs/Newtonsoft.Json/JsonContainerAttribute.cs index e4e29d4..8aec715 100644 --- a/Libs/Newtonsoft.Json/JsonContainerAttribute.cs +++ b/Libs/Newtonsoft.Json/JsonContainerAttribute.cs @@ -38,25 +38,25 @@ namespace LC.Newtonsoft.Json /// Gets or sets the id. /// /// The id. - public string? Id { get; set; } + public string Id { get; set; } /// /// Gets or sets the title. /// /// The title. - public string? Title { get; set; } + public string Title { get; set; } /// /// Gets or sets the description. /// /// The description. - public string? Description { get; set; } + public string Description { get; set; } /// /// Gets or sets the collection's items converter. /// /// The collection's items converter. - public Type? ItemConverterType { get; set; } + public Type ItemConverterType { get; set; } /// /// The parameter list to use when constructing the described by . @@ -69,13 +69,13 @@ namespace LC.Newtonsoft.Json /// [JsonContainer(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// /// - public object[]? ItemConverterParameters { get; set; } + public object[] ItemConverterParameters { get; set; } /// /// Gets or sets the of the . /// /// The of the . - public Type? NamingStrategyType + public Type NamingStrategyType { get => _namingStrategyType; set @@ -96,7 +96,7 @@ namespace LC.Newtonsoft.Json /// [JsonContainer(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })] /// /// - public object[]? NamingStrategyParameters + public object[] NamingStrategyParameters { get => _namingStrategyParameters; set @@ -106,7 +106,7 @@ namespace LC.Newtonsoft.Json } } - internal NamingStrategy? NamingStrategyInstance { get; set; } + internal NamingStrategy NamingStrategyInstance { get; set; } // yuck. can't set nullable properties on an attribute in C# // have to use this approach to get an unset default state @@ -114,8 +114,8 @@ namespace LC.Newtonsoft.Json internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; - private Type? _namingStrategyType; - private object[]? _namingStrategyParameters; + private Type _namingStrategyType; + private object[] _namingStrategyParameters; /// /// Gets or sets a value that indicates whether to preserve object references. diff --git a/Libs/Newtonsoft.Json/JsonConvert.cs b/Libs/Newtonsoft.Json/JsonConvert.cs index 639a169..a7999aa 100644 --- a/Libs/Newtonsoft.Json/JsonConvert.cs +++ b/Libs/Newtonsoft.Json/JsonConvert.cs @@ -36,10 +36,9 @@ using LC.Newtonsoft.Json.Converters; using LC.Newtonsoft.Json.Serialization; using System.Text; using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if HAVE_XLINQ using System.Xml.Linq; + #endif namespace LC.Newtonsoft.Json @@ -59,7 +58,7 @@ namespace LC.Newtonsoft.Json /// To serialize without using any default settings create a with /// . /// - public static Func? DefaultSettings { get; set; } + public static Func DefaultSettings { get; set; } /// /// Represents JavaScript's boolean value true as a string. This field is read-only. @@ -396,7 +395,7 @@ namespace LC.Newtonsoft.Json /// /// The value to convert. /// A JSON string representation of the . - public static string ToString(Uri? value) + public static string ToString(Uri value) { if (value == null) { @@ -416,7 +415,7 @@ namespace LC.Newtonsoft.Json /// /// The value to convert. /// A JSON string representation of the . - public static string ToString(string? value) + public static string ToString(string value) { return ToString(value, '"'); } @@ -427,7 +426,7 @@ namespace LC.Newtonsoft.Json /// The value to convert. /// The string delimiter character. /// A JSON string representation of the . - public static string ToString(string? value, char delimiter) + public static string ToString(string value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } @@ -439,7 +438,7 @@ namespace LC.Newtonsoft.Json /// The string delimiter character. /// The string escape handling. /// A JSON string representation of the . - public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) + public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { @@ -454,7 +453,7 @@ namespace LC.Newtonsoft.Json /// /// The value to convert. /// A JSON string representation of the . - public static string ToString(object? value) + public static string ToString(object value) { if (value == null) { @@ -525,9 +524,9 @@ namespace LC.Newtonsoft.Json /// The object to serialize. /// A JSON string representation of the object. [DebuggerStepThrough] - public static string SerializeObject(object? value) + public static string SerializeObject(object value) { - return SerializeObject(value, null, (JsonSerializerSettings?)null); + return SerializeObject(value, null, (JsonSerializerSettings)null); } /// @@ -539,9 +538,9 @@ namespace LC.Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object? value, Formatting formatting) + public static string SerializeObject(object value, Formatting formatting) { - return SerializeObject(value, formatting, (JsonSerializerSettings?)null); + return SerializeObject(value, formatting, (JsonSerializerSettings)null); } /// @@ -551,9 +550,9 @@ namespace LC.Newtonsoft.Json /// A collection of converters used while serializing. /// A JSON string representation of the object. [DebuggerStepThrough] - public static string SerializeObject(object? value, params JsonConverter[] converters) + public static string SerializeObject(object value, params JsonConverter[] converters) { - JsonSerializerSettings? settings = (converters != null && converters.Length > 0) + JsonSerializerSettings settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings { Converters = converters } : null; @@ -568,9 +567,9 @@ namespace LC.Newtonsoft.Json /// A collection of converters used while serializing. /// A JSON string representation of the object. [DebuggerStepThrough] - public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) + public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) { - JsonSerializerSettings? settings = (converters != null && converters.Length > 0) + JsonSerializerSettings settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings { Converters = converters } : null; @@ -587,7 +586,7 @@ namespace LC.Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object? value, JsonSerializerSettings? settings) + public static string SerializeObject(object value, JsonSerializerSettings settings) { return SerializeObject(value, null, settings); } @@ -607,7 +606,7 @@ namespace LC.Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) + public static string SerializeObject(object value, Type type, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -625,7 +624,7 @@ namespace LC.Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) + public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) { return SerializeObject(value, null, formatting, settings); } @@ -646,7 +645,7 @@ namespace LC.Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) + public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; @@ -654,7 +653,7 @@ namespace LC.Newtonsoft.Json return SerializeObjectInternal(value, type, jsonSerializer); } - private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) + private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer) { StringBuilder sb = new StringBuilder(256); StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); @@ -676,9 +675,9 @@ namespace LC.Newtonsoft.Json /// The JSON to deserialize. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object? DeserializeObject(string value) + public static object DeserializeObject(string value) { - return DeserializeObject(value, null, (JsonSerializerSettings?)null); + return DeserializeObject(value, null, (JsonSerializerSettings)null); } /// @@ -691,7 +690,7 @@ namespace LC.Newtonsoft.Json /// /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object? DeserializeObject(string value, JsonSerializerSettings settings) + public static object DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } @@ -703,9 +702,9 @@ namespace LC.Newtonsoft.Json /// The of object being deserialized. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object? DeserializeObject(string value, Type type) + public static object DeserializeObject(string value, Type type) { - return DeserializeObject(value, type, (JsonSerializerSettings?)null); + return DeserializeObject(value, type, (JsonSerializerSettings)null); } /// @@ -715,9 +714,9 @@ namespace LC.Newtonsoft.Json /// The JSON to deserialize. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static T? DeserializeObject(string value) + public static T DeserializeObject(string value) { - return DeserializeObject(value, (JsonSerializerSettings?)null); + return DeserializeObject(value, (JsonSerializerSettings)null); } /// @@ -732,7 +731,7 @@ namespace LC.Newtonsoft.Json /// The anonymous type object. /// The deserialized anonymous type from the JSON string. [DebuggerStepThrough] - public static T? DeserializeAnonymousType(string value, T anonymousTypeObject) + public static T DeserializeAnonymousType(string value, T anonymousTypeObject) { return DeserializeObject(value); } @@ -753,7 +752,7 @@ namespace LC.Newtonsoft.Json /// /// The deserialized anonymous type from the JSON string. [DebuggerStepThrough] - public static T? DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings) + public static T DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject(value, settings); } @@ -766,9 +765,9 @@ namespace LC.Newtonsoft.Json /// Converters to use while deserializing. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static T? DeserializeObject(string value, params JsonConverter[] converters) + public static T DeserializeObject(string value, params JsonConverter[] converters) { - return (T?)DeserializeObject(value, typeof(T), converters); + return (T)DeserializeObject(value, typeof(T), converters); } /// @@ -782,9 +781,9 @@ namespace LC.Newtonsoft.Json /// /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static T? DeserializeObject(string value, JsonSerializerSettings? settings) + public static T DeserializeObject(string value, JsonSerializerSettings settings) { - return (T?)DeserializeObject(value, typeof(T), settings); + return (T)DeserializeObject(value, typeof(T), settings); } /// @@ -795,9 +794,9 @@ namespace LC.Newtonsoft.Json /// Converters to use while deserializing. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) + public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) { - JsonSerializerSettings? settings = (converters != null && converters.Length > 0) + JsonSerializerSettings settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings { Converters = converters } : null; @@ -814,7 +813,7 @@ namespace LC.Newtonsoft.Json /// If this is null, default serialization settings will be used. /// /// The deserialized object from the JSON string. - public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) + public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -854,7 +853,7 @@ namespace LC.Newtonsoft.Json /// The used to deserialize the object. /// If this is null, default serialization settings will be used. /// - public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) + public static void PopulateObject(string value, object target, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -883,7 +882,7 @@ namespace LC.Newtonsoft.Json /// /// The node to serialize. /// A JSON string of the . - public static string SerializeXmlNode(XmlNode? node) + public static string SerializeXmlNode(XmlNode node) { return SerializeXmlNode(node, Formatting.None); } @@ -894,7 +893,7 @@ namespace LC.Newtonsoft.Json /// The node to serialize. /// Indicates how the output should be formatted. /// A JSON string of the . - public static string SerializeXmlNode(XmlNode? node, Formatting formatting) + public static string SerializeXmlNode(XmlNode node, Formatting formatting) { XmlNodeConverter converter = new XmlNodeConverter(); @@ -908,7 +907,7 @@ namespace LC.Newtonsoft.Json /// Indicates how the output should be formatted. /// Omits writing the root object. /// A JSON string of the . - public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) + public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; @@ -920,7 +919,7 @@ namespace LC.Newtonsoft.Json /// /// The JSON string. /// The deserialized . - public static XmlDocument? DeserializeXmlNode(string value) + public static XmlDocument DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } @@ -931,7 +930,7 @@ namespace LC.Newtonsoft.Json /// The JSON string. /// The name of the root element to append when deserializing. /// The deserialized . - public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) + public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, false); } @@ -947,7 +946,7 @@ namespace LC.Newtonsoft.Json /// This attribute helps preserve arrays when converting the written XML back to JSON. /// /// The deserialized . - public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) + public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false); } @@ -969,14 +968,14 @@ namespace LC.Newtonsoft.Json /// as part of the XML element name. /// /// The deserialized . - public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) + public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter converter = new XmlNodeConverter(); converter.DeserializeRootElementName = deserializeRootElementName; converter.WriteArrayAttribute = writeArrayAttribute; converter.EncodeSpecialCharacters = encodeSpecialCharacters; - return (XmlDocument?)DeserializeObject(value, typeof(XmlDocument), converter); + return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter); } #endif @@ -986,7 +985,7 @@ namespace LC.Newtonsoft.Json /// /// The node to convert to JSON. /// A JSON string of the . - public static string SerializeXNode(XObject? node) + public static string SerializeXNode(XObject node) { return SerializeXNode(node, Formatting.None); } @@ -997,7 +996,7 @@ namespace LC.Newtonsoft.Json /// The node to convert to JSON. /// Indicates how the output should be formatted. /// A JSON string of the . - public static string SerializeXNode(XObject? node, Formatting formatting) + public static string SerializeXNode(XObject node, Formatting formatting) { return SerializeXNode(node, formatting, false); } @@ -1009,7 +1008,7 @@ namespace LC.Newtonsoft.Json /// Indicates how the output should be formatted. /// Omits writing the root object. /// A JSON string of the . - public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) + public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; @@ -1021,7 +1020,7 @@ namespace LC.Newtonsoft.Json /// /// The JSON string. /// The deserialized . - public static XDocument? DeserializeXNode(string value) + public static XDocument DeserializeXNode(string value) { return DeserializeXNode(value, null); } @@ -1032,7 +1031,7 @@ namespace LC.Newtonsoft.Json /// The JSON string. /// The name of the root element to append when deserializing. /// The deserialized . - public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) + public static XDocument DeserializeXNode(string value, string deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, false); } @@ -1048,7 +1047,7 @@ namespace LC.Newtonsoft.Json /// This attribute helps preserve arrays when converting the written XML back to JSON. /// /// The deserialized . - public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) + public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false); } @@ -1070,14 +1069,14 @@ namespace LC.Newtonsoft.Json /// as part of the XML element name. /// /// The deserialized . - public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) + public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter converter = new XmlNodeConverter(); converter.DeserializeRootElementName = deserializeRootElementName; converter.WriteArrayAttribute = writeArrayAttribute; converter.EncodeSpecialCharacters = encodeSpecialCharacters; - return (XDocument?)DeserializeObject(value, typeof(XDocument), converter); + return (XDocument)DeserializeObject(value, typeof(XDocument), converter); } #endif #endregion diff --git a/Libs/Newtonsoft.Json/JsonConverter.cs b/Libs/Newtonsoft.Json/JsonConverter.cs index 9f5ff5d..7977bc5 100644 --- a/Libs/Newtonsoft.Json/JsonConverter.cs +++ b/Libs/Newtonsoft.Json/JsonConverter.cs @@ -26,8 +26,6 @@ using System; using LC.Newtonsoft.Json.Utilities; using System.Globalization; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; namespace LC.Newtonsoft.Json { @@ -42,7 +40,7 @@ namespace LC.Newtonsoft.Json /// The to write to. /// The value. /// The calling serializer. - public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); + public abstract void WriteJson(JsonWriter writer, object value, JsonSerializer serializer); /// /// Reads the JSON representation of the object. @@ -52,7 +50,7 @@ namespace LC.Newtonsoft.Json /// The existing value of object being read. /// The calling serializer. /// The object value. - public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); + public abstract object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer); /// /// Determines whether this instance can convert the specified object type. @@ -88,13 +86,13 @@ namespace LC.Newtonsoft.Json /// The to write to. /// The value. /// The calling serializer. - public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + public sealed override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (!(value != null ? value is T : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } - WriteJson(writer, (T?)value, serializer); + WriteJson(writer, (T)value, serializer); } /// @@ -103,7 +101,7 @@ namespace LC.Newtonsoft.Json /// The to write to. /// The value. /// The calling serializer. - public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); + public abstract void WriteJson(JsonWriter writer, T value, JsonSerializer serializer); /// /// Reads the JSON representation of the object. @@ -113,14 +111,14 @@ namespace LC.Newtonsoft.Json /// The existing value of object being read. /// The calling serializer. /// The object value. - public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + public sealed override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { bool existingIsNull = existingValue == null; if (!(existingIsNull || existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } - return ReadJson(reader, objectType, existingIsNull ? default : (T?)existingValue, !existingIsNull, serializer); + return ReadJson(reader, objectType, existingIsNull ? default : (T)existingValue, !existingIsNull, serializer); } /// @@ -132,7 +130,7 @@ namespace LC.Newtonsoft.Json /// The existing value has a value. /// The calling serializer. /// The object value. - public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); + public abstract T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer); /// /// Determines whether this instance can convert the specified object type. diff --git a/Libs/Newtonsoft.Json/JsonConverterAttribute.cs b/Libs/Newtonsoft.Json/JsonConverterAttribute.cs index 51d12bd..4c6ee9d 100644 --- a/Libs/Newtonsoft.Json/JsonConverterAttribute.cs +++ b/Libs/Newtonsoft.Json/JsonConverterAttribute.cs @@ -47,7 +47,7 @@ namespace LC.Newtonsoft.Json /// The parameter list to use when constructing the described by . /// If null, the default constructor is used. /// - public object[]? ConverterParameters { get; } + public object[] ConverterParameters { get; } /// /// Initializes a new instance of the class. diff --git a/Libs/Newtonsoft.Json/JsonException.cs b/Libs/Newtonsoft.Json/JsonException.cs index 9907d05..0e9edb3 100644 --- a/Libs/Newtonsoft.Json/JsonException.cs +++ b/Libs/Newtonsoft.Json/JsonException.cs @@ -63,7 +63,7 @@ namespace LC.Newtonsoft.Json /// /// The error message that explains the reason for the exception. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonException(string message, Exception? innerException) + public JsonException(string message, Exception innerException) : base(message, innerException) { } diff --git a/Libs/Newtonsoft.Json/JsonNameTable.cs b/Libs/Newtonsoft.Json/JsonNameTable.cs index 01c5ceb..95ef50f 100644 --- a/Libs/Newtonsoft.Json/JsonNameTable.cs +++ b/Libs/Newtonsoft.Json/JsonNameTable.cs @@ -12,6 +12,6 @@ /// The zero-based index into the array specifying the first character of the name. /// The number of characters in the name. /// A string containing the same characters as the specified range of characters in the given array. - public abstract string? Get(char[] key, int start, int length); + public abstract string Get(char[] key, int start, int length); } } diff --git a/Libs/Newtonsoft.Json/JsonPosition.cs b/Libs/Newtonsoft.Json/JsonPosition.cs index ba9ed25..827a2be 100644 --- a/Libs/Newtonsoft.Json/JsonPosition.cs +++ b/Libs/Newtonsoft.Json/JsonPosition.cs @@ -46,7 +46,7 @@ namespace LC.Newtonsoft.Json internal JsonContainerType Type; internal int Position; - internal string? PropertyName; + internal string PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) @@ -62,7 +62,7 @@ namespace LC.Newtonsoft.Json switch (Type) { case JsonContainerType.Object: - return PropertyName!.Length + 5; + return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; @@ -71,12 +71,12 @@ namespace LC.Newtonsoft.Json } } - internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) + internal void WriteTo(StringBuilder sb, ref StringWriter writer, ref char[] buffer) { switch (Type) { case JsonContainerType.Object: - string propertyName = PropertyName!; + string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append(@"['"); @@ -130,8 +130,8 @@ namespace LC.Newtonsoft.Json } StringBuilder sb = new StringBuilder(capacity); - StringWriter? writer = null; - char[]? buffer = null; + StringWriter writer = null; + char[] buffer = null; if (positions != null) { foreach (JsonPosition state in positions) @@ -147,7 +147,7 @@ namespace LC.Newtonsoft.Json return sb.ToString(); } - internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) + internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message) { // don't add a fullstop and space when message ends with a new line if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) diff --git a/Libs/Newtonsoft.Json/JsonPropertyAttribute.cs b/Libs/Newtonsoft.Json/JsonPropertyAttribute.cs index 4faf778..5dec153 100644 --- a/Libs/Newtonsoft.Json/JsonPropertyAttribute.cs +++ b/Libs/Newtonsoft.Json/JsonPropertyAttribute.cs @@ -52,7 +52,7 @@ namespace LC.Newtonsoft.Json /// Gets or sets the type used when serializing the property's collection items. /// /// The collection's items type. - public Type? ItemConverterType { get; set; } + public Type ItemConverterType { get; set; } /// /// The parameter list to use when constructing the described by . @@ -65,13 +65,13 @@ namespace LC.Newtonsoft.Json /// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// /// - public object[]? ItemConverterParameters { get; set; } + public object[] ItemConverterParameters { get; set; } /// /// Gets or sets the of the . /// /// The of the . - public Type? NamingStrategyType { get; set; } + public Type NamingStrategyType { get; set; } /// /// The parameter list to use when constructing the described by . @@ -84,7 +84,7 @@ namespace LC.Newtonsoft.Json /// [JsonProperty(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })] /// /// - public object[]? NamingStrategyParameters { get; set; } + public object[] NamingStrategyParameters { get; set; } /// /// Gets or sets the null value handling used when serializing this property. @@ -172,7 +172,7 @@ namespace LC.Newtonsoft.Json /// Gets or sets the name of the property. /// /// The name of the property. - public string? PropertyName { get; set; } + public string PropertyName { get; set; } /// /// Gets or sets the reference loop handling used when serializing the property's collection items. diff --git a/Libs/Newtonsoft.Json/JsonReader.Async.cs b/Libs/Newtonsoft.Json/JsonReader.Async.cs index a97ec69..453e200 100644 --- a/Libs/Newtonsoft.Json/JsonReader.Async.cs +++ b/Libs/Newtonsoft.Json/JsonReader.Async.cs @@ -101,12 +101,12 @@ namespace LC.Newtonsoft.Json /// property returns the []. This result will be null at the end of an array. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task ReadAsBytesAsync(CancellationToken cancellationToken = default) + public virtual Task ReadAsBytesAsync(CancellationToken cancellationToken = default) { - return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsBytes()); + return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsBytes()); } - internal async Task ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) + internal async Task ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List buffer = new List(); @@ -199,9 +199,9 @@ namespace LC.Newtonsoft.Json /// property returns the . This result will be null at the end of an array. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task ReadAsStringAsync(CancellationToken cancellationToken = default) + public virtual Task ReadAsStringAsync(CancellationToken cancellationToken = default) { - return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsString()); + return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsString()); } internal async Task ReadAndMoveToContentAsync(CancellationToken cancellationToken) diff --git a/Libs/Newtonsoft.Json/JsonReader.cs b/Libs/Newtonsoft.Json/JsonReader.cs index bea7c47..9cae406 100644 --- a/Libs/Newtonsoft.Json/JsonReader.cs +++ b/Libs/Newtonsoft.Json/JsonReader.cs @@ -113,18 +113,18 @@ namespace LC.Newtonsoft.Json // current Token data private JsonToken _tokenType; - private object? _value; + private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; - private CultureInfo? _culture; + private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; - private string? _dateFormatString; - private List? _stack; + private string _dateFormatString; + private List _stack; /// /// Gets the current reader state. @@ -219,7 +219,7 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets how custom date formatted strings are parsed when reading JSON. /// - public string? DateFormatString + public string DateFormatString { get => _dateFormatString; set => _dateFormatString = value; @@ -227,8 +227,6 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . - /// A null value means there is no maximum. - /// The default value is 128. /// public int? MaxDepth { @@ -252,12 +250,12 @@ namespace LC.Newtonsoft.Json /// /// Gets the text value of the current JSON token. /// - public virtual object? Value => _value; + public virtual object Value => _value; /// /// Gets the .NET type for the current JSON token. /// - public virtual Type? ValueType => _value?.GetType(); + public virtual Type ValueType => _value?.GetType(); /// /// Gets the depth of the current token in the JSON document. @@ -297,7 +295,7 @@ namespace LC.Newtonsoft.Json JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; - return JsonPosition.BuildPath(_stack!, current); + return JsonPosition.BuildPath(_stack, current); } } @@ -329,7 +327,6 @@ namespace LC.Newtonsoft.Json _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; - _maxDepth = 64; CloseInput = true; } @@ -411,7 +408,7 @@ namespace LC.Newtonsoft.Json return null; case JsonToken.Integer: case JsonToken.Float: - object v = Value!; + object v = Value; if (v is int i) { return i; @@ -439,16 +436,16 @@ namespace LC.Newtonsoft.Json SetToken(JsonToken.Integer, i, false); return i; case JsonToken.String: - string? s = (string?)Value; + string s = (string)Value; return ReadInt32String(s); } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal int? ReadInt32String(string? s) + internal int? ReadInt32String(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -470,7 +467,7 @@ namespace LC.Newtonsoft.Json /// Reads the next JSON token from the source as a . /// /// A . This method will return null at the end of an array. - public virtual string? ReadAsString() + public virtual string ReadAsString() { JsonToken t = GetContentToken(); @@ -481,12 +478,12 @@ namespace LC.Newtonsoft.Json case JsonToken.EndArray: return null; case JsonToken.String: - return (string?)Value; + return (string)Value; } if (JsonTokenUtils.IsPrimitiveToken(t)) { - object? v = Value; + object v = Value; if (v != null) { string s; @@ -511,7 +508,7 @@ namespace LC.Newtonsoft.Json /// Reads the next JSON token from the source as a []. /// /// A [] or null if the next JSON token is null. This method will return null at the end of an array. - public virtual byte[]? ReadAsBytes() + public virtual byte[] ReadAsBytes() { JsonToken t = GetContentToken(); @@ -521,7 +518,7 @@ namespace LC.Newtonsoft.Json { ReadIntoWrappedTypeObject(); - byte[]? data = ReadAsBytes(); + byte[] data = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) @@ -536,7 +533,7 @@ namespace LC.Newtonsoft.Json { // attempt to convert possible base 64 or GUID string to bytes // GUID has to have format 00000000-0000-0000-0000-000000000000 - string s = (string)Value!; + string s = (string)Value; byte[] data; @@ -568,7 +565,7 @@ namespace LC.Newtonsoft.Json return data; } - return (byte[]?)Value; + return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); } @@ -630,7 +627,7 @@ namespace LC.Newtonsoft.Json return null; case JsonToken.Integer: case JsonToken.Float: - object v = Value!; + object v = Value; if (v is double d) { return d; @@ -651,15 +648,15 @@ namespace LC.Newtonsoft.Json return (double)d; case JsonToken.String: - return ReadDoubleString((string?)Value); + return ReadDoubleString((string)Value); } throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal double? ReadDoubleString(string? s) + internal double? ReadDoubleString(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -708,17 +705,17 @@ namespace LC.Newtonsoft.Json SetToken(JsonToken.Boolean, b, false); return b; case JsonToken.String: - return ReadBooleanString((string?)Value); + return ReadBooleanString((string)Value); case JsonToken.Boolean: - return (bool)Value!; + return (bool)Value; } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal bool? ReadBooleanString(string? s) + internal bool? ReadBooleanString(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -752,7 +749,7 @@ namespace LC.Newtonsoft.Json return null; case JsonToken.Integer: case JsonToken.Float: - object v = Value!; + object v = Value; if (v is decimal d) { @@ -781,15 +778,15 @@ namespace LC.Newtonsoft.Json SetToken(JsonToken.Float, d, false); return d; case JsonToken.String: - return ReadDecimalString((string?)Value); + return ReadDecimalString((string)Value); } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal decimal? ReadDecimalString(string? s) + internal decimal? ReadDecimalString(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -833,17 +830,18 @@ namespace LC.Newtonsoft.Json } #endif - return (DateTime)Value!; + return (DateTime)Value; case JsonToken.String: - return ReadDateTimeString((string?)Value); + string s = (string)Value; + return ReadDateTimeString(s); } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } - internal DateTime? ReadDateTimeString(string? s) + internal DateTime? ReadDateTimeString(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -887,18 +885,18 @@ namespace LC.Newtonsoft.Json SetToken(JsonToken.Date, new DateTimeOffset(time), false); } - return (DateTimeOffset)Value!; + return (DateTimeOffset)Value; case JsonToken.String: - string? s = (string?)Value; + string s = (string)Value; return ReadDateTimeOffsetString(s); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } - internal DateTimeOffset? ReadDateTimeOffsetString(string? s) + internal DateTimeOffset? ReadDateTimeOffsetString(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -987,7 +985,7 @@ namespace LC.Newtonsoft.Json /// /// The new token. /// The value. - protected void SetToken(JsonToken newToken, object? value) + protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } @@ -998,7 +996,7 @@ namespace LC.Newtonsoft.Json /// The new token. /// The value. /// A flag indicating whether the position index inside an array should be updated. - protected void SetToken(JsonToken newToken, object? value, bool updateIndex) + protected void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; @@ -1029,7 +1027,7 @@ namespace LC.Newtonsoft.Json case JsonToken.PropertyName: _currentState = State.Property; - _currentPosition.PropertyName = (string)value!; + _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: @@ -1172,7 +1170,7 @@ namespace LC.Newtonsoft.Json } } - internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) + internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { @@ -1180,7 +1178,7 @@ namespace LC.Newtonsoft.Json } } - internal bool ReadForType(JsonContract? contract, bool hasConverter) + internal bool ReadForType(JsonContract contract, bool hasConverter) { // don't read properties with converters as a specific value // the value might be a string which will then get converted which will error if read as date for example diff --git a/Libs/Newtonsoft.Json/JsonReaderException.cs b/Libs/Newtonsoft.Json/JsonReaderException.cs index 8a0ec38..7ff138a 100644 --- a/Libs/Newtonsoft.Json/JsonReaderException.cs +++ b/Libs/Newtonsoft.Json/JsonReaderException.cs @@ -54,7 +54,7 @@ namespace LC.Newtonsoft.Json /// Gets the path to the JSON where the error occurred. /// /// The path to the JSON where the error occurred. - public string? Path { get; } + public string Path { get; } /// /// Initializes a new instance of the class. @@ -107,7 +107,7 @@ namespace LC.Newtonsoft.Json /// The line number indicating where the error occurred. /// The line position indicating where the error occurred. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) + public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception innerException) : base(message, innerException) { Path = path; @@ -120,12 +120,12 @@ namespace LC.Newtonsoft.Json return Create(reader, message, null); } - internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) + internal static JsonReaderException Create(JsonReader reader, string message, Exception ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } - internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) + internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); diff --git a/Libs/Newtonsoft.Json/JsonSerializationException.cs b/Libs/Newtonsoft.Json/JsonSerializationException.cs index 8c44980..0492f14 100644 --- a/Libs/Newtonsoft.Json/JsonSerializationException.cs +++ b/Libs/Newtonsoft.Json/JsonSerializationException.cs @@ -54,7 +54,7 @@ namespace LC.Newtonsoft.Json /// Gets the path to the JSON where the error occurred. /// /// The path to the JSON where the error occurred. - public string? Path { get; } + public string Path { get; } /// /// Initializes a new instance of the class. @@ -107,7 +107,7 @@ namespace LC.Newtonsoft.Json /// The line number indicating where the error occurred. /// The line position indicating where the error occurred. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) + public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception innerException) : base(message, innerException) { Path = path; @@ -120,12 +120,12 @@ namespace LC.Newtonsoft.Json return Create(reader, message, null); } - internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) + internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } - internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) + internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); diff --git a/Libs/Newtonsoft.Json/JsonSerializer.cs b/Libs/Newtonsoft.Json/JsonSerializer.cs index aab727f..4723161 100644 --- a/Libs/Newtonsoft.Json/JsonSerializer.cs +++ b/Libs/Newtonsoft.Json/JsonSerializer.cs @@ -35,8 +35,6 @@ using LC.Newtonsoft.Json.Serialization; using LC.Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using ErrorEventArgs = LC.Newtonsoft.Json.Serialization.ErrorEventArgs; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; namespace LC.Newtonsoft.Json { @@ -56,13 +54,13 @@ namespace LC.Newtonsoft.Json internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; - internal JsonConverterCollection? _converters; + internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; - internal ITraceWriter? _traceWriter; - internal IEqualityComparer? _equalityComparer; + internal ITraceWriter _traceWriter; + internal IEqualityComparer _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; - private IReferenceResolver? _referenceResolver; + private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; @@ -75,18 +73,18 @@ namespace LC.Newtonsoft.Json private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; - private string? _dateFormatString; + private string _dateFormatString; private bool _dateFormatStringSet; /// /// Occurs when the errors during serialization and deserialization. /// - public virtual event EventHandler? Error; + public virtual event EventHandler Error; /// /// Gets or sets the used by the serializer when resolving references. /// - public virtual IReferenceResolver? ReferenceResolver + public virtual IReferenceResolver ReferenceResolver { get => GetReferenceResolver(); set @@ -108,6 +106,11 @@ namespace LC.Newtonsoft.Json { get { + if (_serializationBinder == null) + { + return null; + } + if (_serializationBinder is SerializationBinder legacySerializationBinder) { return legacySerializationBinder; @@ -152,7 +155,7 @@ namespace LC.Newtonsoft.Json /// Gets or sets the used by the serializer when writing trace messages. /// /// The trace writer. - public virtual ITraceWriter? TraceWriter + public virtual ITraceWriter TraceWriter { get => _traceWriter; set => _traceWriter = value; @@ -162,7 +165,7 @@ namespace LC.Newtonsoft.Json /// Gets or sets the equality comparer used by the serializer when comparing references. /// /// The equality comparer. - public virtual IEqualityComparer? EqualityComparer + public virtual IEqualityComparer EqualityComparer { get => _equalityComparer; set => _equalityComparer = value; @@ -514,7 +517,7 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is 128. + /// The default value is null. /// public virtual int? MaxDepth { @@ -596,7 +599,7 @@ namespace LC.Newtonsoft.Json /// The will not use default settings /// from . /// - public static JsonSerializer Create(JsonSerializerSettings? settings) + public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); @@ -621,7 +624,7 @@ namespace LC.Newtonsoft.Json public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues - JsonSerializerSettings? defaultSettings = JsonConvert.DefaultSettings?.Invoke(); + JsonSerializerSettings defaultSettings = JsonConvert.DefaultSettings?.Invoke(); return Create(defaultSettings); } @@ -637,7 +640,7 @@ namespace LC.Newtonsoft.Json /// The will use default settings /// from as well as the specified . /// - public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) + public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) @@ -811,14 +814,14 @@ namespace LC.Newtonsoft.Json SetupReader( reader, - out CultureInfo? previousCulture, + out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, - out string? previousDateFormatString); + out string previousDateFormatString); - TraceJsonReader? traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null; @@ -827,7 +830,7 @@ namespace LC.Newtonsoft.Json if (traceJsonReader != null) { - TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); @@ -839,20 +842,20 @@ namespace LC.Newtonsoft.Json /// The that contains the JSON structure to deserialize. /// The being deserialized. [DebuggerStepThrough] - public object? Deserialize(JsonReader reader) + public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// - /// Deserializes the JSON structure contained by the specified + /// Deserializes the JSON structure contained by the specified /// into an instance of the specified type. /// /// The containing the object. /// The of object being deserialized. /// The instance of being deserialized. [DebuggerStepThrough] - public object? Deserialize(TextReader reader, Type objectType) + public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } @@ -865,9 +868,9 @@ namespace LC.Newtonsoft.Json /// The type of the object to deserialize. /// The instance of being deserialized. [DebuggerStepThrough] - public T? Deserialize(JsonReader reader) + public T Deserialize(JsonReader reader) { - return (T?)Deserialize(reader, typeof(T)); + return (T)Deserialize(reader, typeof(T)); } /// @@ -878,34 +881,34 @@ namespace LC.Newtonsoft.Json /// The of object being deserialized. /// The instance of being deserialized. [DebuggerStepThrough] - public object? Deserialize(JsonReader reader, Type? objectType) + public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } - internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) + internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); SetupReader( reader, - out CultureInfo? previousCulture, + out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, - out string? previousDateFormatString); + out string previousDateFormatString); - TraceJsonReader? traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); - object? value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); + object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { - TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); @@ -913,7 +916,7 @@ namespace LC.Newtonsoft.Json return value; } - private void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) + private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { @@ -984,7 +987,7 @@ namespace LC.Newtonsoft.Json } } - private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) + private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) { // reset reader back to previous options if (previousCulture != null) @@ -1025,7 +1028,7 @@ namespace LC.Newtonsoft.Json /// /// The used to write the JSON structure. /// The to serialize. - public void Serialize(TextWriter textWriter, object? value) + public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } @@ -1041,7 +1044,7 @@ namespace LC.Newtonsoft.Json /// This parameter is used when is to write out the type name if the type of the value does not match. /// Specifying the type is optional. /// - public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) + public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } @@ -1057,7 +1060,7 @@ namespace LC.Newtonsoft.Json /// This parameter is used when is Auto to write out the type name if the type of the value does not match. /// Specifying the type is optional. /// - public void Serialize(TextWriter textWriter, object? value, Type objectType) + public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } @@ -1068,7 +1071,7 @@ namespace LC.Newtonsoft.Json /// /// The used to write the JSON structure. /// The to serialize. - public void Serialize(JsonWriter jsonWriter, object? value) + public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } @@ -1084,7 +1087,7 @@ namespace LC.Newtonsoft.Json return traceReader; } - internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) + internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter)); @@ -1124,21 +1127,21 @@ namespace LC.Newtonsoft.Json jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } - CultureInfo? previousCulture = null; + CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } - string? previousDateFormatString = null; + string previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } - TraceJsonWriter? traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; @@ -1147,7 +1150,7 @@ namespace LC.Newtonsoft.Json if (traceJsonWriter != null) { - TraceWriter!.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); + TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } // reset writer back to previous options @@ -1191,12 +1194,12 @@ namespace LC.Newtonsoft.Json return _referenceResolver; } - internal JsonConverter? GetMatchingConverter(Type type) + internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } - internal static JsonConverter? GetMatchingConverter(IList? converters, Type objectType) + internal static JsonConverter GetMatchingConverter(IList converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, nameof(objectType)); diff --git a/Libs/Newtonsoft.Json/JsonSerializerSettings.cs b/Libs/Newtonsoft.Json/JsonSerializerSettings.cs index e0d42b8..583cb29 100644 --- a/Libs/Newtonsoft.Json/JsonSerializerSettings.cs +++ b/Libs/Newtonsoft.Json/JsonSerializerSettings.cs @@ -61,7 +61,6 @@ namespace LC.Newtonsoft.Json internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; - internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; @@ -70,11 +69,11 @@ namespace LC.Newtonsoft.Json internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; - internal CultureInfo? _culture; + internal CultureInfo _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; - internal string? _dateFormatString; + internal string _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; @@ -226,27 +225,27 @@ namespace LC.Newtonsoft.Json /// serializing .NET objects to JSON and vice versa. /// /// The contract resolver. - public IContractResolver? ContractResolver { get; set; } + public IContractResolver ContractResolver { get; set; } /// /// Gets or sets the equality comparer used by the serializer when comparing references. /// /// The equality comparer. - public IEqualityComparer? EqualityComparer { get; set; } + public IEqualityComparer EqualityComparer { get; set; } /// /// Gets or sets the used by the serializer when resolving references. /// /// The reference resolver. [Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")] - public IReferenceResolver? ReferenceResolver + public IReferenceResolver ReferenceResolver { get => ReferenceResolverProvider?.Invoke(); set { ReferenceResolverProvider = (value != null) ? () => value - : (Func?)null; + : (Func)null; } } @@ -254,20 +253,20 @@ namespace LC.Newtonsoft.Json /// Gets or sets a function that creates the used by the serializer when resolving references. /// /// A function that creates the used by the serializer when resolving references. - public Func? ReferenceResolverProvider { get; set; } + public Func ReferenceResolverProvider { get; set; } /// /// Gets or sets the used by the serializer when writing trace messages. /// /// The trace writer. - public ITraceWriter? TraceWriter { get; set; } + public ITraceWriter TraceWriter { get; set; } /// /// Gets or sets the used by the serializer when resolving type names. /// /// The binder. [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] - public SerializationBinder? Binder + public SerializationBinder Binder { get { @@ -290,13 +289,13 @@ namespace LC.Newtonsoft.Json /// Gets or sets the used by the serializer when resolving type names. /// /// The binder. - public ISerializationBinder? SerializationBinder { get; set; } + public ISerializationBinder SerializationBinder { get; set; } /// /// Gets or sets the error handler called during serialization and deserialization. /// /// The error handler called during serialization and deserialization. - public EventHandler? Error { get; set; } + public EventHandler Error { get; set; } /// /// Gets or sets the used by the serializer when invoking serialization callback methods. @@ -326,11 +325,11 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is 128. + /// The default value is null. /// public int? MaxDepth { - get => _maxDepthSet ? _maxDepth : DefaultMaxDepth; + get => _maxDepth; set { if (value <= 0) diff --git a/Libs/Newtonsoft.Json/JsonTextReader.Async.cs b/Libs/Newtonsoft.Json/JsonTextReader.Async.cs index 79ffe99..520709e 100644 --- a/Libs/Newtonsoft.Json/JsonTextReader.Async.cs +++ b/Libs/Newtonsoft.Json/JsonTextReader.Async.cs @@ -34,7 +34,6 @@ using System.Numerics; using System.Threading.Tasks; using LC.Newtonsoft.Json.Serialization; using LC.Newtonsoft.Json.Utilities; -using System.Diagnostics; namespace LC.Newtonsoft.Json { @@ -111,8 +110,6 @@ namespace LC.Newtonsoft.Json private async Task ParsePostValueAsync(bool ignoreComments, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -196,8 +193,6 @@ namespace LC.Newtonsoft.Json private async Task ReadFromFinishedAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); @@ -227,8 +222,6 @@ namespace LC.Newtonsoft.Json private async Task ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - if (_isEndOfFile) { return 0; @@ -251,8 +244,6 @@ namespace LC.Newtonsoft.Json private async Task ParseValueAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -382,8 +373,6 @@ namespace LC.Newtonsoft.Json private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; @@ -600,8 +589,6 @@ namespace LC.Newtonsoft.Json private async Task ParseObjectAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -659,8 +646,6 @@ namespace LC.Newtonsoft.Json private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - // should have already parsed / character before reaching this method _charPos++; @@ -757,8 +742,6 @@ namespace LC.Newtonsoft.Json private async Task EatWhitespaceAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -815,8 +798,6 @@ namespace LC.Newtonsoft.Json private async Task MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - // will match value and then move to the next character, checking that it is a separator character if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false)) { @@ -831,7 +812,7 @@ namespace LC.Newtonsoft.Json return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0'; } - private async Task MatchAndSetAsync(string value, JsonToken newToken, object? tokenValue, CancellationToken cancellationToken) + private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken) { if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false)) { @@ -860,8 +841,6 @@ namespace LC.Newtonsoft.Json private async Task ParseConstructorAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); @@ -960,8 +939,6 @@ namespace LC.Newtonsoft.Json private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - ShiftBufferIfNeeded(); char firstChar = _chars[_charPos]; @@ -979,8 +956,6 @@ namespace LC.Newtonsoft.Json private async Task ParsePropertyAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - char firstChar = _chars[_charPos]; char quoteChar; @@ -1033,8 +1008,6 @@ namespace LC.Newtonsoft.Json private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - int charPos = _charPos; while (true) @@ -1069,8 +1042,6 @@ namespace LC.Newtonsoft.Json private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - int initialPosition = _charPos; // parse unquoted property name until whitespace or colon @@ -1120,8 +1091,6 @@ namespace LC.Newtonsoft.Json private async Task HandleNullAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false)) { if (_chars[_charPos + 1] == 'u') @@ -1140,8 +1109,6 @@ namespace LC.Newtonsoft.Json private async Task ReadFinishedAsync(CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_chars != null); - if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); @@ -1164,10 +1131,9 @@ namespace LC.Newtonsoft.Json SetToken(JsonToken.None); } - private async Task ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken) + private async Task ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken) { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1300,10 +1266,9 @@ namespace LC.Newtonsoft.Json } } - private async Task ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken) + private async Task ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken) { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1430,7 +1395,6 @@ namespace LC.Newtonsoft.Json internal async Task DoReadAsBooleanAsync(CancellationToken cancellationToken) { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1558,16 +1522,14 @@ namespace LC.Newtonsoft.Json /// property returns the []. This result will be null at the end of an array. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task ReadAsBytesAsync(CancellationToken cancellationToken = default) + public override Task ReadAsBytesAsync(CancellationToken cancellationToken = default) { return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken); } - internal async Task DoReadAsBytesAsync(CancellationToken cancellationToken) + internal async Task DoReadAsBytesAsync(CancellationToken cancellationToken) { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); - bool isWrapped = false; switch (_currentState) @@ -1601,7 +1563,7 @@ namespace LC.Newtonsoft.Json case '"': case '\'': await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false); - byte[]? data = (byte[]?)Value; + byte[] data = (byte[])Value; if (isWrapped) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); @@ -1791,14 +1753,14 @@ namespace LC.Newtonsoft.Json /// property returns the . This result will be null at the end of an array. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task ReadAsStringAsync(CancellationToken cancellationToken = default) + public override Task ReadAsStringAsync(CancellationToken cancellationToken = default) { return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken); } - internal async Task DoReadAsStringAsync(CancellationToken cancellationToken) + internal async Task DoReadAsStringAsync(CancellationToken cancellationToken) { - return (string?)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false); + return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false); } } } diff --git a/Libs/Newtonsoft.Json/JsonTextReader.cs b/Libs/Newtonsoft.Json/JsonTextReader.cs index 9bfa85c..8e0852e 100644 --- a/Libs/Newtonsoft.Json/JsonTextReader.cs +++ b/Libs/Newtonsoft.Json/JsonTextReader.cs @@ -27,7 +27,6 @@ using System; using System.Runtime.CompilerServices; using System.IO; using System.Globalization; -using System.Diagnostics; #if HAVE_BIG_INTEGER using System.Numerics; #endif @@ -67,7 +66,7 @@ namespace LC.Newtonsoft.Json #endif private readonly TextReader _reader; - private char[]? _chars; + private char[] _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; @@ -75,7 +74,7 @@ namespace LC.Newtonsoft.Json private bool _isEndOfFile; private StringBuffer _stringBuffer; private StringReference _stringReference; - private IArrayPool? _arrayPool; + private IArrayPool _arrayPool; /// /// Initializes a new instance of the class with the specified . @@ -97,7 +96,7 @@ namespace LC.Newtonsoft.Json } #if DEBUG - internal char[]? CharBuffer + internal char[] CharBuffer { get => _chars; set => _chars = value; @@ -109,12 +108,12 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets the reader's property name table. /// - public JsonNameTable? PropertyNameTable { get; set; } + public JsonNameTable PropertyNameTable { get; set; } /// /// Gets or sets the reader's character buffer pool. /// - public IArrayPool? ArrayPool + public IArrayPool ArrayPool { get => _arrayPool; set @@ -138,8 +137,6 @@ namespace LC.Newtonsoft.Json private void SetNewLine(bool hasNextChar) { - MiscellaneousUtils.Assert(_chars != null); - if (hasNextChar && _chars[_charPos] == StringUtils.LineFeed) { _charPos++; @@ -252,8 +249,6 @@ namespace LC.Newtonsoft.Json private void ShiftBufferIfNeeded() { - MiscellaneousUtils.Assert(_chars != null); - // once in the last 10% of the buffer, or buffer is already very large then // shift the remaining content to the start to avoid unnecessarily increasing // the buffer size when reading numbers/strings @@ -280,8 +275,6 @@ namespace LC.Newtonsoft.Json private void PrepareBufferForReadData(bool append, int charsRequired) { - MiscellaneousUtils.Assert(_chars != null); - // char buffer is full if (_charsUsed + charsRequired >= _chars.Length - 1) { @@ -345,7 +338,6 @@ namespace LC.Newtonsoft.Json } PrepareBufferForReadData(append, charsRequired); - MiscellaneousUtils.Assert(_chars != null); int attemptCharReadCount = _chars.Length - _charsUsed - 1; @@ -414,7 +406,6 @@ namespace LC.Newtonsoft.Json public override bool Read() { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); while (true) { @@ -485,20 +476,18 @@ namespace LC.Newtonsoft.Json /// Reads the next JSON token from the underlying as a . /// /// A . This method will return null at the end of an array. - public override string? ReadAsString() + public override string ReadAsString() { - return (string?)ReadStringValue(ReadType.ReadAsString); + return (string)ReadStringValue(ReadType.ReadAsString); } /// /// Reads the next JSON token from the underlying as a []. /// /// A [] or null if the next JSON token is null. This method will return null at the end of an array. - public override byte[]? ReadAsBytes() + public override byte[] ReadAsBytes() { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); - bool isWrapped = false; switch (_currentState) @@ -531,7 +520,7 @@ namespace LC.Newtonsoft.Json case '"': case '\'': ParseString(currentChar, ReadType.ReadAsBytes); - byte[]? data = (byte[]?)Value; + byte[] data = (byte[])Value; if (isWrapped) { ReaderReadAndAssert(); @@ -600,10 +589,9 @@ namespace LC.Newtonsoft.Json } } - private object? ReadStringValue(ReadType readType) + private object ReadStringValue(ReadType readType) { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -730,7 +718,7 @@ namespace LC.Newtonsoft.Json } } - private object? FinishReadQuotedStringValue(ReadType readType) + private object FinishReadQuotedStringValue(ReadType readType) { switch (readType) { @@ -743,7 +731,7 @@ namespace LC.Newtonsoft.Json return time; } - return ReadDateTimeString((string?)Value); + return ReadDateTimeString((string)Value); #if HAVE_DATE_TIME_OFFSET case ReadType.ReadAsDateTimeOffset: if (Value is DateTimeOffset offset) @@ -751,7 +739,7 @@ namespace LC.Newtonsoft.Json return offset; } - return ReadDateTimeOffsetString((string?)Value); + return ReadDateTimeOffsetString((string)Value); #endif default: throw new ArgumentOutOfRangeException(nameof(readType)); @@ -770,7 +758,6 @@ namespace LC.Newtonsoft.Json public override bool? ReadAsBoolean() { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -905,10 +892,9 @@ namespace LC.Newtonsoft.Json SetStateBasedOnCurrent(); } - private object? ReadNumberValue(ReadType readType) + private object ReadNumberValue(ReadType readType) { EnsureBuffer(); - MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1016,7 +1002,7 @@ namespace LC.Newtonsoft.Json } } - private object? FinishReadQuotedNumber(ReadType readType) + private object FinishReadQuotedNumber(ReadType readType) { switch (readType) { @@ -1062,8 +1048,6 @@ namespace LC.Newtonsoft.Json private void HandleNull() { - MiscellaneousUtils.Assert(_chars != null); - if (EnsureChars(1, true)) { char next = _chars[_charPos + 1]; @@ -1084,8 +1068,6 @@ namespace LC.Newtonsoft.Json private void ReadFinished() { - MiscellaneousUtils.Assert(_chars != null); - if (EnsureChars(0, false)) { EatWhitespace(); @@ -1135,8 +1117,6 @@ namespace LC.Newtonsoft.Json private void ReadStringIntoBuffer(char quote) { - MiscellaneousUtils.Assert(_chars != null); - int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; @@ -1290,8 +1270,6 @@ namespace LC.Newtonsoft.Json private void FinishReadStringIntoBuffer(int charPos, int initialPosition, int lastWritePosition) { - MiscellaneousUtils.Assert(_chars != null); - if (initialPosition == lastWritePosition) { _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition); @@ -1305,7 +1283,7 @@ namespace LC.Newtonsoft.Json _stringBuffer.Append(_arrayPool, _chars, lastWritePosition, charPos - lastWritePosition); } - _stringReference = new StringReference(_stringBuffer.InternalBuffer!, 0, _stringBuffer.Position); + _stringReference = new StringReference(_stringBuffer.InternalBuffer, 0, _stringBuffer.Position); } _charPos = charPos + 1; @@ -1313,8 +1291,6 @@ namespace LC.Newtonsoft.Json private void WriteCharToBuffer(char writeChar, int lastWritePosition, int writeToPosition) { - MiscellaneousUtils.Assert(_chars != null); - if (writeToPosition > lastWritePosition) { _stringBuffer.Append(_arrayPool, _chars, lastWritePosition, writeToPosition - lastWritePosition); @@ -1325,8 +1301,6 @@ namespace LC.Newtonsoft.Json private char ConvertUnicode(bool enoughChars) { - MiscellaneousUtils.Assert(_chars != null); - if (enoughChars) { if (ConvertUtils.TryHexTextToInt(_chars, _charPos, _charPos + 4, out int value)) @@ -1353,8 +1327,6 @@ namespace LC.Newtonsoft.Json private void ReadNumberIntoBuffer() { - MiscellaneousUtils.Assert(_chars != null); - int charPos = _charPos; while (true) @@ -1439,8 +1411,6 @@ namespace LC.Newtonsoft.Json private bool ParsePostValue(bool ignoreComments) { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -1521,8 +1491,6 @@ namespace LC.Newtonsoft.Json private bool ParseObject() { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -1577,8 +1545,6 @@ namespace LC.Newtonsoft.Json private bool ParseProperty() { - MiscellaneousUtils.Assert(_chars != null); - char firstChar = _chars[_charPos]; char quoteChar; @@ -1600,7 +1566,7 @@ namespace LC.Newtonsoft.Json throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } - string? propertyName; + string propertyName; if (PropertyNameTable != null) { @@ -1640,8 +1606,6 @@ namespace LC.Newtonsoft.Json private void ParseUnquotedProperty() { - MiscellaneousUtils.Assert(_chars != null); - int initialPosition = _charPos; // parse unquoted property name until whitespace or colon @@ -1673,8 +1637,6 @@ namespace LC.Newtonsoft.Json private bool ReadUnquotedPropertyReportIfDone(char currentChar, int initialPosition) { - MiscellaneousUtils.Assert(_chars != null); - if (ValidIdentifierChar(currentChar)) { _charPos++; @@ -1692,8 +1654,6 @@ namespace LC.Newtonsoft.Json private bool ParseValue() { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -1834,8 +1794,6 @@ namespace LC.Newtonsoft.Json private void EatWhitespace() { - MiscellaneousUtils.Assert(_chars != null); - while (true) { char currentChar = _chars[_charPos]; @@ -1877,8 +1835,6 @@ namespace LC.Newtonsoft.Json private void ParseConstructor() { - MiscellaneousUtils.Assert(_chars != null); - if (MatchValueWithTrailingSeparator("new")) { EatWhitespace(); @@ -1963,7 +1919,6 @@ namespace LC.Newtonsoft.Json private void ParseNumber(ReadType readType) { ShiftBufferIfNeeded(); - MiscellaneousUtils.Assert(_chars != null); char firstChar = _chars[_charPos]; int initialPosition = _charPos; @@ -1974,9 +1929,7 @@ namespace LC.Newtonsoft.Json } private void ParseReadNumber(ReadType readType, char firstChar, int initialPosition) - { - MiscellaneousUtils.Assert(_chars != null); - + { // set state to PostValue now so that if there is an error parsing the number then the reader can continue SetPostValueState(true); @@ -2237,7 +2190,7 @@ namespace LC.Newtonsoft.Json SetToken(numberType, numberValue, false); } - private JsonReaderException ThrowReaderError(string message, Exception? ex = null) + private JsonReaderException ThrowReaderError(string message, Exception ex = null) { SetToken(JsonToken.Undefined, null, false); return JsonReaderException.Create(this, message, ex); @@ -2257,8 +2210,6 @@ namespace LC.Newtonsoft.Json private void ParseComment(bool setToken) { - MiscellaneousUtils.Assert(_chars != null); - // should have already parsed / character before reaching this method _charPos++; @@ -2364,8 +2315,6 @@ namespace LC.Newtonsoft.Json private bool MatchValue(bool enoughChars, string value) { - MiscellaneousUtils.Assert(_chars != null); - if (!enoughChars) { _charPos = _charsUsed; @@ -2388,8 +2337,6 @@ namespace LC.Newtonsoft.Json private bool MatchValueWithTrailingSeparator(string value) { - MiscellaneousUtils.Assert(_chars != null); - // will match value and then move to the next character, checking that it is a separator character bool match = MatchValue(value); @@ -2408,8 +2355,6 @@ namespace LC.Newtonsoft.Json private bool IsSeparator(char c) { - MiscellaneousUtils.Assert(_chars != null); - switch (c) { case '}': diff --git a/Libs/Newtonsoft.Json/JsonTextWriter.Async.cs b/Libs/Newtonsoft.Json/JsonTextWriter.Async.cs index dd7309e..a76faba 100644 --- a/Libs/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/Libs/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -33,7 +33,6 @@ using System.Numerics; #endif using System.Threading.Tasks; using LC.Newtonsoft.Json.Utilities; -using System.Diagnostics; namespace LC.Newtonsoft.Json { @@ -165,7 +164,6 @@ namespace LC.Newtonsoft.Json int currentIndentCount = Top * _indentation; int newLineLen = SetIndentChars(); - MiscellaneousUtils.Assert(_indentChars != null); if (currentIndentCount <= IndentCharBufferSize) { @@ -177,8 +175,6 @@ namespace LC.Newtonsoft.Json private async Task WriteIndentAsync(int currentIndentCount, int newLineLen, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(_indentChars != null); - await _writer.WriteAsync(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize), cancellationToken).ConfigureAwait(false); while ((currentIndentCount -= IndentCharBufferSize) > 0) @@ -229,12 +225,12 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteRawAsync(string? json, CancellationToken cancellationToken = default) + public override Task WriteRawAsync(string json, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteRawAsync(json, cancellationToken) : base.WriteRawAsync(json, cancellationToken); } - internal Task DoWriteRawAsync(string? json, CancellationToken cancellationToken) + internal Task DoWriteRawAsync(string json, CancellationToken cancellationToken) { return _writer.WriteAsync(json, cancellationToken); } @@ -264,7 +260,7 @@ namespace LC.Newtonsoft.Json } int length = WriteNumberToBuffer(uvalue, negative); - return _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken); + return _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken); } private Task WriteIntegerValueAsync(ulong uvalue, bool negative, CancellationToken cancellationToken) @@ -302,7 +298,7 @@ namespace LC.Newtonsoft.Json private Task WriteEscapedStringAsync(string value, bool quote, CancellationToken cancellationToken) { - return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, this, _writeBuffer!, cancellationToken); + return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, this, _writeBuffer, cancellationToken); } /// @@ -589,7 +585,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(byte[]? value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(byte[] value, CancellationToken cancellationToken = default) { return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNonNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken); } @@ -657,11 +653,11 @@ namespace LC.Newtonsoft.Json await InternalWriteValueAsync(JsonToken.Date, cancellationToken).ConfigureAwait(false); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); - if (StringUtils.IsNullOrEmpty(DateFormatString)) + if (string.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); - await _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken).ConfigureAwait(false); + await _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); } else { @@ -706,11 +702,11 @@ namespace LC.Newtonsoft.Json { await InternalWriteValueAsync(JsonToken.Date, cancellationToken).ConfigureAwait(false); - if (StringUtils.IsNullOrEmpty(DateFormatString)) + if (string.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); - await _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken).ConfigureAwait(false); + await _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); } else { @@ -957,7 +953,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(object? value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(object value, CancellationToken cancellationToken = default) { if (_safeAsync) { @@ -1050,12 +1046,12 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(string? value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(string value, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } - internal Task DoWriteValueAsync(string? value, CancellationToken cancellationToken) + internal Task DoWriteValueAsync(string value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); if (task.IsCompletedSucessfully()) @@ -1066,7 +1062,7 @@ namespace LC.Newtonsoft.Json return DoWriteValueAsync(task, value, cancellationToken); } - private async Task DoWriteValueAsync(Task task, string? value, CancellationToken cancellationToken) + private async Task DoWriteValueAsync(Task task, string value, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await (value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken)).ConfigureAwait(false); @@ -1185,7 +1181,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(Uri? value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default) { return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNotNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken); } @@ -1248,16 +1244,16 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteCommentAsync(string? text, CancellationToken cancellationToken = default) + public override Task WriteCommentAsync(string text, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteCommentAsync(text, cancellationToken) : base.WriteCommentAsync(text, cancellationToken); } - internal async Task DoWriteCommentAsync(string? text, CancellationToken cancellationToken) + internal async Task DoWriteCommentAsync(string text, CancellationToken cancellationToken) { await InternalWriteCommentAsync(cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("/*", cancellationToken).ConfigureAwait(false); - await _writer.WriteAsync(text ?? string.Empty, cancellationToken).ConfigureAwait(false); + await _writer.WriteAsync(text, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("*/", cancellationToken).ConfigureAwait(false); } @@ -1305,12 +1301,12 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteRawValueAsync(string? json, CancellationToken cancellationToken = default) + public override Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteRawValueAsync(json, cancellationToken) : base.WriteRawValueAsync(json, cancellationToken); } - internal Task DoWriteRawValueAsync(string? json, CancellationToken cancellationToken) + internal Task DoWriteRawValueAsync(string json, CancellationToken cancellationToken) { UpdateScopeWithFinishedValue(); Task task = AutoCompleteAsync(JsonToken.Undefined, cancellationToken); @@ -1322,7 +1318,7 @@ namespace LC.Newtonsoft.Json return DoWriteRawValueAsync(task, json, cancellationToken); } - private async Task DoWriteRawValueAsync(Task task, string? json, CancellationToken cancellationToken) + private async Task DoWriteRawValueAsync(Task task, string json, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await WriteRawAsync(json, cancellationToken).ConfigureAwait(false); @@ -1335,7 +1331,7 @@ namespace LC.Newtonsoft.Json length = 35; } - char[]? buffer = _writeBuffer; + char[] buffer = _writeBuffer; if (buffer == null) { return _writeBuffer = BufferUtils.RentBuffer(_arrayPool, length); diff --git a/Libs/Newtonsoft.Json/JsonTextWriter.cs b/Libs/Newtonsoft.Json/JsonTextWriter.cs index 9719604..80bb455 100644 --- a/Libs/Newtonsoft.Json/JsonTextWriter.cs +++ b/Libs/Newtonsoft.Json/JsonTextWriter.cs @@ -33,7 +33,6 @@ using System.Text; using System.IO; using System.Xml; using LC.Newtonsoft.Json.Utilities; -using System.Diagnostics; namespace LC.Newtonsoft.Json { @@ -44,15 +43,15 @@ namespace LC.Newtonsoft.Json { private const int IndentCharBufferSize = 12; private readonly TextWriter _writer; - private Base64Encoder? _base64Encoder; + private Base64Encoder _base64Encoder; private char _indentChar; private int _indentation; private char _quoteChar; private bool _quoteName; - private bool[]? _charEscapeFlags; - private char[]? _writeBuffer; - private IArrayPool? _arrayPool; - private char[]? _indentChars; + private bool[] _charEscapeFlags; + private char[] _writeBuffer; + private IArrayPool _arrayPool; + private char[] _indentChars; private Base64Encoder Base64Encoder { @@ -70,7 +69,7 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets the writer's character array pool. /// - public IArrayPool? ArrayPool + public IArrayPool ArrayPool { get => _arrayPool; set @@ -343,7 +342,7 @@ namespace LC.Newtonsoft.Json { for (int i = 0; i != newLineLen; ++i) { - if (writerNewLine[i] != _indentChars![i]) + if (writerNewLine[i] != _indentChars[i]) { match = false; break; @@ -388,7 +387,7 @@ namespace LC.Newtonsoft.Json /// An error will raised if the value cannot be written as a single JSON token. /// /// The value to write. - public override void WriteValue(object? value) + public override void WriteValue(object value) { #if HAVE_BIG_INTEGER if (value is BigInteger i) @@ -425,7 +424,7 @@ namespace LC.Newtonsoft.Json /// Writes raw JSON. /// /// The raw JSON to write. - public override void WriteRaw(string? json) + public override void WriteRaw(string json) { InternalWriteRaw(); @@ -436,7 +435,7 @@ namespace LC.Newtonsoft.Json /// Writes a value. /// /// The value to write. - public override void WriteValue(string? value) + public override void WriteValue(string value) { InternalWriteValue(JsonToken.String); @@ -453,7 +452,7 @@ namespace LC.Newtonsoft.Json private void WriteEscapedString(string value, bool quote) { EnsureWriteBuffer(); - JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, _arrayPool, ref _writeBuffer); + JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, _arrayPool, ref _writeBuffer); } /// @@ -633,7 +632,7 @@ namespace LC.Newtonsoft.Json InternalWriteValue(JsonToken.Date); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); - if (StringUtils.IsNullOrEmpty(DateFormatString)) + if (string.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); @@ -650,7 +649,6 @@ namespace LC.Newtonsoft.Json private int WriteValueToBuffer(DateTime value) { EnsureWriteBuffer(); - MiscellaneousUtils.Assert(_writeBuffer != null); int pos = 0; _writeBuffer[pos++] = _quoteChar; @@ -663,7 +661,7 @@ namespace LC.Newtonsoft.Json /// Writes a [] value. /// /// The [] value to write. - public override void WriteValue(byte[]? value) + public override void WriteValue(byte[] value) { if (value == null) { @@ -688,7 +686,7 @@ namespace LC.Newtonsoft.Json { InternalWriteValue(JsonToken.Date); - if (StringUtils.IsNullOrEmpty(DateFormatString)) + if (string.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); @@ -705,7 +703,6 @@ namespace LC.Newtonsoft.Json private int WriteValueToBuffer(DateTimeOffset value) { EnsureWriteBuffer(); - MiscellaneousUtils.Assert(_writeBuffer != null); int pos = 0; _writeBuffer[pos++] = _quoteChar; @@ -723,7 +720,7 @@ namespace LC.Newtonsoft.Json { InternalWriteValue(JsonToken.String); - string text; + string text = null; #if HAVE_CHAR_TO_STRING_WITH_CULTURE text = value.ToString("D", CultureInfo.InvariantCulture); @@ -760,7 +757,7 @@ namespace LC.Newtonsoft.Json /// Writes a value. /// /// The value to write. - public override void WriteValue(Uri? value) + public override void WriteValue(Uri value) { if (value == null) { @@ -778,7 +775,7 @@ namespace LC.Newtonsoft.Json /// Writes a comment /*...*/ containing the specified text. /// /// Text to place inside the comment. - public override void WriteComment(string? text) + public override void WriteComment(string text) { InternalWriteComment(); @@ -842,7 +839,6 @@ namespace LC.Newtonsoft.Json } EnsureWriteBuffer(); - MiscellaneousUtils.Assert(_writeBuffer != null); int totalLength = MathUtils.IntLength(value); @@ -894,7 +890,6 @@ namespace LC.Newtonsoft.Json private int WriteNumberToBuffer(uint value, bool negative) { EnsureWriteBuffer(); - MiscellaneousUtils.Assert(_writeBuffer != null); int totalLength = MathUtils.IntLength(value); diff --git a/Libs/Newtonsoft.Json/JsonValidatingReader.cs b/Libs/Newtonsoft.Json/JsonValidatingReader.cs index 93efb46..f0a343c 100644 --- a/Libs/Newtonsoft.Json/JsonValidatingReader.cs +++ b/Libs/Newtonsoft.Json/JsonValidatingReader.cs @@ -41,8 +41,6 @@ using System.Linq; #endif -#nullable disable - namespace LC.Newtonsoft.Json { /// diff --git a/Libs/Newtonsoft.Json/JsonWriter.Async.cs b/Libs/Newtonsoft.Json/JsonWriter.Async.cs index bbeec12..2a4adc4 100644 --- a/Libs/Newtonsoft.Json/JsonWriter.Async.cs +++ b/Libs/Newtonsoft.Json/JsonWriter.Async.cs @@ -225,7 +225,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteRawAsync(string? json, CancellationToken cancellationToken = default) + public virtual Task WriteRawAsync(string json, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -546,7 +546,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteCommentAsync(string? text, CancellationToken cancellationToken = default) + public virtual Task WriteCommentAsync(string text, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -570,7 +570,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteRawValueAsync(string? json, CancellationToken cancellationToken = default) + public virtual Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -673,7 +673,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public Task WriteTokenAsync(JsonToken token, object? value, CancellationToken cancellationToken = default) + public Task WriteTokenAsync(JsonToken token, object value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -755,7 +755,7 @@ namespace LC.Newtonsoft.Json return WriteValueAsync(guid, cancellationToken); } - return WriteValueAsync((byte[]?)value, cancellationToken); + return WriteValueAsync((byte[])value, cancellationToken); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type."); } @@ -768,7 +768,7 @@ namespace LC.Newtonsoft.Json do { // write a JValue date when the constructor is for a date - if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) + if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) { await WriteConstructorDateAsync(reader, cancellationToken).ConfigureAwait(false); } @@ -785,7 +785,7 @@ namespace LC.Newtonsoft.Json && writeChildren && await reader.ReadAsync(cancellationToken).ConfigureAwait(false)); - if (IsWriteTokenIncomplete(reader, writeChildren, initialDepth)) + if (initialDepth < CalculateWriteTokenFinalDepth(reader)) { throw JsonWriterException.Create(this, "Unexpected end when reading token.", null); } @@ -801,7 +801,7 @@ namespace LC.Newtonsoft.Json do { // write a JValue date when the constructor is for a date - if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) + if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) { WriteConstructorDate(reader); } @@ -831,7 +831,7 @@ namespace LC.Newtonsoft.Json throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); } - DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime((long)reader.Value!); + DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime((long)reader.Value); if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) { @@ -929,7 +929,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(byte[]? value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(byte[] value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -1290,7 +1290,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(object? value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(object value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -1387,7 +1387,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(string? value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(string value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -1524,7 +1524,7 @@ namespace LC.Newtonsoft.Json /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(Uri? value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { diff --git a/Libs/Newtonsoft.Json/JsonWriter.cs b/Libs/Newtonsoft.Json/JsonWriter.cs index 3149fb4..5d80ec2 100644 --- a/Libs/Newtonsoft.Json/JsonWriter.cs +++ b/Libs/Newtonsoft.Json/JsonWriter.cs @@ -62,7 +62,7 @@ namespace LC.Newtonsoft.Json // array that gives a new state based on the current state an the token being written private static readonly State[][] StateArray; - internal static readonly State[][] StateArrayTemplate = new[] + internal static readonly State[][] StateArrayTempate = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // @@ -78,9 +78,9 @@ namespace LC.Newtonsoft.Json internal static State[][] BuildStateArray() { - List allStates = StateArrayTemplate.ToList(); - State[] errorStates = StateArrayTemplate[0]; - State[] valueStates = StateArrayTemplate[7]; + List allStates = StateArrayTempate.ToList(); + State[] errorStates = StateArrayTempate[0]; + State[] valueStates = StateArrayTempate[7]; EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(typeof(JsonToken)); @@ -116,7 +116,7 @@ namespace LC.Newtonsoft.Json StateArray = BuildStateArray(); } - private List? _stack; + private List _stack; private JsonPosition _currentPosition; private State _currentState; private Formatting _formatting; @@ -218,7 +218,7 @@ namespace LC.Newtonsoft.Json JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; - return JsonPosition.BuildPath(_stack!, current); + return JsonPosition.BuildPath(_stack, current); } } @@ -226,8 +226,8 @@ namespace LC.Newtonsoft.Json private DateTimeZoneHandling _dateTimeZoneHandling; private StringEscapeHandling _stringEscapeHandling; private FloatFormatHandling _floatFormatHandling; - private string? _dateFormatString; - private CultureInfo? _culture; + private string _dateFormatString; + private CultureInfo _culture; /// /// Gets or sets a value indicating how JSON text output should be formatted. @@ -325,7 +325,7 @@ namespace LC.Newtonsoft.Json /// /// Gets or sets how and values are formatted when writing JSON text. /// - public string? DateFormatString + public string DateFormatString { get => _dateFormatString; set => _dateFormatString = value; @@ -522,7 +522,7 @@ namespace LC.Newtonsoft.Json /// A value is only required for tokens that have an associated value, e.g. the property name for . /// null can be passed to the method for tokens that don't have a value, e.g. . /// - public void WriteToken(JsonToken token, object? value) + public void WriteToken(JsonToken token, object value) { switch (token) { @@ -579,9 +579,8 @@ namespace LC.Newtonsoft.Json } break; case JsonToken.String: - // Allow for a null string. This matches JTokenReader behavior which can read - // a JsonToken.String with a null value. - WriteValue(value?.ToString()); + ValidationUtils.ArgumentNotNull(value, nameof(value)); + WriteValue(value.ToString()); break; case JsonToken.Boolean: ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -626,7 +625,7 @@ namespace LC.Newtonsoft.Json } else { - WriteValue((byte[])value!); + WriteValue((byte[])value); } break; default: @@ -650,7 +649,7 @@ namespace LC.Newtonsoft.Json do { // write a JValue date when the constructor is for a date - if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) + if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) { WriteConstructorDate(reader); } @@ -667,19 +666,12 @@ namespace LC.Newtonsoft.Json && writeChildren && reader.Read()); - if (IsWriteTokenIncomplete(reader, writeChildren, initialDepth)) + if (initialDepth < CalculateWriteTokenFinalDepth(reader)) { throw JsonWriterException.Create(this, "Unexpected end when reading token.", null); } } - private bool IsWriteTokenIncomplete(JsonReader reader, bool writeChildren, int initialDepth) - { - int finalDepth = CalculateWriteTokenFinalDepth(reader); - return initialDepth < finalDepth || - (writeChildren && initialDepth == finalDepth && JsonTokenUtils.IsStartToken(reader.TokenType)); - } - private int CalculateWriteTokenInitialDepth(JsonReader reader) { JsonToken type = reader.TokenType; @@ -704,7 +696,7 @@ namespace LC.Newtonsoft.Json private void WriteConstructorDate(JsonReader reader) { - if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string? errorMessage)) + if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string errorMessage)) { throw JsonWriterException.Create(this, errorMessage, null); } @@ -795,7 +787,7 @@ namespace LC.Newtonsoft.Json { int currentLevel = top - i; - if (_stack![currentLevel].Type == type) + if (_stack[currentLevel].Type == type) { levelsToComplete = i + 2; break; @@ -917,7 +909,7 @@ namespace LC.Newtonsoft.Json /// Writes raw JSON without changing the writer's state. /// /// The raw JSON to write. - public virtual void WriteRaw(string? json) + public virtual void WriteRaw(string json) { InternalWriteRaw(); } @@ -926,7 +918,7 @@ namespace LC.Newtonsoft.Json /// Writes raw JSON where a value is expected and updates the writer's state. /// /// The raw JSON to write. - public virtual void WriteRawValue(string? json) + public virtual void WriteRawValue(string json) { // hack. want writer to change state as if a value had been written UpdateScopeWithFinishedValue(); @@ -938,7 +930,7 @@ namespace LC.Newtonsoft.Json /// Writes a value. /// /// The value to write. - public virtual void WriteValue(string? value) + public virtual void WriteValue(string value) { InternalWriteValue(JsonToken.String); } @@ -1384,7 +1376,7 @@ namespace LC.Newtonsoft.Json /// Writes a [] value. /// /// The [] value to write. - public virtual void WriteValue(byte[]? value) + public virtual void WriteValue(byte[] value) { if (value == null) { @@ -1400,7 +1392,7 @@ namespace LC.Newtonsoft.Json /// Writes a value. /// /// The value to write. - public virtual void WriteValue(Uri? value) + public virtual void WriteValue(Uri value) { if (value == null) { @@ -1417,7 +1409,7 @@ namespace LC.Newtonsoft.Json /// An error will raised if the value cannot be written as a single JSON token. /// /// The value to write. - public virtual void WriteValue(object? value) + public virtual void WriteValue(object value) { if (value == null) { @@ -1443,7 +1435,7 @@ namespace LC.Newtonsoft.Json /// Writes a comment /*...*/ containing the specified text. /// /// Text to place inside the comment. - public virtual void WriteComment(string? text) + public virtual void WriteComment(string text) { InternalWriteComment(); } diff --git a/Libs/Newtonsoft.Json/JsonWriterException.cs b/Libs/Newtonsoft.Json/JsonWriterException.cs index a2c8d34..9a65a83 100644 --- a/Libs/Newtonsoft.Json/JsonWriterException.cs +++ b/Libs/Newtonsoft.Json/JsonWriterException.cs @@ -42,7 +42,7 @@ namespace LC.Newtonsoft.Json /// Gets the path to the JSON where the error occurred. /// /// The path to the JSON where the error occurred. - public string? Path { get; } + public string Path { get; } /// /// Initializes a new instance of the class. @@ -93,18 +93,18 @@ namespace LC.Newtonsoft.Json /// The error message that explains the reason for the exception. /// The path to the JSON where the error occurred. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonWriterException(string message, string path, Exception? innerException) + public JsonWriterException(string message, string path, Exception innerException) : base(message, innerException) { Path = path; } - internal static JsonWriterException Create(JsonWriter writer, string message, Exception? ex) + internal static JsonWriterException Create(JsonWriter writer, string message, Exception ex) { return Create(writer.ContainerPath, message, ex); } - internal static JsonWriterException Create(string path, string message, Exception? ex) + internal static JsonWriterException Create(string path, string message, Exception ex) { message = JsonPosition.FormatMessage(null, path, message); diff --git a/Libs/Newtonsoft.Json/LC.Newtonsoft.Json.csproj b/Libs/Newtonsoft.Json/LC.Newtonsoft.Json.csproj index d4472c7..c350d48 100644 --- a/Libs/Newtonsoft.Json/LC.Newtonsoft.Json.csproj +++ b/Libs/Newtonsoft.Json/LC.Newtonsoft.Json.csproj @@ -2,7 +2,7 @@ netstandard2.0 $(LibraryFrameworks) - 9.0 + 8.0 11.0.0.0 11.0.1 @@ -18,34 +18,30 @@ Json.NET LC.Newtonsoft.Json json - packageIcon.png - $(MSBuildThisFileDirectory)packageIcon.png + https://www.newtonsoft.com/content/images/nugeticon.png https://www.newtonsoft.com/json MIT true LC.Newtonsoft.Json LC.Newtonsoft.Json true - enable 2.12 true snupkg Newtonsoft.Json.ruleset - true 0.7.1 - - - - + + + Json.NET - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) Json.NET .NET 4.0 @@ -60,27 +56,42 @@ NET20;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_DB_NULL_TYPE_CODE;HAVE_EMPTY_TYPES;HAVE_FAST_REVERSE;HAVE_FULL_REFLECTION;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_MEMORY_BARRIER;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_REFLECTION_EMIT;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;$(AdditionalConstants) - - - + + + Json.NET .NET Standard 1.0 - NETSTANDARD1_0;PORTABLE;HAVE_ASYNC;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + NETSTANDARD1_0;PORTABLE;HAVE_ASYNC;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;$(AdditionalConstants) - - + + Json.NET .NET Standard 1.3 - NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;HAVE_REGEX_TIMEOUTS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;$(AdditionalConstants) Json.NET .NET Standard 2.0 - NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) - - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;;DEBUG;NETSTANDARD;NETSTANDARD2_0; + + Json.NET Portable .NET 4.0 + PORTABLE40;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;$(AdditionalConstants) + .NETPortable + v4.0 + Profile328 + .NETPortable,Version=v0.0,Profile=Profile328 + $(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets + + + Json.NET Portable + PORTABLE;HAVE_ASYNC;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;$(AdditionalConstants) + .NETPortable + v4.5 + Profile259 + .NETPortable,Version=v0.0,Profile=Profile259 + $(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Linq/Extensions.cs b/Libs/Newtonsoft.Json/Linq/Extensions.cs index e401a5c..917b90b 100644 --- a/Libs/Newtonsoft.Json/Linq/Extensions.cs +++ b/Libs/Newtonsoft.Json/Linq/Extensions.cs @@ -27,8 +27,6 @@ using System; using System.Collections.Generic; using LC.Newtonsoft.Json.Utilities; using System.Globalization; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -113,9 +111,9 @@ namespace LC.Newtonsoft.Json.Linq /// An of that contains the source collection. /// The token key. /// An of that contains the values of every token in the source collection with the given key. - public static IJEnumerable Values(this IEnumerable source, object? key) + public static IJEnumerable Values(this IEnumerable source, object key) { - return Values(source, key)!.AsJEnumerable(); + return Values(source, key).AsJEnumerable(); } /// @@ -135,7 +133,7 @@ namespace LC.Newtonsoft.Json.Linq /// An of that contains the source collection. /// The token key. /// An that contains the converted values of every token in the source collection with the given key. - public static IEnumerable Values(this IEnumerable source, object key) + public static IEnumerable Values(this IEnumerable source, object key) { return Values(source, key); } @@ -146,7 +144,7 @@ namespace LC.Newtonsoft.Json.Linq /// The type to convert the values to. /// An of that contains the source collection. /// An that contains the converted values of every token in the source collection. - public static IEnumerable Values(this IEnumerable source) + public static IEnumerable Values(this IEnumerable source) { return Values(source, null); } @@ -157,7 +155,7 @@ namespace LC.Newtonsoft.Json.Linq /// The type to convert the value to. /// A cast as a of . /// A converted value. - public static U? Value(this IEnumerable value) + public static U Value(this IEnumerable value) { return value.Value(); } @@ -169,7 +167,7 @@ namespace LC.Newtonsoft.Json.Linq /// The type to convert the value to. /// A cast as a of . /// A converted value. - public static U? Value(this IEnumerable value) where T : JToken + public static U Value(this IEnumerable value) where T : JToken { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -181,7 +179,7 @@ namespace LC.Newtonsoft.Json.Linq return token.Convert(); } - internal static IEnumerable Values(this IEnumerable source, object? key) where T : JToken + internal static IEnumerable Values(this IEnumerable source, object key) where T : JToken { ValidationUtils.ArgumentNotNull(source, nameof(source)); @@ -206,7 +204,7 @@ namespace LC.Newtonsoft.Json.Linq { foreach (T token in source) { - JToken? value = token[key]; + JToken value = token[key]; if (value != null) { yield return value.Convert(); @@ -226,7 +224,7 @@ namespace LC.Newtonsoft.Json.Linq /// An of that contains the values of every token in the source collection. public static IJEnumerable Children(this IEnumerable source) where T : JToken { - return Children(source)!.AsJEnumerable(); + return Children(source).AsJEnumerable(); } /// @@ -236,14 +234,14 @@ namespace LC.Newtonsoft.Json.Linq /// The type to convert the values to. /// The source collection type. /// An that contains the converted values of every token in the source collection. - public static IEnumerable Children(this IEnumerable source) where T : JToken + public static IEnumerable Children(this IEnumerable source) where T : JToken { ValidationUtils.ArgumentNotNull(source, nameof(source)); return source.SelectMany(c => c.Children()).Convert(); } - internal static IEnumerable Convert(this IEnumerable source) where T : JToken + internal static IEnumerable Convert(this IEnumerable source) where T : JToken { ValidationUtils.ArgumentNotNull(source, nameof(source)); @@ -253,13 +251,11 @@ namespace LC.Newtonsoft.Json.Linq } } - internal static U? Convert(this T token) where T : JToken? + internal static U Convert(this T token) where T : JToken { if (token == null) { -#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. return default; -#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. } if (token is U castValue @@ -286,9 +282,7 @@ namespace LC.Newtonsoft.Json.Linq { if (value.Value == null) { -#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. return default; -#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. } targetType = Nullable.GetUnderlyingType(targetType); @@ -321,7 +315,7 @@ namespace LC.Newtonsoft.Json.Linq { if (source == null) { - return null!; + return null; } else if (source is IJEnumerable customEnumerable) { diff --git a/Libs/Newtonsoft.Json/Linq/JArray.Async.cs b/Libs/Newtonsoft.Json/Linq/JArray.Async.cs index 85e9b28..efa4cdd 100644 --- a/Libs/Newtonsoft.Json/Linq/JArray.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JArray.Async.cs @@ -73,7 +73,7 @@ namespace LC.Newtonsoft.Json.Linq /// If this is null, default load settings will be used. /// The token to monitor for cancellation requests. The default value is . /// A representing the asynchronous load. The property contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { diff --git a/Libs/Newtonsoft.Json/Linq/JArray.cs b/Libs/Newtonsoft.Json/Linq/JArray.cs index 070cbc8..d9fcefa 100644 --- a/Libs/Newtonsoft.Json/Linq/JArray.cs +++ b/Libs/Newtonsoft.Json/Linq/JArray.cs @@ -115,7 +115,7 @@ namespace LC.Newtonsoft.Json.Linq /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . - public new static JArray Load(JsonReader reader, JsonLoadSettings? settings) + public new static JArray Load(JsonReader reader, JsonLoadSettings settings) { if (reader.TokenType == JsonToken.None) { @@ -163,7 +163,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// /// - public new static JArray Parse(string json, JsonLoadSettings? settings) + public new static JArray Parse(string json, JsonLoadSettings settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { @@ -227,7 +227,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets the with the specified key. /// /// The with the specified key. - public override JToken? this[object key] + public override JToken this[object key] { get { @@ -263,19 +263,14 @@ namespace LC.Newtonsoft.Json.Linq set => SetItem(index, value); } - internal override int IndexOfItem(JToken? item) + internal override int IndexOfItem(JToken item) { - if (item == null) - { - return -1; - } - return _values.IndexOfReference(item); } - internal override void MergeItem(object content, JsonMergeSettings? settings) + internal override void MergeItem(object content, JsonMergeSettings settings) { - IEnumerable? a = (IsMultiContent(content) || content is JArray) + IEnumerable a = (IsMultiContent(content) || content is JArray) ? (IEnumerable)content : null; if (a == null) diff --git a/Libs/Newtonsoft.Json/Linq/JConstructor.Async.cs b/Libs/Newtonsoft.Json/Linq/JConstructor.Async.cs index 1feb80f..ff9be4f 100644 --- a/Libs/Newtonsoft.Json/Linq/JConstructor.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JConstructor.Async.cs @@ -43,7 +43,7 @@ namespace LC.Newtonsoft.Json.Linq /// A that represents the asynchronous write operation. public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { - await writer.WriteStartConstructorAsync(_name ?? string.Empty, cancellationToken).ConfigureAwait(false); + await writer.WriteStartConstructorAsync(_name, cancellationToken).ConfigureAwait(false); for (int i = 0; i < _values.Count; i++) { @@ -76,7 +76,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// A that represents the asynchronous load. The /// property returns a that contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { @@ -93,7 +93,7 @@ namespace LC.Newtonsoft.Json.Linq throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JConstructor c = new JConstructor((string)reader.Value!); + JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo, settings); await c.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); diff --git a/Libs/Newtonsoft.Json/Linq/JConstructor.cs b/Libs/Newtonsoft.Json/Linq/JConstructor.cs index 62c7875..2d3f6d3 100644 --- a/Libs/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Libs/Newtonsoft.Json/Linq/JConstructor.cs @@ -36,7 +36,7 @@ namespace LC.Newtonsoft.Json.Linq /// public partial class JConstructor : JContainer { - private string? _name; + private string _name; private readonly List _values = new List(); /// @@ -45,17 +45,12 @@ namespace LC.Newtonsoft.Json.Linq /// The container's children tokens. protected override IList ChildrenTokens => _values; - internal override int IndexOfItem(JToken? item) + internal override int IndexOfItem(JToken item) { - if (item == null) - { - return -1; - } - return _values.IndexOfReference(item); } - internal override void MergeItem(object content, JsonMergeSettings? settings) + internal override void MergeItem(object content, JsonMergeSettings settings) { if (!(content is JConstructor c)) { @@ -73,7 +68,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets or sets the name of this constructor. /// /// The constructor name. - public string? Name + public string Name { get => _name; set => _name = value; @@ -159,7 +154,7 @@ namespace LC.Newtonsoft.Json.Linq /// A collection of which will be used when writing the token. public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { - writer.WriteStartConstructor(_name!); + writer.WriteStartConstructor(_name); int count = _values.Count; for (int i = 0; i < count; i++) @@ -174,7 +169,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets the with the specified key. /// /// The with the specified key. - public override JToken? this[object key] + public override JToken this[object key] { get { @@ -202,7 +197,7 @@ namespace LC.Newtonsoft.Json.Linq internal override int GetDeepHashCode() { - return (_name?.GetHashCode() ?? 0) ^ ContentsHashCode(); + return _name.GetHashCode() ^ ContentsHashCode(); } /// @@ -222,7 +217,7 @@ namespace LC.Newtonsoft.Json.Linq /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . - public new static JConstructor Load(JsonReader reader, JsonLoadSettings? settings) + public new static JConstructor Load(JsonReader reader, JsonLoadSettings settings) { if (reader.TokenType == JsonToken.None) { @@ -239,7 +234,7 @@ namespace LC.Newtonsoft.Json.Linq throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JConstructor c = new JConstructor((string)reader.Value!); + JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo, settings); c.ReadTokenFrom(reader, settings); diff --git a/Libs/Newtonsoft.Json/Linq/JContainer.Async.cs b/Libs/Newtonsoft.Json/Linq/JContainer.Async.cs index 1b3a4e1..dcff69b 100644 --- a/Libs/Newtonsoft.Json/Linq/JContainer.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JContainer.Async.cs @@ -26,7 +26,6 @@ #if HAVE_ASYNC using System; -using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -36,7 +35,7 @@ namespace LC.Newtonsoft.Json.Linq { public abstract partial class JContainer { - internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings? options, CancellationToken cancellationToken = default) + internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings options, CancellationToken cancellationToken = default) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); int startDepth = reader.Depth; @@ -54,11 +53,11 @@ namespace LC.Newtonsoft.Json.Linq } } - private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { - IJsonLineInfo? lineInfo = reader as IJsonLineInfo; + IJsonLineInfo lineInfo = reader as IJsonLineInfo; - JContainer? parent = this; + JContainer parent = this; do { @@ -72,8 +71,6 @@ namespace LC.Newtonsoft.Json.Linq parent = parent.Parent; } - MiscellaneousUtils.Assert(parent != null); - switch (reader.TokenType) { case JsonToken.None: @@ -109,7 +106,7 @@ namespace LC.Newtonsoft.Json.Linq parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(reader.Value!.ToString()); + JConstructor constructor = new JConstructor(reader.Value.ToString()); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; @@ -135,7 +132,7 @@ namespace LC.Newtonsoft.Json.Linq case JsonToken.Comment: if (settings != null && settings.CommentHandling == CommentHandling.Load) { - v = JValue.CreateComment(reader.Value!.ToString()); + v = JValue.CreateComment(reader.Value.ToString()); v.SetLineInfo(lineInfo, settings); parent.Add(v); } @@ -151,7 +148,7 @@ namespace LC.Newtonsoft.Json.Linq parent.Add(v); break; case JsonToken.PropertyName: - JProperty? property = ReadProperty(reader, settings, lineInfo, parent); + JProperty property = ReadProperty(reader, settings, lineInfo, parent); if (property != null) { parent = property; diff --git a/Libs/Newtonsoft.Json/Linq/JContainer.cs b/Libs/Newtonsoft.Json/Linq/JContainer.cs index 8b17d56..84d448b 100644 --- a/Libs/Newtonsoft.Json/Linq/JContainer.cs +++ b/Libs/Newtonsoft.Json/Linq/JContainer.cs @@ -33,13 +33,11 @@ using LC.Newtonsoft.Json.Utilities; using System.Collections; using System.Globalization; using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace LC.Newtonsoft.Json.Linq @@ -57,8 +55,8 @@ namespace LC.Newtonsoft.Json.Linq #endif { #if HAVE_COMPONENT_MODEL - internal ListChangedEventHandler? _listChanged; - internal AddingNewEventHandler? _addingNew; + internal ListChangedEventHandler _listChanged; + internal AddingNewEventHandler _addingNew; /// /// Occurs when the list changes or an item in the list changes. @@ -79,7 +77,7 @@ namespace LC.Newtonsoft.Json.Linq } #endif #if HAVE_INOTIFY_COLLECTION_CHANGED - internal NotifyCollectionChangedEventHandler? _collectionChanged; + internal NotifyCollectionChangedEventHandler _collectionChanged; /// /// Occurs when the items list of the collection has changed, or the collection is reset. @@ -97,7 +95,7 @@ namespace LC.Newtonsoft.Json.Linq /// The container's children tokens. protected abstract IList ChildrenTokens { get; } - private object? _syncRoot; + private object _syncRoot; #if (HAVE_COMPONENT_MODEL || HAVE_INOTIFY_COLLECTION_CHANGED) private bool _busy; #endif @@ -114,11 +112,9 @@ namespace LC.Newtonsoft.Json.Linq int i = 0; foreach (JToken child in other) { - TryAddInternal(i, child, false); + AddInternal(i, child, false); i++; } - - CopyAnnotations(this, other); } internal void CheckReentrancy() @@ -152,7 +148,7 @@ namespace LC.Newtonsoft.Json.Linq /// The instance containing the event data. protected virtual void OnListChanged(ListChangedEventArgs e) { - ListChangedEventHandler? handler = _listChanged; + ListChangedEventHandler handler = _listChanged; if (handler != null) { @@ -175,7 +171,7 @@ namespace LC.Newtonsoft.Json.Linq /// The instance containing the event data. protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { - NotifyCollectionChangedEventHandler? handler = _collectionChanged; + NotifyCollectionChangedEventHandler handler = _collectionChanged; if (handler != null) { @@ -232,7 +228,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// A containing the first child token of the . /// - public override JToken? First + public override JToken First { get { @@ -247,7 +243,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// A containing the last child token of the . /// - public override JToken? Last + public override JToken Last { get { @@ -275,7 +271,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// A containing the child values of this , in document order. /// - public override IEnumerable Values() where T : default + public override IEnumerable Values() { return ChildrenTokens.Convert(); } @@ -318,12 +314,12 @@ namespace LC.Newtonsoft.Json.Linq } } - internal bool IsMultiContent([NotNullWhen(true)]object? content) + internal bool IsMultiContent(object content) { return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[])); } - internal JToken EnsureParentToken(JToken? item, bool skipParentCheck) + internal JToken EnsureParentToken(JToken item, bool skipParentCheck) { if (item == null) { @@ -347,9 +343,9 @@ namespace LC.Newtonsoft.Json.Linq return item; } - internal abstract int IndexOfItem(JToken? item); + internal abstract int IndexOfItem(JToken item); - internal virtual bool InsertItem(int index, JToken? item, bool skipParentCheck) + internal virtual void InsertItem(int index, JToken item, bool skipParentCheck) { IList children = ChildrenTokens; @@ -362,9 +358,9 @@ namespace LC.Newtonsoft.Json.Linq item = EnsureParentToken(item, skipParentCheck); - JToken? previous = (index == 0) ? null : children[index - 1]; + JToken previous = (index == 0) ? null : children[index - 1]; // haven't inserted new token yet so next token is still at the inserting index - JToken? next = (index == children.Count) ? null : children[index]; + JToken next = (index == children.Count) ? null : children[index]; ValidateToken(item, null); @@ -396,8 +392,6 @@ namespace LC.Newtonsoft.Json.Linq OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } #endif - - return true; } internal virtual void RemoveItemAt(int index) @@ -416,8 +410,8 @@ namespace LC.Newtonsoft.Json.Linq CheckReentrancy(); JToken item = children[index]; - JToken? previous = (index == 0) ? null : children[index - 1]; - JToken? next = (index == children.Count - 1) ? null : children[index + 1]; + JToken previous = (index == 0) ? null : children[index - 1]; + JToken next = (index == children.Count - 1) ? null : children[index + 1]; if (previous != null) { @@ -448,16 +442,13 @@ namespace LC.Newtonsoft.Json.Linq #endif } - internal virtual bool RemoveItem(JToken? item) + internal virtual bool RemoveItem(JToken item) { - if (item != null) + int index = IndexOfItem(item); + if (index >= 0) { - int index = IndexOfItem(item); - if (index >= 0) - { - RemoveItemAt(index); - return true; - } + RemoveItemAt(index); + return true; } return false; @@ -468,7 +459,7 @@ namespace LC.Newtonsoft.Json.Linq return ChildrenTokens[index]; } - internal virtual void SetItem(int index, JToken? item) + internal virtual void SetItem(int index, JToken item) { IList children = ChildrenTokens; @@ -494,8 +485,8 @@ namespace LC.Newtonsoft.Json.Linq ValidateToken(item, existing); - JToken? previous = (index == 0) ? null : children[index - 1]; - JToken? next = (index == children.Count - 1) ? null : children[index + 1]; + JToken previous = (index == 0) ? null : children[index - 1]; + JToken next = (index == children.Count - 1) ? null : children[index + 1]; item.Parent = this; @@ -571,7 +562,7 @@ namespace LC.Newtonsoft.Json.Linq SetItem(index, replacement); } - internal virtual bool ContainsItem(JToken? item) + internal virtual bool ContainsItem(JToken item) { return (IndexOfItem(item) != -1); } @@ -603,14 +594,14 @@ namespace LC.Newtonsoft.Json.Linq } } - internal static bool IsTokenUnchanged(JToken currentValue, JToken? newValue) + internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue) { if (currentValue is JValue v1) { - if (newValue == null) + // null will get turned into a JValue of type null + if (v1.Type == JTokenType.Null && newValue == null) { - // null will get turned into a JValue of type null - return v1.Type == JTokenType.Null; + return true; } return v1.Equals(newValue); @@ -619,7 +610,7 @@ namespace LC.Newtonsoft.Json.Linq return false; } - internal virtual void ValidateToken(JToken o, JToken? existing) + internal virtual void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); @@ -633,31 +624,26 @@ namespace LC.Newtonsoft.Json.Linq /// Adds the specified content as children of this . /// /// The content to be added. - public virtual void Add(object? content) + public virtual void Add(object content) { - TryAddInternal(ChildrenTokens.Count, content, false); - } - - internal bool TryAdd(object? content) - { - return TryAddInternal(ChildrenTokens.Count, content, false); + AddInternal(ChildrenTokens.Count, content, false); } internal void AddAndSkipParentCheck(JToken token) { - TryAddInternal(ChildrenTokens.Count, token, true); + AddInternal(ChildrenTokens.Count, token, true); } /// /// Adds the specified content as the first children of this . /// /// The content to be added. - public void AddFirst(object? content) + public void AddFirst(object content) { - TryAddInternal(0, content, false); + AddInternal(0, content, false); } - internal bool TryAddInternal(int index, object? content, bool skipParentCheck) + internal void AddInternal(int index, object content, bool skipParentCheck) { if (IsMultiContent(content)) { @@ -666,21 +652,19 @@ namespace LC.Newtonsoft.Json.Linq int multiIndex = index; foreach (object c in enumerable) { - TryAddInternal(multiIndex, c, skipParentCheck); + AddInternal(multiIndex, c, skipParentCheck); multiIndex++; } - - return true; } else { JToken item = CreateFromContent(content); - return InsertItem(index, item, skipParentCheck); + InsertItem(index, item, skipParentCheck); } } - internal static JToken CreateFromContent(object? content) + internal static JToken CreateFromContent(object content) { if (content is JToken token) { @@ -717,7 +701,7 @@ namespace LC.Newtonsoft.Json.Linq ClearItems(); } - internal abstract void MergeItem(object content, JsonMergeSettings? settings); + internal abstract void MergeItem(object content, JsonMergeSettings settings); /// /// Merge the specified content into this . @@ -725,7 +709,7 @@ namespace LC.Newtonsoft.Json.Linq /// The content to be merged. public void Merge(object content) { - MergeItem(content, null); + MergeItem(content, new JsonMergeSettings()); } /// @@ -733,12 +717,12 @@ namespace LC.Newtonsoft.Json.Linq /// /// The content to be merged. /// The used to merge the content. - public void Merge(object content, JsonMergeSettings? settings) + public void Merge(object content, JsonMergeSettings settings) { MergeItem(content, settings); } - internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings? options) + internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings options) { int startDepth = reader.Depth; @@ -757,12 +741,12 @@ namespace LC.Newtonsoft.Json.Linq } } - internal void ReadContentFrom(JsonReader r, JsonLoadSettings? settings) + internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) { ValidationUtils.ArgumentNotNull(r, nameof(r)); - IJsonLineInfo? lineInfo = r as IJsonLineInfo; + IJsonLineInfo lineInfo = r as IJsonLineInfo; - JContainer? parent = this; + JContainer parent = this; do { @@ -776,8 +760,6 @@ namespace LC.Newtonsoft.Json.Linq parent = parent.Parent; } - MiscellaneousUtils.Assert(parent != null); - switch (r.TokenType) { case JsonToken.None: @@ -813,7 +795,7 @@ namespace LC.Newtonsoft.Json.Linq parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(r.Value!.ToString()); + JConstructor constructor = new JConstructor(r.Value.ToString()); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; @@ -839,7 +821,7 @@ namespace LC.Newtonsoft.Json.Linq case JsonToken.Comment: if (settings != null && settings.CommentHandling == CommentHandling.Load) { - v = JValue.CreateComment(r.Value!.ToString()); + v = JValue.CreateComment(r.Value.ToString()); v.SetLineInfo(lineInfo, settings); parent.Add(v); } @@ -855,7 +837,7 @@ namespace LC.Newtonsoft.Json.Linq parent.Add(v); break; case JsonToken.PropertyName: - JProperty? property = ReadProperty(r, settings, lineInfo, parent); + JProperty property = ReadProperty(r, settings, lineInfo, parent); if (property != null) { parent = property; @@ -871,13 +853,13 @@ namespace LC.Newtonsoft.Json.Linq } while (r.Read()); } - private static JProperty? ReadProperty(JsonReader r, JsonLoadSettings? settings, IJsonLineInfo? lineInfo, JContainer parent) + private static JProperty ReadProperty(JsonReader r, JsonLoadSettings settings, IJsonLineInfo lineInfo, JContainer parent) { DuplicatePropertyNameHandling duplicatePropertyNameHandling = settings?.DuplicatePropertyNameHandling ?? DuplicatePropertyNameHandling.Replace; JObject parentObject = (JObject)parent; - string propertyName = r.Value!.ToString(); - JProperty? existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal); + string propertyName = r.Value.ToString(); + JProperty existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal); if (existingPropertyWithName != null) { if (duplicatePropertyNameHandling == DuplicatePropertyNameHandling.Ignore) @@ -921,9 +903,9 @@ namespace LC.Newtonsoft.Json.Linq return string.Empty; } - PropertyDescriptorCollection? ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) + PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { - ICustomTypeDescriptor? d = First as ICustomTypeDescriptor; + ICustomTypeDescriptor d = First as ICustomTypeDescriptor; return d?.GetProperties(); } #endif @@ -980,7 +962,7 @@ namespace LC.Newtonsoft.Json.Linq } #endregion - private JToken? EnsureValue(object value) + private JToken EnsureValue(object value) { if (value == null) { @@ -1126,7 +1108,7 @@ namespace LC.Newtonsoft.Json.Linq ListSortDirection IBindingList.SortDirection => ListSortDirection.Ascending; - PropertyDescriptor? IBindingList.SortProperty => null; + PropertyDescriptor IBindingList.SortProperty => null; bool IBindingList.SupportsChangeNotification => true; @@ -1136,9 +1118,9 @@ namespace LC.Newtonsoft.Json.Linq #endif #endregion - internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings? settings) + internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings settings) { - switch (settings?.MergeArrayHandling ?? MergeArrayHandling.Concat) + switch (settings.MergeArrayHandling) { case MergeArrayHandling.Concat: foreach (JToken item in content) @@ -1175,10 +1157,6 @@ namespace LC.Newtonsoft.Json.Linq #endif break; case MergeArrayHandling.Replace: - if (target == content) - { - break; - } target.ClearItems(); foreach (JToken item in content) { @@ -1191,7 +1169,7 @@ namespace LC.Newtonsoft.Json.Linq { if (i < target.Count) { - JToken? sourceItem = target[i]; + JToken sourceItem = target[i]; if (sourceItem is JContainer existingContainer) { diff --git a/Libs/Newtonsoft.Json/Linq/JEnumerable.cs b/Libs/Newtonsoft.Json/Linq/JEnumerable.cs index 9bd3a49..8d4665e 100644 --- a/Libs/Newtonsoft.Json/Linq/JEnumerable.cs +++ b/Libs/Newtonsoft.Json/Linq/JEnumerable.cs @@ -88,7 +88,7 @@ namespace LC.Newtonsoft.Json.Linq return JEnumerable.Empty; } - return new JEnumerable(_enumerable.Values(key)!); + return new JEnumerable(_enumerable.Values(key)); } } diff --git a/Libs/Newtonsoft.Json/Linq/JObject.Async.cs b/Libs/Newtonsoft.Json/Linq/JObject.Async.cs index 0c5d6f9..35b7d63 100644 --- a/Libs/Newtonsoft.Json/Linq/JObject.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JObject.Async.cs @@ -97,7 +97,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// A that represents the asynchronous load. The /// property returns a that contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); diff --git a/Libs/Newtonsoft.Json/Linq/JObject.cs b/Libs/Newtonsoft.Json/Linq/JObject.cs index 0e63fcf..f788c8b 100644 --- a/Libs/Newtonsoft.Json/Linq/JObject.cs +++ b/Libs/Newtonsoft.Json/Linq/JObject.cs @@ -37,8 +37,6 @@ using System.Linq.Expressions; using System.IO; using LC.Newtonsoft.Json.Utilities; using System.Globalization; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -53,7 +51,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// /// - public partial class JObject : JContainer, IDictionary, INotifyPropertyChanged + public partial class JObject : JContainer, IDictionary, INotifyPropertyChanged #if HAVE_COMPONENT_MODEL , ICustomTypeDescriptor #endif @@ -72,13 +70,13 @@ namespace LC.Newtonsoft.Json.Linq /// /// Occurs when a property value changes. /// - public event PropertyChangedEventHandler? PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; #if HAVE_INOTIFY_PROPERTY_CHANGING /// /// Occurs when a property value is changing. /// - public event PropertyChangingEventHandler? PropertyChanging; + public event PropertyChangingEventHandler PropertyChanging; #endif /// @@ -125,28 +123,23 @@ namespace LC.Newtonsoft.Json.Linq return _properties.Compare(t._properties); } - internal override int IndexOfItem(JToken? item) + internal override int IndexOfItem(JToken item) { - if (item == null) - { - return -1; - } - return _properties.IndexOfReference(item); } - internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) + internal override void InsertItem(int index, JToken item, bool skipParentCheck) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) { - return false; + return; } - return base.InsertItem(index, item, skipParentCheck); + base.InsertItem(index, item, skipParentCheck); } - internal override void ValidateToken(JToken o, JToken? existing) + internal override void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); @@ -173,16 +166,16 @@ namespace LC.Newtonsoft.Json.Linq } } - internal override void MergeItem(object content, JsonMergeSettings? settings) + internal override void MergeItem(object content, JsonMergeSettings settings) { if (!(content is JObject o)) { return; } - foreach (KeyValuePair contentItem in o) + foreach (KeyValuePair contentItem in o) { - JProperty? existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal); + JProperty existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal); if (existingProperty == null) { @@ -269,7 +262,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The property name. /// A with the specified name or null. - public JProperty? Property(string name) + public JProperty Property(string name) { return Property(name, StringComparison.Ordinal); } @@ -282,14 +275,14 @@ namespace LC.Newtonsoft.Json.Linq /// The property name. /// One of the enumeration values that specifies how the strings will be compared. /// A matched with the specified name or null. - public JProperty? Property(string name, StringComparison comparison) + public JProperty Property(string name, StringComparison comparison) { if (name == null) { return null; } - if (_properties.TryGetValue(name, out JToken? property)) + if (_properties.TryGetValue(name, out JToken property)) { return (JProperty)property; } @@ -323,7 +316,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets the with the specified key. /// /// The with the specified key. - public override JToken? this[object key] + public override JToken this[object key] { get { @@ -353,29 +346,29 @@ namespace LC.Newtonsoft.Json.Linq /// Gets or sets the with the specified property name. /// /// - public JToken? this[string propertyName] + public JToken this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); - JProperty? property = Property(propertyName, StringComparison.Ordinal); + JProperty property = Property(propertyName, StringComparison.Ordinal); return property?.Value; } set { - JProperty? property = Property(propertyName, StringComparison.Ordinal); + JProperty property = Property(propertyName, StringComparison.Ordinal); if (property != null) { - property.Value = value!; + property.Value = value; } else { #if HAVE_INOTIFY_PROPERTY_CHANGING OnPropertyChanging(propertyName); #endif - Add(propertyName, value); + Add(new JProperty(propertyName, value)); OnPropertyChanged(propertyName); } } @@ -404,7 +397,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// is not valid JSON. /// - public new static JObject Load(JsonReader reader, JsonLoadSettings? settings) + public new static JObject Load(JsonReader reader, JsonLoadSettings settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -460,7 +453,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// /// - public new static JObject Parse(string json, JsonLoadSettings? settings) + public new static JObject Parse(string json, JsonLoadSettings settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { @@ -495,7 +488,7 @@ namespace LC.Newtonsoft.Json.Linq { JToken token = FromObjectInternal(o, jsonSerializer); - if (token.Type != JTokenType.Object) + if (token != null && token.Type != JTokenType.Object) { throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); } @@ -525,7 +518,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// Name of the property. /// The with the specified property name. - public JToken? GetValue(string? propertyName) + public JToken GetValue(string propertyName) { return GetValue(propertyName, StringComparison.Ordinal); } @@ -538,7 +531,7 @@ namespace LC.Newtonsoft.Json.Linq /// Name of the property. /// One of the enumeration values that specifies how the strings will be compared. /// The with the specified property name. - public JToken? GetValue(string? propertyName, StringComparison comparison) + public JToken GetValue(string propertyName, StringComparison comparison) { if (propertyName == null) { @@ -560,7 +553,7 @@ namespace LC.Newtonsoft.Json.Linq /// The value. /// One of the enumeration values that specifies how the strings will be compared. /// true if a value was successfully retrieved; otherwise, false. - public bool TryGetValue(string propertyName, StringComparison comparison, [NotNullWhen(true)]out JToken? value) + public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value) { value = GetValue(propertyName, comparison); return (value != null); @@ -572,7 +565,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// Name of the property. /// The value. - public void Add(string propertyName, JToken? value) + public void Add(string propertyName, JToken value) { Add(new JProperty(propertyName, value)); } @@ -589,7 +582,7 @@ namespace LC.Newtonsoft.Json.Linq return _properties.Contains(propertyName); } - ICollection IDictionary.Keys => _properties.Keys; + ICollection IDictionary.Keys => _properties.Keys; /// /// Removes the property with the specified name. @@ -598,7 +591,7 @@ namespace LC.Newtonsoft.Json.Linq /// true if item was successfully removed; otherwise, false. public bool Remove(string propertyName) { - JProperty? property = Property(propertyName, StringComparison.Ordinal); + JProperty property = Property(propertyName, StringComparison.Ordinal); if (property == null) { return false; @@ -614,9 +607,9 @@ namespace LC.Newtonsoft.Json.Linq /// Name of the property. /// The value. /// true if a value was successfully retrieved; otherwise, false. - public bool TryGetValue(string propertyName, [NotNullWhen(true)]out JToken? value) + public bool TryGetValue(string propertyName, out JToken value) { - JProperty? property = Property(propertyName, StringComparison.Ordinal); + JProperty property = Property(propertyName, StringComparison.Ordinal); if (property == null) { value = null; @@ -627,24 +620,24 @@ namespace LC.Newtonsoft.Json.Linq return true; } - ICollection IDictionary.Values => throw new NotImplementedException(); + ICollection IDictionary.Values => throw new NotImplementedException(); #endregion #region ICollection> Members - void ICollection>.Add(KeyValuePair item) + void ICollection>.Add(KeyValuePair item) { Add(new JProperty(item.Key, item.Value)); } - void ICollection>.Clear() + void ICollection>.Clear() { RemoveAll(); } - bool ICollection>.Contains(KeyValuePair item) + bool ICollection>.Contains(KeyValuePair item) { - JProperty? property = Property(item.Key, StringComparison.Ordinal); + JProperty property = Property(item.Key, StringComparison.Ordinal); if (property == null) { return false; @@ -653,7 +646,7 @@ namespace LC.Newtonsoft.Json.Linq return (property.Value == item.Value); } - void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { if (array == null) { @@ -675,16 +668,16 @@ namespace LC.Newtonsoft.Json.Linq int index = 0; foreach (JProperty property in _properties) { - array[arrayIndex + index] = new KeyValuePair(property.Name, property.Value); + array[arrayIndex + index] = new KeyValuePair(property.Name, property.Value); index++; } } - bool ICollection>.IsReadOnly => false; + bool ICollection>.IsReadOnly => false; - bool ICollection>.Remove(KeyValuePair item) + bool ICollection>.Remove(KeyValuePair item) { - if (!((ICollection>)this).Contains(item)) + if (!((ICollection>)this).Contains(item)) { return false; } @@ -705,11 +698,11 @@ namespace LC.Newtonsoft.Json.Linq /// /// A that can be used to iterate through the collection. /// - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { foreach (JProperty property in _properties) { - yield return new KeyValuePair(property.Name, property.Value); + yield return new KeyValuePair(property.Name, property.Value); } } @@ -744,15 +737,14 @@ namespace LC.Newtonsoft.Json.Linq PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { - PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count]; - int i = 0; - foreach (KeyValuePair propertyValue in this) + PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); + + foreach (KeyValuePair propertyValue in this) { - propertiesArray[i] = new JPropertyDescriptor(propertyValue.Key); - i++; + descriptors.Add(new JPropertyDescriptor(propertyValue.Key)); } - return new PropertyDescriptorCollection(propertiesArray); + return descriptors; } AttributeCollection ICustomTypeDescriptor.GetAttributes() @@ -760,12 +752,12 @@ namespace LC.Newtonsoft.Json.Linq return AttributeCollection.Empty; } - string? ICustomTypeDescriptor.GetClassName() + string ICustomTypeDescriptor.GetClassName() { return null; } - string? ICustomTypeDescriptor.GetComponentName() + string ICustomTypeDescriptor.GetComponentName() { return null; } @@ -775,17 +767,17 @@ namespace LC.Newtonsoft.Json.Linq return new TypeConverter(); } - EventDescriptor? ICustomTypeDescriptor.GetDefaultEvent() + EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } - PropertyDescriptor? ICustomTypeDescriptor.GetDefaultProperty() + PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) + object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } @@ -800,7 +792,7 @@ namespace LC.Newtonsoft.Json.Linq return EventDescriptorCollection.Empty; } - object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) + object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { if (pd is JPropertyDescriptor) { @@ -828,7 +820,7 @@ namespace LC.Newtonsoft.Json.Linq private class JObjectDynamicProxy : DynamicProxy { - public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object? result) + public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) { // result can be null result = instance[binder.Name]; diff --git a/Libs/Newtonsoft.Json/Linq/JProperty.Async.cs b/Libs/Newtonsoft.Json/Linq/JProperty.Async.cs index 3047996..f7a7d71 100644 --- a/Libs/Newtonsoft.Json/Linq/JProperty.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JProperty.Async.cs @@ -88,7 +88,7 @@ namespace LC.Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. The default value is . /// A representing the asynchronous creation. The /// property returns a that contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { @@ -105,7 +105,7 @@ namespace LC.Newtonsoft.Json.Linq throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JProperty p = new JProperty((string)reader.Value!); + JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo, settings); await p.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); diff --git a/Libs/Newtonsoft.Json/Linq/JProperty.cs b/Libs/Newtonsoft.Json/Linq/JProperty.cs index 5745e2c..adb33d0 100644 --- a/Libs/Newtonsoft.Json/Linq/JProperty.cs +++ b/Libs/Newtonsoft.Json/Linq/JProperty.cs @@ -40,7 +40,7 @@ namespace LC.Newtonsoft.Json.Linq #region JPropertyList private class JPropertyList : IList { - internal JToken? _token; + internal JToken _token; public IEnumerator GetEnumerator() { @@ -115,24 +115,13 @@ namespace LC.Newtonsoft.Json.Linq public JToken this[int index] { - get - { - if (index != 0) - { - throw new IndexOutOfRangeException(); - } - - MiscellaneousUtils.Assert(_token != null); - return _token; - } + get => (index == 0) ? _token : null; set { - if (index != 0) + if (index == 0) { - throw new IndexOutOfRangeException(); + _token = value; } - - _token = value; } } } @@ -164,7 +153,7 @@ namespace LC.Newtonsoft.Json.Linq public JToken Value { [DebuggerStepThrough] - get { return _content._token!; } + get { return _content._token; } set { CheckReentrancy(); @@ -202,7 +191,7 @@ namespace LC.Newtonsoft.Json.Linq return Value; } - internal override void SetItem(int index, JToken? item) + internal override void SetItem(int index, JToken item) { if (index != 0) { @@ -214,14 +203,14 @@ namespace LC.Newtonsoft.Json.Linq return; } - ((JObject?)Parent)?.InternalPropertyChanging(this); + ((JObject)Parent)?.InternalPropertyChanging(this); base.SetItem(0, item); - ((JObject?)Parent)?.InternalPropertyChanged(this); + ((JObject)Parent)?.InternalPropertyChanged(this); } - internal override bool RemoveItem(JToken? item) + internal override bool RemoveItem(JToken item) { throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } @@ -231,22 +220,17 @@ namespace LC.Newtonsoft.Json.Linq throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } - internal override int IndexOfItem(JToken? item) + internal override int IndexOfItem(JToken item) { - if (item == null) - { - return -1; - } - return _content.IndexOf(item); } - internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) + internal override void InsertItem(int index, JToken item, bool skipParentCheck) { // don't add comments to JProperty if (item != null && item.Type == JTokenType.Comment) { - return false; + return; } if (Value != null) @@ -254,17 +238,17 @@ namespace LC.Newtonsoft.Json.Linq throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } - return base.InsertItem(0, item, false); + base.InsertItem(0, item, false); } - internal override bool ContainsItem(JToken? item) + internal override bool ContainsItem(JToken item) { return (Value == item); } - internal override void MergeItem(object content, JsonMergeSettings? settings) + internal override void MergeItem(object content, JsonMergeSettings settings) { - JToken? value = (content as JProperty)?.Value; + JToken value = (content as JProperty)?.Value; if (value != null && value.Type != JTokenType.Null) { @@ -320,7 +304,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The property name. /// The property content. - public JProperty(string name, object? content) + public JProperty(string name, object content) { ValidationUtils.ArgumentNotNull(name, nameof(name)); @@ -373,7 +357,7 @@ namespace LC.Newtonsoft.Json.Linq /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . - public new static JProperty Load(JsonReader reader, JsonLoadSettings? settings) + public new static JProperty Load(JsonReader reader, JsonLoadSettings settings) { if (reader.TokenType == JsonToken.None) { @@ -390,7 +374,7 @@ namespace LC.Newtonsoft.Json.Linq throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JProperty p = new JProperty((string)reader.Value!); + JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo, settings); p.ReadTokenFrom(reader, settings); diff --git a/Libs/Newtonsoft.Json/Linq/JPropertyDescriptor.cs b/Libs/Newtonsoft.Json/Linq/JPropertyDescriptor.cs index 2ebbe94..54cdf35 100644 --- a/Libs/Newtonsoft.Json/Linq/JPropertyDescriptor.cs +++ b/Libs/Newtonsoft.Json/Linq/JPropertyDescriptor.cs @@ -67,7 +67,7 @@ namespace LC.Newtonsoft.Json.Linq /// The value of a property for a given component. /// /// The component with the property for which to retrieve the value. - public override object? GetValue(object component) + public override object GetValue(object component) { return (component as JObject)?[Name]; } diff --git a/Libs/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs b/Libs/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs index 61de800..6b15870 100644 --- a/Libs/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs +++ b/Libs/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs @@ -26,8 +26,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using LC.Newtonsoft.Json.Utilities; namespace LC.Newtonsoft.Json.Linq @@ -36,7 +34,7 @@ namespace LC.Newtonsoft.Json.Linq { private static readonly IEqualityComparer Comparer = StringComparer.Ordinal; - private Dictionary? _dictionary; + private Dictionary _dictionary; public JPropertyKeyedCollection() : base(new List()) { @@ -45,7 +43,7 @@ namespace LC.Newtonsoft.Json.Linq private void AddKey(string key, JToken item) { EnsureDictionary(); - _dictionary![key] = item; + _dictionary[key] = item; } protected void ChangeItemKey(JToken item, string newKey) @@ -191,7 +189,7 @@ namespace LC.Newtonsoft.Json.Linq } } - public bool TryGetValue(string key, [NotNullWhen(true)]out JToken? value) + public bool TryGetValue(string key, out JToken value) { if (_dictionary == null) { @@ -207,7 +205,7 @@ namespace LC.Newtonsoft.Json.Linq get { EnsureDictionary(); - return _dictionary!.Keys; + return _dictionary.Keys; } } @@ -216,7 +214,7 @@ namespace LC.Newtonsoft.Json.Linq get { EnsureDictionary(); - return _dictionary!.Values; + return _dictionary.Values; } } @@ -234,8 +232,8 @@ namespace LC.Newtonsoft.Json.Linq // dictionaries in JavaScript aren't ordered // ignore order when comparing properties - Dictionary? d1 = _dictionary; - Dictionary? d2 = other._dictionary; + Dictionary d1 = _dictionary; + Dictionary d2 = other._dictionary; if (d1 == null && d2 == null) { @@ -244,7 +242,7 @@ namespace LC.Newtonsoft.Json.Linq if (d1 == null) { - return (d2!.Count == 0); + return (d2.Count == 0); } if (d2 == null) diff --git a/Libs/Newtonsoft.Json/Linq/JRaw.cs b/Libs/Newtonsoft.Json/Linq/JRaw.cs index cf3790b..2ffca15 100644 --- a/Libs/Newtonsoft.Json/Linq/JRaw.cs +++ b/Libs/Newtonsoft.Json/Linq/JRaw.cs @@ -46,7 +46,7 @@ namespace LC.Newtonsoft.Json.Linq /// Initializes a new instance of the class. /// /// The raw json. - public JRaw(object? rawJson) + public JRaw(object rawJson) : base(rawJson, JTokenType.Raw) { } diff --git a/Libs/Newtonsoft.Json/Linq/JToken.Async.cs b/Libs/Newtonsoft.Json/Linq/JToken.Async.cs index e18a6aa..72a9ce6 100644 --- a/Libs/Newtonsoft.Json/Linq/JToken.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JToken.Async.cs @@ -89,7 +89,7 @@ namespace LC.Newtonsoft.Json.Linq /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -101,7 +101,7 @@ namespace LC.Newtonsoft.Json.Linq } } - IJsonLineInfo? lineInfo = reader as IJsonLineInfo; + IJsonLineInfo lineInfo = reader as IJsonLineInfo; switch (reader.TokenType) { @@ -123,7 +123,7 @@ namespace LC.Newtonsoft.Json.Linq v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Comment: - v = JValue.CreateComment(reader.Value?.ToString()); + v = JValue.CreateComment(reader.Value.ToString()); v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Null: @@ -168,7 +168,7 @@ namespace LC.Newtonsoft.Json.Linq /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) + public static Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { return ReadFromAsync(reader, settings, cancellationToken); } diff --git a/Libs/Newtonsoft.Json/Linq/JToken.cs b/Libs/Newtonsoft.Json/Linq/JToken.cs index bb480af..e055140 100644 --- a/Libs/Newtonsoft.Json/Linq/JToken.cs +++ b/Libs/Newtonsoft.Json/Linq/JToken.cs @@ -38,12 +38,11 @@ using LC.Newtonsoft.Json.Utilities; using System.Diagnostics; using System.Globalization; using System.Collections; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace LC.Newtonsoft.Json.Linq @@ -59,12 +58,12 @@ namespace LC.Newtonsoft.Json.Linq , IDynamicMetaObjectProvider #endif { - private static JTokenEqualityComparer? _equalityComparer; + private static JTokenEqualityComparer _equalityComparer; - private JContainer? _parent; - private JToken? _previous; - private JToken? _next; - private object? _annotations; + private JContainer _parent; + private JToken _previous; + private JToken _next; + private object _annotations; private static readonly JTokenType[] BooleanTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean }; private static readonly JTokenType[] NumberTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean }; @@ -100,7 +99,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets or sets the parent. /// /// The parent. - public JContainer? Parent + public JContainer Parent { [DebuggerStepThrough] get { return _parent; } @@ -115,7 +114,7 @@ namespace LC.Newtonsoft.Json.Linq { get { - JContainer? parent = Parent; + JContainer parent = Parent; if (parent == null) { return this; @@ -153,7 +152,7 @@ namespace LC.Newtonsoft.Json.Linq /// The first to compare. /// The second to compare. /// true if the tokens are equal; otherwise false. - public static bool DeepEquals(JToken? t1, JToken? t2) + public static bool DeepEquals(JToken t1, JToken t2) { return (t1 == t2 || (t1 != null && t2 != null && t1.DeepEquals(t2))); } @@ -162,7 +161,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets the next sibling token of this node. /// /// The that contains the next sibling token. - public JToken? Next + public JToken Next { get => _next; internal set => _next = value; @@ -172,7 +171,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets the previous sibling token of this node. /// /// The that contains the previous sibling token. - public JToken? Previous + public JToken Previous { get => _previous; internal set => _previous = value; @@ -191,8 +190,8 @@ namespace LC.Newtonsoft.Json.Linq } List positions = new List(); - JToken? previous = null; - for (JToken? current = this; current != null; current = current.Parent) + JToken previous = null; + for (JToken current = this; current != null; current = current.Parent) { switch (current.Type) { @@ -232,7 +231,7 @@ namespace LC.Newtonsoft.Json.Linq /// Adds the specified content immediately after this token. /// /// A content object that contains simple content or a collection of content objects to be added after this token. - public void AddAfterSelf(object? content) + public void AddAfterSelf(object content) { if (_parent == null) { @@ -240,14 +239,14 @@ namespace LC.Newtonsoft.Json.Linq } int index = _parent.IndexOfItem(this); - _parent.TryAddInternal(index + 1, content, false); + _parent.AddInternal(index + 1, content, false); } /// /// Adds the specified content immediately before this token. /// /// A content object that contains simple content or a collection of content objects to be added before this token. - public void AddBeforeSelf(object? content) + public void AddBeforeSelf(object content) { if (_parent == null) { @@ -255,7 +254,7 @@ namespace LC.Newtonsoft.Json.Linq } int index = _parent.IndexOfItem(this); - _parent.TryAddInternal(index, content, false); + _parent.AddInternal(index, content, false); } /// @@ -278,7 +277,7 @@ namespace LC.Newtonsoft.Json.Linq internal IEnumerable GetAncestors(bool self) { - for (JToken? current = self ? this : Parent; current != null; current = current.Parent) + for (JToken current = self ? this : Parent; current != null; current = current.Parent) { yield return current; } @@ -295,7 +294,7 @@ namespace LC.Newtonsoft.Json.Linq yield break; } - for (JToken? o = Next; o != null; o = o.Next) + for (JToken o = Next; o != null; o = o.Next) { yield return o; } @@ -307,12 +306,7 @@ namespace LC.Newtonsoft.Json.Linq /// A collection of the sibling tokens before this token, in document order. public IEnumerable BeforeSelf() { - if (Parent == null) - { - yield break; - } - - for (JToken? o = Parent.First; o != this && o != null; o = o.Next) + for (JToken o = Parent.First; o != this; o = o.Next) { yield return o; } @@ -322,7 +316,7 @@ namespace LC.Newtonsoft.Json.Linq /// Gets the with the specified key. /// /// The with the specified key. - public virtual JToken? this[object key] + public virtual JToken this[object key] { get => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); set => throw new InvalidOperationException("Cannot set child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); @@ -334,9 +328,9 @@ namespace LC.Newtonsoft.Json.Linq /// The type to convert the token to. /// The token key. /// The converted token value. - public virtual T? Value(object key) + public virtual T Value(object key) { - JToken? token = this[key]; + JToken token = this[key]; // null check to fix MonoTouch issue - https://github.com/dolbz/Newtonsoft.Json/commit/a24e3062846b30ee505f3271ac08862bb471b822 return token == null ? default : Extensions.Convert(token); @@ -346,13 +340,13 @@ namespace LC.Newtonsoft.Json.Linq /// Get the first child token of this token. /// /// A containing the first child token of the . - public virtual JToken? First => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); + public virtual JToken First => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); /// /// Get the last child token of this token. /// /// A containing the last child token of the . - public virtual JToken? Last => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); + public virtual JToken Last => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); /// /// Returns a collection of the child tokens of this token, in document order. @@ -378,7 +372,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The type to convert the values to. /// A containing the child values of this , in document order. - public virtual IEnumerable Values() + public virtual IEnumerable Values() { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); } @@ -420,10 +414,6 @@ namespace LC.Newtonsoft.Json.Linq /// /// Returns the indented JSON for this token. /// - /// - /// ToString() returns a non-JSON string value for tokens with a type of . - /// If you want the JSON for all token types then you should use . - /// /// /// The indented JSON for this token. /// @@ -451,7 +441,7 @@ namespace LC.Newtonsoft.Json.Linq } } - private static JValue? EnsureValue(JToken value) + private static JValue EnsureValue(JToken value) { if (value == null) { @@ -463,7 +453,7 @@ namespace LC.Newtonsoft.Json.Linq value = property.Value; } - JValue? v = value as JValue; + JValue v = value as JValue; return v; } @@ -485,7 +475,7 @@ namespace LC.Newtonsoft.Json.Linq return (Array.IndexOf(validTypes, o.Type) != -1) || (nullable && (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined)); } - #region Cast from operators +#region Cast from operators /// /// Performs an explicit conversion from to . /// @@ -493,7 +483,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator bool(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BooleanTypes, false)) { throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -517,7 +507,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator DateTimeOffset(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, false)) { throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -542,14 +532,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator bool?(JToken? value) + public static explicit operator bool?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BooleanTypes, true)) { throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -572,7 +562,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator long(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -593,14 +583,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator DateTime?(JToken? value) + public static explicit operator DateTime?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, true)) { throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -622,14 +612,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator DateTimeOffset?(JToken? value) + public static explicit operator DateTimeOffset?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, true)) { throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -658,14 +648,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator decimal?(JToken? value) + public static explicit operator decimal?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -686,14 +676,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator double?(JToken? value) + public static explicit operator double?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -714,14 +704,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator char?(JToken? value) + public static explicit operator char?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, CharTypes, true)) { throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -744,7 +734,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator int(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -767,7 +757,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator short(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -791,7 +781,7 @@ namespace LC.Newtonsoft.Json.Linq [CLSCompliant(false)] public static explicit operator ushort(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -815,7 +805,7 @@ namespace LC.Newtonsoft.Json.Linq [CLSCompliant(false)] public static explicit operator char(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, CharTypes, false)) { throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -838,7 +828,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator byte(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -862,7 +852,7 @@ namespace LC.Newtonsoft.Json.Linq [CLSCompliant(false)] public static explicit operator sbyte(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -883,14 +873,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator int?(JToken? value) + public static explicit operator int?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -911,14 +901,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator short?(JToken? value) + public static explicit operator short?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -940,14 +930,14 @@ namespace LC.Newtonsoft.Json.Linq /// The value. /// The result of the conversion. [CLSCompliant(false)] - public static explicit operator ushort?(JToken? value) + public static explicit operator ushort?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -968,14 +958,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator byte?(JToken? value) + public static explicit operator byte?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -997,14 +987,14 @@ namespace LC.Newtonsoft.Json.Linq /// The value. /// The result of the conversion. [CLSCompliant(false)] - public static explicit operator sbyte?(JToken? value) + public static explicit operator sbyte?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1027,7 +1017,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator DateTime(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, false)) { throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1048,14 +1038,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator long?(JToken? value) + public static explicit operator long?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1076,14 +1066,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator float?(JToken? value) + public static explicit operator float?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1106,7 +1096,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator decimal(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1128,14 +1118,14 @@ namespace LC.Newtonsoft.Json.Linq /// The value. /// The result of the conversion. [CLSCompliant(false)] - public static explicit operator uint?(JToken? value) + public static explicit operator uint?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1157,14 +1147,14 @@ namespace LC.Newtonsoft.Json.Linq /// The value. /// The result of the conversion. [CLSCompliant(false)] - public static explicit operator ulong?(JToken? value) + public static explicit operator ulong?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1187,7 +1177,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator double(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1210,7 +1200,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator float(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1231,14 +1221,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator string?(JToken? value) + public static explicit operator string(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, StringTypes, true)) { throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1272,7 +1262,7 @@ namespace LC.Newtonsoft.Json.Linq [CLSCompliant(false)] public static explicit operator uint(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1296,7 +1286,7 @@ namespace LC.Newtonsoft.Json.Linq [CLSCompliant(false)] public static explicit operator ulong(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1317,14 +1307,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator byte[]?(JToken? value) + public static explicit operator byte[](JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BytesTypes, false)) { throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1356,7 +1346,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator Guid(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, GuidTypes, false)) { throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1375,14 +1365,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator Guid?(JToken? value) + public static explicit operator Guid?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, GuidTypes, true)) { throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1408,7 +1398,7 @@ namespace LC.Newtonsoft.Json.Linq /// The result of the conversion. public static explicit operator TimeSpan(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, TimeSpanTypes, false)) { throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1422,14 +1412,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator TimeSpan?(JToken? value) + public static explicit operator TimeSpan?(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, TimeSpanTypes, true)) { throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1448,14 +1438,14 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// The result of the conversion. - public static explicit operator Uri?(JToken? value) + public static explicit operator Uri(JToken value) { if (value == null) { return null; } - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, UriTypes, true)) { throw new ArgumentException("Can not convert {0} to Uri.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1472,18 +1462,18 @@ namespace LC.Newtonsoft.Json.Linq #if HAVE_BIG_INTEGER private static BigInteger ToBigInteger(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BigIntegerTypes, false)) { throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); } - return ConvertUtils.ToBigInteger(v.Value!); + return ConvertUtils.ToBigInteger(v.Value); } private static BigInteger? ToBigIntegerNullable(JToken value) { - JValue? v = EnsureValue(value); + JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BigIntegerTypes, true)) { throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1497,9 +1487,9 @@ namespace LC.Newtonsoft.Json.Linq return ConvertUtils.ToBigInteger(v.Value); } #endif - #endregion +#endregion - #region Cast to operators +#region Cast to operators /// /// Performs an implicit conversion from to . /// @@ -1777,7 +1767,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value to create a from. /// The initialized with the specified value. - public static implicit operator JToken(string? value) + public static implicit operator JToken(string value) { return new JValue(value); } @@ -1819,7 +1809,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value to create a from. /// The initialized with the specified value. - public static implicit operator JToken(Uri? value) + public static implicit operator JToken(Uri value) { return new JValue(value); } @@ -1863,7 +1853,7 @@ namespace LC.Newtonsoft.Json.Linq { return new JValue(value); } - #endregion +#endregion IEnumerator IEnumerable.GetEnumerator() { @@ -1877,7 +1867,7 @@ namespace LC.Newtonsoft.Json.Linq internal abstract int GetDeepHashCode(); - IJEnumerable IJEnumerable.this[object key] => this[key]!; + IJEnumerable IJEnumerable.this[object key] => this[key]; /// /// Creates a for this token. @@ -1897,7 +1887,7 @@ namespace LC.Newtonsoft.Json.Linq using (JTokenWriter jsonWriter = new JTokenWriter()) { jsonSerializer.Serialize(jsonWriter, o); - token = jsonWriter.Token!; + token = jsonWriter.Token; } return token; @@ -1929,9 +1919,9 @@ namespace LC.Newtonsoft.Json.Linq /// /// The object type that the token will be deserialized to. /// The new object created from the JSON value. - public T? ToObject() + public T ToObject() { - return (T?)ToObject(typeof(T)); + return (T)ToObject(typeof(T)); } /// @@ -1939,7 +1929,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The object type that the token will be deserialized to. /// The new object created from the JSON value. - public object? ToObject(Type objectType) + public object ToObject(Type objectType) { if (JsonConvert.DefaultSettings == null) { @@ -1957,7 +1947,7 @@ namespace LC.Newtonsoft.Json.Linq catch (Exception ex) { Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); - throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string?)this, enumType.Name), ex); + throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex); } } @@ -2033,13 +2023,13 @@ namespace LC.Newtonsoft.Json.Linq return (DateTimeOffset)this; #endif case PrimitiveTypeCode.String: - return (string?)this; + return (string)this; case PrimitiveTypeCode.GuidNullable: return (Guid?)this; case PrimitiveTypeCode.Guid: return (Guid)this; case PrimitiveTypeCode.Uri: - return (Uri?)this; + return (Uri)this; case PrimitiveTypeCode.TimeSpanNullable: return (TimeSpan?)this; case PrimitiveTypeCode.TimeSpan: @@ -2062,9 +2052,9 @@ namespace LC.Newtonsoft.Json.Linq /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. - public T? ToObject(JsonSerializer jsonSerializer) + public T ToObject(JsonSerializer jsonSerializer) { - return (T?)ToObject(typeof(T), jsonSerializer); + return (T)ToObject(typeof(T), jsonSerializer); } /// @@ -2073,7 +2063,7 @@ namespace LC.Newtonsoft.Json.Linq /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. - public object? ToObject(Type objectType, JsonSerializer jsonSerializer) + public object ToObject(Type objectType, JsonSerializer jsonSerializer) { ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); @@ -2108,7 +2098,7 @@ namespace LC.Newtonsoft.Json.Linq /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static JToken ReadFrom(JsonReader reader, JsonLoadSettings? settings) + public static JToken ReadFrom(JsonReader reader, JsonLoadSettings settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -2133,7 +2123,7 @@ namespace LC.Newtonsoft.Json.Linq throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); } - IJsonLineInfo? lineInfo = reader as IJsonLineInfo; + IJsonLineInfo lineInfo = reader as IJsonLineInfo; switch (reader.TokenType) { @@ -2155,7 +2145,7 @@ namespace LC.Newtonsoft.Json.Linq v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Comment: - v = JValue.CreateComment(reader.Value!.ToString()); + v = JValue.CreateComment(reader.Value.ToString()); v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Null: @@ -2188,7 +2178,7 @@ namespace LC.Newtonsoft.Json.Linq /// The used to load the JSON. /// If this is null, default load settings will be used. /// A populated from the string that contains JSON. - public static JToken Parse(string json, JsonLoadSettings? settings) + public static JToken Parse(string json, JsonLoadSettings settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { @@ -2199,6 +2189,7 @@ namespace LC.Newtonsoft.Json.Linq // Any content encountered here other than a comment will throw in the reader. } + return t; } } @@ -2214,7 +2205,7 @@ namespace LC.Newtonsoft.Json.Linq /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static JToken Load(JsonReader reader, JsonLoadSettings? settings) + public static JToken Load(JsonReader reader, JsonLoadSettings settings) { return ReadFrom(reader, settings); } @@ -2233,7 +2224,7 @@ namespace LC.Newtonsoft.Json.Linq return Load(reader, null); } - internal void SetLineInfo(IJsonLineInfo? lineInfo, JsonLoadSettings? settings) + internal void SetLineInfo(IJsonLineInfo lineInfo, JsonLoadSettings settings) { if (settings != null && settings.LineInfoHandling != LineInfoHandling.Load) { @@ -2274,7 +2265,7 @@ namespace LC.Newtonsoft.Json.Linq { get { - LineInfoAnnotation? annotation = Annotation(); + LineInfoAnnotation annotation = Annotation(); if (annotation != null) { return annotation.LineNumber; @@ -2288,7 +2279,7 @@ namespace LC.Newtonsoft.Json.Linq { get { - LineInfoAnnotation? annotation = Annotation(); + LineInfoAnnotation annotation = Annotation(); if (annotation != null) { return annotation.LinePosition; @@ -2299,48 +2290,31 @@ namespace LC.Newtonsoft.Json.Linq } /// - /// Selects a using a JSONPath expression. Selects the token that matches the object path. + /// Selects a using a JPath expression. Selects the token that matches the object path. /// /// - /// A that contains a JSONPath expression. + /// A that contains a JPath expression. /// /// A , or null. - public JToken? SelectToken(string path) + public JToken SelectToken(string path) { - return SelectToken(path, settings: null); + return SelectToken(path, false); } /// - /// Selects a using a JSONPath expression. Selects the token that matches the object path. + /// Selects a using a JPath expression. Selects the token that matches the object path. /// /// - /// A that contains a JSONPath expression. + /// A that contains a JPath expression. /// /// A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression. /// A . - public JToken? SelectToken(string path, bool errorWhenNoMatch) - { - JsonSelectSettings? settings = errorWhenNoMatch - ? new JsonSelectSettings { ErrorWhenNoMatch = true } - : null; - - return SelectToken(path, settings); - } - - /// - /// Selects a using a JSONPath expression. Selects the token that matches the object path. - /// - /// - /// A that contains a JSONPath expression. - /// - /// The used to select tokens. - /// A . - public JToken? SelectToken(string path, JsonSelectSettings? settings) + public JToken SelectToken(string path, bool errorWhenNoMatch) { JPath p = new JPath(path); - JToken? token = null; - foreach (JToken t in p.Evaluate(this, this, settings)) + JToken token = null; + foreach (JToken t in p.Evaluate(this, this, errorWhenNoMatch)) { if (token != null) { @@ -2354,46 +2328,29 @@ namespace LC.Newtonsoft.Json.Linq } /// - /// Selects a collection of elements using a JSONPath expression. + /// Selects a collection of elements using a JPath expression. /// /// - /// A that contains a JSONPath expression. + /// A that contains a JPath expression. /// /// An of that contains the selected elements. public IEnumerable SelectTokens(string path) { - return SelectTokens(path, settings: null); + return SelectTokens(path, false); } /// - /// Selects a collection of elements using a JSONPath expression. + /// Selects a collection of elements using a JPath expression. /// /// - /// A that contains a JSONPath expression. + /// A that contains a JPath expression. /// /// A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression. /// An of that contains the selected elements. public IEnumerable SelectTokens(string path, bool errorWhenNoMatch) { - JsonSelectSettings? settings = errorWhenNoMatch - ? new JsonSelectSettings { ErrorWhenNoMatch = true } - : null; - - return SelectTokens(path, settings); - } - - /// - /// Selects a collection of elements using a JSONPath expression. - /// - /// - /// A that contains a JSONPath expression. - /// - /// The used to select tokens. - /// An of that contains the selected elements. - public IEnumerable SelectTokens(string path, JsonSelectSettings? settings) - { - var p = new JPath(path); - return p.Evaluate(this, this, settings); + JPath p = new JPath(path); + return p.Evaluate(this, this, errorWhenNoMatch); } #if HAVE_DYNAMIC @@ -2481,7 +2438,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The type of the annotation to retrieve. /// The first annotation object that matches the specified type, or null if no annotation is of the specified type. - public T? Annotation() where T : class + public T Annotation() where T : class { if (_annotations != null) { @@ -2512,7 +2469,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The of the annotation to retrieve. /// The first annotation object that matches the specified type, or null if no annotation is of the specified type. - public object? Annotation(Type type) + public object Annotation(Type type) { if (type == null) { @@ -2638,7 +2595,7 @@ namespace LC.Newtonsoft.Json.Linq { if (_annotations != null) { - if (!(_annotations is object?[] annotations)) + if (!(_annotations is object[] annotations)) { if (_annotations is T) { @@ -2651,7 +2608,7 @@ namespace LC.Newtonsoft.Json.Linq int keepCount = 0; while (index < annotations.Length) { - object? obj2 = annotations[index]; + object obj2 = annotations[index]; if (obj2 == null) { break; @@ -2693,7 +2650,7 @@ namespace LC.Newtonsoft.Json.Linq if (_annotations != null) { - if (!(_annotations is object?[] annotations)) + if (!(_annotations is object[] annotations)) { if (type.IsInstanceOfType(_annotations)) { @@ -2706,7 +2663,7 @@ namespace LC.Newtonsoft.Json.Linq int keepCount = 0; while (index < annotations.Length) { - object? o = annotations[index]; + object o = annotations[index]; if (o == null) { break; @@ -2734,17 +2691,5 @@ namespace LC.Newtonsoft.Json.Linq } } } - - internal void CopyAnnotations(JToken target, JToken source) - { - if (source._annotations is object[] annotations) - { - target._annotations = annotations.ToArray(); - } - else - { - target._annotations = source._annotations; - } - } } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Linq/JTokenReader.cs b/Libs/Newtonsoft.Json/Linq/JTokenReader.cs index b066191..971be03 100644 --- a/Libs/Newtonsoft.Json/Linq/JTokenReader.cs +++ b/Libs/Newtonsoft.Json/Linq/JTokenReader.cs @@ -34,14 +34,14 @@ namespace LC.Newtonsoft.Json.Linq public class JTokenReader : JsonReader, IJsonLineInfo { private readonly JToken _root; - private string? _initialPath; - private JToken? _parent; - private JToken? _current; + private string _initialPath; + private JToken _parent; + private JToken _current; /// /// Gets the at the reader's current position. /// - public JToken? CurrentToken => _current; + public JToken CurrentToken => _current; /// /// Initializes a new instance of the class. @@ -90,12 +90,6 @@ namespace LC.Newtonsoft.Json.Linq } } - // The current value could already be the root value if it is a comment - if (_current == _root) - { - return false; - } - _current = _root; SetToken(_current); return true; @@ -108,8 +102,8 @@ namespace LC.Newtonsoft.Json.Linq return ReadToEnd(); } - JToken? next = t.Next; - if ((next == null || next == t) || t == t.Parent!.Last) + JToken next = t.Next; + if ((next == null || next == t) || t == t.Parent.Last) { if (t.Parent == null) { @@ -152,7 +146,7 @@ namespace LC.Newtonsoft.Json.Linq private bool ReadInto(JContainer c) { - JToken? firstChild = c.First; + JToken firstChild = c.First; if (firstChild == null) { return SetEnd(c); @@ -221,7 +215,7 @@ namespace LC.Newtonsoft.Json.Linq break; case JTokenType.Date: { - object? v = ((JValue)token).Value; + object v = ((JValue)token).Value; if (v is DateTime dt) { v = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); @@ -241,7 +235,7 @@ namespace LC.Newtonsoft.Json.Linq break; case JTokenType.Uri: { - object? v = ((JValue)token).Value; + object v = ((JValue)token).Value; SetToken(JsonToken.String, v is Uri uri ? uri.OriginalString : SafeToString(v)); break; } @@ -253,7 +247,7 @@ namespace LC.Newtonsoft.Json.Linq } } - private string? SafeToString(object? value) + private string SafeToString(object value) { return value?.ToString(); } @@ -265,7 +259,7 @@ namespace LC.Newtonsoft.Json.Linq return false; } - IJsonLineInfo? info = _current; + IJsonLineInfo info = _current; return (info != null && info.HasLineInfo()); } @@ -278,7 +272,7 @@ namespace LC.Newtonsoft.Json.Linq return 0; } - IJsonLineInfo? info = _current; + IJsonLineInfo info = _current; if (info != null) { return info.LineNumber; @@ -297,7 +291,7 @@ namespace LC.Newtonsoft.Json.Linq return 0; } - IJsonLineInfo? info = _current; + IJsonLineInfo info = _current; if (info != null) { return info.LinePosition; @@ -321,9 +315,9 @@ namespace LC.Newtonsoft.Json.Linq _initialPath = _root.Path; } - if (!StringUtils.IsNullOrEmpty(_initialPath)) + if (!string.IsNullOrEmpty(_initialPath)) { - if (StringUtils.IsNullOrEmpty(path)) + if (string.IsNullOrEmpty(path)) { return _initialPath; } diff --git a/Libs/Newtonsoft.Json/Linq/JTokenWriter.cs b/Libs/Newtonsoft.Json/Linq/JTokenWriter.cs index ce3efde..5d8c534 100644 --- a/Libs/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Libs/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -24,7 +24,6 @@ #endregion using System; -using System.Diagnostics; using System.Globalization; #if HAVE_BIG_INTEGER using System.Numerics; @@ -38,22 +37,22 @@ namespace LC.Newtonsoft.Json.Linq /// public partial class JTokenWriter : JsonWriter { - private JContainer? _token; - private JContainer? _parent; + private JContainer _token; + private JContainer _parent; // used when writer is writing single value and the value has no containing parent - private JValue? _value; - private JToken? _current; + private JValue _value; + private JToken _current; /// /// Gets the at the writer's current position. /// - public JToken? CurrentToken => _current; + public JToken CurrentToken => _current; /// /// Gets the token being written. /// /// The token being written. - public JToken? Token + public JToken Token { get { @@ -132,7 +131,7 @@ namespace LC.Newtonsoft.Json.Linq private void RemoveParent() { _current = _parent; - _parent = _parent!.Parent; + _parent = _parent.Parent; if (_parent != null && _parent.Type == JTokenType.Property) { @@ -187,26 +186,21 @@ namespace LC.Newtonsoft.Json.Linq base.WritePropertyName(name); } - private void AddValue(object? value, JsonToken token) + private void AddValue(object value, JsonToken token) { AddValue(new JValue(value), token); } - internal void AddValue(JValue? value, JsonToken token) + internal void AddValue(JValue value, JsonToken token) { if (_parent != null) { - // TryAdd will return false if an invalid JToken type is added. - // For example, a JComment can't be added to a JObject. - // If there is an invalid JToken type then skip it. - if (_parent.TryAdd(value)) - { - _current = _parent.Last; + _parent.Add(value); + _current = _parent.Last; - if (_parent.Type == JTokenType.Property) - { - _parent = _parent.Parent; - } + if (_parent.Type == JTokenType.Property) + { + _parent = _parent.Parent; } } else @@ -222,7 +216,7 @@ namespace LC.Newtonsoft.Json.Linq /// An error will be raised if the value cannot be written as a single JSON token. /// /// The value to write. - public override void WriteValue(object? value) + public override void WriteValue(object value) { #if HAVE_BIG_INTEGER if (value is BigInteger) @@ -259,7 +253,7 @@ namespace LC.Newtonsoft.Json.Linq /// Writes raw JSON. /// /// The raw JSON to write. - public override void WriteRaw(string? json) + public override void WriteRaw(string json) { base.WriteRaw(json); AddValue(new JRaw(json), JsonToken.Raw); @@ -269,7 +263,7 @@ namespace LC.Newtonsoft.Json.Linq /// Writes a comment /*...*/ containing the specified text. /// /// Text to place inside the comment. - public override void WriteComment(string? text) + public override void WriteComment(string text) { base.WriteComment(text); AddValue(JValue.CreateComment(text), JsonToken.Comment); @@ -279,7 +273,7 @@ namespace LC.Newtonsoft.Json.Linq /// Writes a value. /// /// The value to write. - public override void WriteValue(string? value) + public override void WriteValue(string value) { base.WriteValue(value); AddValue(value, JsonToken.String); @@ -452,7 +446,7 @@ namespace LC.Newtonsoft.Json.Linq /// Writes a [] value. /// /// The [] value to write. - public override void WriteValue(byte[]? value) + public override void WriteValue(byte[] value) { base.WriteValue(value); AddValue(value, JsonToken.Bytes); @@ -482,7 +476,7 @@ namespace LC.Newtonsoft.Json.Linq /// Writes a value. /// /// The value to write. - public override void WriteValue(Uri? value) + public override void WriteValue(Uri value) { base.WriteValue(value); AddValue(value, JsonToken.String); @@ -502,7 +496,7 @@ namespace LC.Newtonsoft.Json.Linq } } - JToken value = tokenReader.CurrentToken!.CloneToken(); + JToken value = tokenReader.CurrentToken.CloneToken(); if (_parent != null) { diff --git a/Libs/Newtonsoft.Json/Linq/JValue.Async.cs b/Libs/Newtonsoft.Json/Linq/JValue.Async.cs index 2408541..5b832ea 100644 --- a/Libs/Newtonsoft.Json/Linq/JValue.Async.cs +++ b/Libs/Newtonsoft.Json/Linq/JValue.Async.cs @@ -49,7 +49,7 @@ namespace LC.Newtonsoft.Json.Linq { if (converters != null && converters.Length > 0 && _value != null) { - JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); + JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { // TODO: Call WriteJsonAsync when it exists. @@ -121,13 +121,13 @@ namespace LC.Newtonsoft.Json.Linq return writer.WriteValueAsync(Convert.ToDateTime(_value, CultureInfo.InvariantCulture), cancellationToken); case JTokenType.Bytes: - return writer.WriteValueAsync((byte[]?)_value, cancellationToken); + return writer.WriteValueAsync((byte[])_value, cancellationToken); case JTokenType.Guid: return writer.WriteValueAsync(_value != null ? (Guid?)_value : null, cancellationToken); case JTokenType.TimeSpan: return writer.WriteValueAsync(_value != null ? (TimeSpan?)_value : null, cancellationToken); case JTokenType.Uri: - return writer.WriteValueAsync((Uri?)_value, cancellationToken); + return writer.WriteValueAsync((Uri)_value, cancellationToken); } throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type."); diff --git a/Libs/Newtonsoft.Json/Linq/JValue.cs b/Libs/Newtonsoft.Json/Linq/JValue.cs index 12a59c0..d79cc02 100644 --- a/Libs/Newtonsoft.Json/Linq/JValue.cs +++ b/Libs/Newtonsoft.Json/Linq/JValue.cs @@ -28,8 +28,6 @@ using System.Collections.Generic; using System.Diagnostics; using LC.Newtonsoft.Json.Utilities; using System.Globalization; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; @@ -49,9 +47,9 @@ namespace LC.Newtonsoft.Json.Linq #endif { private JTokenType _valueType; - private object? _value; + private object _value; - internal JValue(object? value, JTokenType type) + internal JValue(object value, JTokenType type) { _value = value; _valueType = type; @@ -64,7 +62,6 @@ namespace LC.Newtonsoft.Json.Linq public JValue(JValue other) : this(other.Value, other.Type) { - CopyAnnotations(this, other); } /// @@ -155,7 +152,7 @@ namespace LC.Newtonsoft.Json.Linq /// Initializes a new instance of the class with the given value. /// /// The value. - public JValue(string? value) + public JValue(string value) : this(value, JTokenType.String) { } @@ -173,7 +170,7 @@ namespace LC.Newtonsoft.Json.Linq /// Initializes a new instance of the class with the given value. /// /// The value. - public JValue(Uri? value) + public JValue(Uri value) : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) { } @@ -191,7 +188,7 @@ namespace LC.Newtonsoft.Json.Linq /// Initializes a new instance of the class with the given value. /// /// The value. - public JValue(object? value) + public JValue(object value) : this(value, GetValueType(null, value)) { } @@ -244,7 +241,7 @@ namespace LC.Newtonsoft.Json.Linq } #endif - internal static int Compare(JTokenType valueType, object? objA, object? objB) + internal static int Compare(JTokenType valueType, object objA, object objB) { if (objA == objB) { @@ -270,8 +267,8 @@ namespace LC.Newtonsoft.Json.Linq } if (objB is BigInteger integerB) { - return -CompareBigInteger(integerB, objA); - } + return -CompareBigInteger(integerB, objA); + } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { @@ -303,7 +300,7 @@ namespace LC.Newtonsoft.Json.Linq return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } return CompareFloat(objA, objB); - } + } case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: @@ -356,10 +353,10 @@ namespace LC.Newtonsoft.Json.Linq throw new ArgumentException("Object must be of type byte[]."); } - byte[]? bytesA = objA as byte[]; - MiscellaneousUtils.Assert(bytesA != null); + byte[] bytesA = objA as byte[]; + Debug.Assert(bytesA != null); - return MiscellaneousUtils.ByteArrayCompare(bytesA!, bytesB); + return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB); case JTokenType.Guid: if (!(objB is Guid)) { @@ -371,7 +368,7 @@ namespace LC.Newtonsoft.Json.Linq return guid1.CompareTo(guid2); case JTokenType.Uri: - Uri? uri2 = objB as Uri; + Uri uri2 = objB as Uri; if (uri2 == null) { throw new ArgumentException("Object must be of type Uri."); @@ -410,7 +407,7 @@ namespace LC.Newtonsoft.Json.Linq } #if HAVE_EXPRESSIONS - private static bool Operation(ExpressionType operation, object? objA, object? objB, out object? result) + private static bool Operation(ExpressionType operation, object objA, object objB, out object result) { if (objA is string || objB is string) { @@ -567,7 +564,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// A comment with the given value. - public static JValue CreateComment(string? value) + public static JValue CreateComment(string value) { return new JValue(value, JTokenType.Comment); } @@ -577,7 +574,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// The value. /// A string with the given value. - public static JValue CreateString(string? value) + public static JValue CreateString(string value) { return new JValue(value, JTokenType.String); } @@ -600,7 +597,7 @@ namespace LC.Newtonsoft.Json.Linq return new JValue(null, JTokenType.Undefined); } - private static JTokenType GetValueType(JTokenType? current, object? value) + private static JTokenType GetValueType(JTokenType? current, object value) { if (value == null) { @@ -697,13 +694,13 @@ namespace LC.Newtonsoft.Json.Linq /// Gets or sets the underlying token value. /// /// The underlying token value. - public object? Value + public object Value { get => _value; set { - Type? currentType = _value?.GetType(); - Type? newType = value?.GetType(); + Type currentType = _value?.GetType(); + Type newType = value?.GetType(); if (currentType != newType) { @@ -723,7 +720,7 @@ namespace LC.Newtonsoft.Json.Linq { if (converters != null && converters.Length > 0 && _value != null) { - JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); + JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); @@ -806,7 +803,7 @@ namespace LC.Newtonsoft.Json.Linq } return; case JTokenType.Bytes: - writer.WriteValue((byte[]?)_value); + writer.WriteValue((byte[])_value); return; case JTokenType.Guid: writer.WriteValue((_value != null) ? (Guid?)_value : null); @@ -815,7 +812,7 @@ namespace LC.Newtonsoft.Json.Linq writer.WriteValue((_value != null) ? (TimeSpan?)_value : null); return; case JTokenType.Uri: - writer.WriteValue((Uri?)_value); + writer.WriteValue((Uri)_value); return; } @@ -842,7 +839,7 @@ namespace LC.Newtonsoft.Json.Linq /// true if the current object is equal to the parameter; otherwise, false. /// /// An object to compare with this object. - public bool Equals(JValue? other) + public bool Equals(JValue other) { if (other == null) { @@ -861,12 +858,7 @@ namespace LC.Newtonsoft.Json.Linq /// public override bool Equals(object obj) { - if (obj is JValue v) - { - return Equals(v); - } - - return false; + return Equals(obj as JValue); } /// @@ -888,10 +880,6 @@ namespace LC.Newtonsoft.Json.Linq /// /// Returns a that represents this instance. /// - /// - /// ToString() returns a non-JSON string value for tokens with a type of . - /// If you want the JSON for all token types then you should use . - /// /// /// A that represents this instance. /// @@ -937,7 +925,7 @@ namespace LC.Newtonsoft.Json.Linq /// /// A that represents this instance. /// - public string ToString(string? format, IFormatProvider formatProvider) + public string ToString(string format, IFormatProvider formatProvider) { if (_value == null) { @@ -969,7 +957,7 @@ namespace LC.Newtonsoft.Json.Linq private class JValueDynamicProxy : DynamicProxy { - public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result) + public override bool TryConvert(JValue instance, ConvertBinder binder, out object result) { if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken)) { @@ -977,7 +965,7 @@ namespace LC.Newtonsoft.Json.Linq return true; } - object? value = instance.Value; + object value = instance.Value; if (value == null) { @@ -989,9 +977,9 @@ namespace LC.Newtonsoft.Json.Linq return true; } - public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, [NotNullWhen(true)]out object? result) + public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result) { - object? compareValue = arg is JValue value ? value.Value : arg; + object compareValue = arg is JValue value ? value.Value : arg; switch (binder.Operation) { @@ -1043,7 +1031,7 @@ namespace LC.Newtonsoft.Json.Linq } JTokenType comparisonType; - object? otherValue; + object otherValue; if (obj is JValue value) { otherValue = value.Value; @@ -1178,7 +1166,7 @@ namespace LC.Newtonsoft.Json.Linq return (DateTime)this; } - object? IConvertible.ToType(Type conversionType, IFormatProvider provider) + object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ToObject(conversionType); } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs index dd0654c..fb7fa4d 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs @@ -8,13 +8,13 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { public int? Index { get; set; } - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken t in current) { if (Index != null) { - JToken? v = GetTokenIndex(t, settings, Index.GetValueOrDefault()); + JToken v = GetTokenIndex(t, errorWhenNoMatch, Index.GetValueOrDefault()); if (v != null) { @@ -32,7 +32,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } else { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Index * not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs index fb7c2e4..9b7da15 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs @@ -4,20 +4,15 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class ArrayMultipleIndexFilter : PathFilter { - internal List Indexes; + public List Indexes { get; set; } - public ArrayMultipleIndexFilter(List indexes) - { - Indexes = indexes; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken t in current) { foreach (int i in Indexes) { - JToken? v = GetTokenIndex(t, settings, i); + JToken v = GetTokenIndex(t, errorWhenNoMatch, i); if (v != null) { diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs index 2370da8..cf9d964 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs @@ -11,7 +11,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath public int? End { get; set; } public int? Step { get; set; } - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { if (Step == 0) { @@ -56,7 +56,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } else { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Array slice of {0} to {1} returned no results.".FormatWith(CultureInfo.InvariantCulture, Start != null ? Start.GetValueOrDefault().ToString(CultureInfo.InvariantCulture) : "*", @@ -66,7 +66,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } else { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Array slice is not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs index d1ded0c..d1b1a53 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs @@ -6,14 +6,9 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class FieldFilter : PathFilter { - internal string? Name; + public string Name { get; set; } - public FieldFilter(string? name) - { - Name = name; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken t in current) { @@ -21,28 +16,28 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { if (Name != null) { - JToken? v = o[Name]; + JToken v = o[Name]; if (v != null) { yield return v; } - else if (settings?.ErrorWhenNoMatch ?? false) + else if (errorWhenNoMatch) { throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, Name)); } } else { - foreach (KeyValuePair p in o) + foreach (KeyValuePair p in o) { - yield return p.Value!; + yield return p.Value; } } } else { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, Name ?? "*", t.GetType().Name)); } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs index 196290a..889aea1 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs @@ -11,14 +11,9 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class FieldMultipleFilter : PathFilter { - internal List Names; + public List Names { get; set; } - public FieldMultipleFilter(List names) - { - Names = names; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken t in current) { @@ -26,14 +21,14 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { foreach (string name in Names) { - JToken? v = o[name]; + JToken v = o[name]; if (v != null) { yield return v; } - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, name)); } @@ -41,7 +36,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } else { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Properties {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", Names.Select(n => "'" + n + "'") #if !HAVE_STRING_JOIN_WITH_ENUMERABLE diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/JPath.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/JPath.cs index d4d0ad7..2ce4141 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/JPath.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/JPath.cs @@ -107,7 +107,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath case '(': if (_currentIndex > currentPartStartIndex) { - string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); + string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; @@ -118,8 +118,6 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } filters.Add(ParseIndexer(currentChar, scan)); - scan = false; - _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = true; @@ -138,7 +136,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath case '.': if (_currentIndex > currentPartStartIndex) { - string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); + string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; @@ -179,7 +177,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath if (_currentIndex > currentPartStartIndex) { - string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); + string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); if (member == "*") { member = null; @@ -198,9 +196,9 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath return atPathEnd; } - private static PathFilter CreatePathFilter(string? member, bool scan) + private static PathFilter CreatePathFilter(string member, bool scan) { - PathFilter filter = (scan) ? (PathFilter)new ScanFilter(member) : new FieldFilter(member); + PathFilter filter = (scan) ? (PathFilter)new ScanFilter {Name = member} : new FieldFilter {Name = member}; return filter; } @@ -232,7 +230,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { int start = _currentIndex; int? end = null; - List? indexes = null; + List indexes = null; int colonCount = 0; int? startIndex = null; int? endIndex = null; @@ -264,7 +262,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); indexes.Add(index); - return new ArrayMultipleIndexFilter(indexes); + return new ArrayMultipleIndexFilter { Indexes = indexes }; } else if (colonCount > 0) { @@ -423,19 +421,26 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath if (!scan) { - return new QueryFilter(expression); + return new QueryFilter + { + Expression = expression + }; } else { - return new QueryScanFilter(expression); + return new QueryScanFilter + { + Expression = expression + }; } } - private bool TryParseExpression(out List? expressionPath) + private bool TryParseExpression(out List expressionPath) { if (_expression[_currentIndex] == '$') { - expressionPath = new List { RootFilter.Instance }; + expressionPath = new List(); + expressionPath.Add(RootFilter.Instance); } else if (_expression[_currentIndex] == '@') { @@ -449,7 +454,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath _currentIndex++; - if (ParsePath(expressionPath!, _currentIndex, true)) + if (ParsePath(expressionPath, _currentIndex, true)) { throw new JsonException("Path ended with open query."); } @@ -466,12 +471,12 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { EatWhitespace(); - if (TryParseExpression(out List? expressionPath)) + if (TryParseExpression(out var expressionPath)) { EatWhitespace(); EnsureLength("Path ended with open query."); - return expressionPath!; + return expressionPath; } if (TryParseValue(out var value)) @@ -487,13 +492,13 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath private QueryExpression ParseExpression() { - QueryExpression? rootExpression = null; - CompositeExpression? parentExpression = null; + QueryExpression rootExpression = null; + CompositeExpression parentExpression = null; while (_currentIndex < _expression.Length) { object left = ParseSide(); - object? right = null; + object right = null; QueryOperator op; if (_expression[_currentIndex] == ')' @@ -509,14 +514,19 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath right = ParseSide(); } - BooleanQueryExpression booleanExpression = new BooleanQueryExpression(op, left, right); + BooleanQueryExpression booleanExpression = new BooleanQueryExpression + { + Left = left, + Operator = op, + Right = right + }; if (_expression[_currentIndex] == ')') { if (parentExpression != null) { parentExpression.Expressions.Add(booleanExpression); - return rootExpression!; + return rootExpression; } return booleanExpression; @@ -530,7 +540,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath if (parentExpression == null || parentExpression.Operator != QueryOperator.And) { - CompositeExpression andExpression = new CompositeExpression(QueryOperator.And); + CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; parentExpression?.Expressions.Add(andExpression); @@ -553,7 +563,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath if (parentExpression == null || parentExpression.Operator != QueryOperator.Or) { - CompositeExpression orExpression = new CompositeExpression(QueryOperator.Or); + CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; parentExpression?.Expressions.Add(orExpression); @@ -572,7 +582,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath throw new JsonException("Path ended with open query."); } - private bool TryParseValue(out object? value) + private bool TryParseValue(out object value) { char currentChar = _expression[_currentIndex]; if (currentChar == '\'') @@ -753,9 +763,9 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath private bool Match(string s) { int currentPosition = _currentIndex; - for (int i = 0; i < s.Length; i++) + foreach (char c in s) { - if (currentPosition < _expression.Length && _expression[currentPosition] == s[i]) + if (currentPosition < _expression.Length && _expression[currentPosition] == c) { currentPosition++; } @@ -822,7 +832,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath private PathFilter ParseQuotedField(char indexerCloseChar, bool scan) { - List? fields = null; + List fields = null; while (_currentIndex < _expression.Length) { @@ -837,8 +847,8 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { fields.Add(field); return (scan) - ? (PathFilter)new ScanMultipleFilter(fields) - : (PathFilter)new FieldMultipleFilter(fields); + ? (PathFilter)new ScanMultipleFilter { Names = fields } + : (PathFilter)new FieldMultipleFilter { Names = fields }; } else { @@ -874,17 +884,17 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } } - internal IEnumerable Evaluate(JToken root, JToken t, JsonSelectSettings? settings) + internal IEnumerable Evaluate(JToken root, JToken t, bool errorWhenNoMatch) { - return Evaluate(Filters, root, t, settings); + return Evaluate(Filters, root, t, errorWhenNoMatch); } - internal static IEnumerable Evaluate(List filters, JToken root, JToken t, JsonSelectSettings? settings) + internal static IEnumerable Evaluate(List filters, JToken root, JToken t, bool errorWhenNoMatch) { IEnumerable current = new[] { t }; foreach (PathFilter filter in filters) { - current = filter.ExecuteFilter(root, current, settings); + current = filter.ExecuteFilter(root, current, errorWhenNoMatch); } return current; diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs index d859b96..a029fc3 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs @@ -6,15 +6,16 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal abstract class PathFilter { - public abstract IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings); + public abstract IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch); - protected static JToken? GetTokenIndex(JToken t, JsonSelectSettings? settings, int index) + protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index) { + if (t is JArray a) { if (a.Count <= index) { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); } @@ -28,7 +29,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { if (c.Count <= index) { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Index {0} outside the bounds of JConstructor.".FormatWith(CultureInfo.InvariantCulture, index)); } @@ -40,7 +41,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } else { - if (settings?.ErrorWhenNoMatch ?? false) + if (errorWhenNoMatch) { throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, t.GetType().Name)); } @@ -49,7 +50,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } } - protected static JToken? GetNextScanValue(JToken originalParent, JToken? container, JToken? value) + protected static JToken GetNextScanValue(JToken originalParent, JToken container, JToken value) { // step into container's values if (container != null && container.HasValues) @@ -59,7 +60,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath else { // finished container, move to parent - while (value != null && value != originalParent && value == value.Parent!.Last) + while (value != null && value != originalParent && value == value.Parent.Last) { value = value.Parent; } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs index 26756d4..1c0a1d7 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs @@ -32,39 +32,28 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath internal abstract class QueryExpression { - internal QueryOperator Operator; + public QueryOperator Operator { get; set; } - public QueryExpression(QueryOperator @operator) - { - Operator = @operator; - } - - // For unit tests - public bool IsMatch(JToken root, JToken t) - { - return IsMatch(root, t, null); - } - - public abstract bool IsMatch(JToken root, JToken t, JsonSelectSettings? settings); + public abstract bool IsMatch(JToken root, JToken t); } internal class CompositeExpression : QueryExpression { public List Expressions { get; set; } - public CompositeExpression(QueryOperator @operator) : base(@operator) + public CompositeExpression() { Expressions = new List(); } - public override bool IsMatch(JToken root, JToken t, JsonSelectSettings? settings) + public override bool IsMatch(JToken root, JToken t) { switch (Operator) { case QueryOperator.And: foreach (QueryExpression e in Expressions) { - if (!e.IsMatch(root, t, settings)) + if (!e.IsMatch(root, t)) { return false; } @@ -73,7 +62,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath case QueryOperator.Or: foreach (QueryExpression e in Expressions) { - if (e.IsMatch(root, t, settings)) + if (e.IsMatch(root, t)) { return true; } @@ -87,16 +76,10 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath internal class BooleanQueryExpression : QueryExpression { - public readonly object Left; - public readonly object? Right; + public object Left { get; set; } + public object Right { get; set; } - public BooleanQueryExpression(QueryOperator @operator, object left, object? right) : base(@operator) - { - Left = left; - Right = right; - } - - private IEnumerable GetResult(JToken root, JToken t, object? o) + private IEnumerable GetResult(JToken root, JToken t, object o) { if (o is JToken resultToken) { @@ -105,13 +88,13 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath if (o is List pathFilters) { - return JPath.Evaluate(pathFilters, root, t, null); + return JPath.Evaluate(pathFilters, root, t, false); } return CollectionUtils.ArrayEmpty(); } - public override bool IsMatch(JToken root, JToken t, JsonSelectSettings? settings) + public override bool IsMatch(JToken root, JToken t) { if (Operator == QueryOperator.Exists) { @@ -130,7 +113,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath JToken leftResult = leftResults.Current; foreach (JToken rightResult in rightResults) { - if (MatchTokens(leftResult, rightResult, settings)) + if (MatchTokens(leftResult, rightResult)) { return true; } @@ -142,14 +125,14 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath return false; } - private bool MatchTokens(JToken leftResult, JToken rightResult, JsonSelectSettings? settings) + private bool MatchTokens(JToken leftResult, JToken rightResult) { if (leftResult is JValue leftValue && rightResult is JValue rightValue) { switch (Operator) { case QueryOperator.RegexEquals: - if (RegexEquals(leftValue, rightValue, settings)) + if (RegexEquals(leftValue, rightValue)) { return true; } @@ -221,25 +204,20 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath return false; } - private static bool RegexEquals(JValue input, JValue pattern, JsonSelectSettings? settings) + private static bool RegexEquals(JValue input, JValue pattern) { if (input.Type != JTokenType.String || pattern.Type != JTokenType.String) { return false; } - string regexText = (string)pattern.Value!; + string regexText = (string)pattern.Value; int patternOptionDelimiterIndex = regexText.LastIndexOf('/'); string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1); string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1); -#if HAVE_REGEX_TIMEOUTS - TimeSpan timeout = settings?.RegexMatchTimeout ?? Regex.InfiniteMatchTimeout; - return Regex.IsMatch((string)input.Value!, patternText, MiscellaneousUtils.GetRegexOptions(optionsText), timeout); -#else - return Regex.IsMatch((string)input.Value!, patternText, MiscellaneousUtils.GetRegexOptions(optionsText)); -#endif + return Regex.IsMatch((string)input.Value, patternText, MiscellaneousUtils.GetRegexOptions(optionsText)); } internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue) @@ -262,7 +240,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath return false; } - string queryValueString = (string)queryValue.Value!; + string queryValueString = (string)queryValue.Value; string currentValueString; @@ -280,21 +258,21 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath else #endif { - DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value!, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); + DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); } currentValueString = writer.ToString(); } break; case JTokenType.Bytes: - currentValueString = Convert.ToBase64String((byte[])value.Value!); + currentValueString = Convert.ToBase64String((byte[])value.Value); break; case JTokenType.Guid: case JTokenType.TimeSpan: - currentValueString = value.Value!.ToString(); + currentValueString = value.Value.ToString(); break; case JTokenType.Uri: - currentValueString = ((Uri)value.Value!).OriginalString; + currentValueString = ((Uri)value.Value).OriginalString; break; default: return false; @@ -305,8 +283,8 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath internal static bool EqualsWithStrictMatch(JValue value, JValue queryValue) { - MiscellaneousUtils.Assert(value != null); - MiscellaneousUtils.Assert(queryValue != null); + Debug.Assert(value != null); + Debug.Assert(queryValue != null); // Handle comparing an integer with a float // e.g. Comparing 1 and 1.0 diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs index 54f540f..8104d20 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs @@ -5,20 +5,15 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class QueryFilter : PathFilter { - internal QueryExpression Expression; + public QueryExpression Expression { get; set; } - public QueryFilter(QueryExpression expression) - { - Expression = expression; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken t in current) { foreach (JToken v in t) { - if (Expression.IsMatch(root, v, settings)) + if (Expression.IsMatch(root, v)) { yield return v; } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs index ef71ab5..60b8ce0 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs @@ -5,14 +5,9 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class QueryScanFilter : PathFilter { - internal QueryExpression Expression; + public QueryExpression Expression { get; set; } - public QueryScanFilter(QueryExpression expression) - { - Expression = expression; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken t in current) { @@ -20,7 +15,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { foreach (JToken d in c.DescendantsAndSelf()) { - if (Expression.IsMatch(root, d, settings)) + if (Expression.IsMatch(root, d)) { yield return d; } @@ -28,7 +23,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } else { - if (Expression.IsMatch(root, t, settings)) + if (Expression.IsMatch(root, t)) { yield return t; } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/RootFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/RootFilter.cs index 0c980c5..4a6b4a7 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/RootFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/RootFilter.cs @@ -10,7 +10,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { } - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { return new[] { root }; } diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs index 12c2306..d3f7d6f 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs @@ -4,14 +4,9 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class ScanFilter : PathFilter { - internal string? Name; + public string Name { get; set; } - public ScanFilter(string? name) - { - Name = name; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken c in current) { @@ -20,11 +15,11 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath yield return c; } - JToken? value = c; + JToken value = c; while (true) { - JContainer? container = value as JContainer; + JContainer container = value as JContainer; value = GetNextScanValue(c, container, value); if (value == null) diff --git a/Libs/Newtonsoft.Json/Linq/JsonPath/ScanMultipleFilter.cs b/Libs/Newtonsoft.Json/Linq/JsonPath/ScanMultipleFilter.cs index c805a4b..ce99d49 100644 --- a/Libs/Newtonsoft.Json/Linq/JsonPath/ScanMultipleFilter.cs +++ b/Libs/Newtonsoft.Json/Linq/JsonPath/ScanMultipleFilter.cs @@ -4,22 +4,17 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath { internal class ScanMultipleFilter : PathFilter { - private List _names; + public List Names { get; set; } - public ScanMultipleFilter(List names) - { - _names = names; - } - - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) { foreach (JToken c in current) { - JToken? value = c; + JToken value = c; while (true) { - JContainer? container = value as JContainer; + JContainer container = value as JContainer; value = GetNextScanValue(c, container, value); if (value == null) @@ -29,7 +24,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath if (value is JProperty property) { - foreach (string name in _names) + foreach (string name in Names) { if (property.Name == name) { @@ -37,6 +32,7 @@ namespace LC.Newtonsoft.Json.Linq.JsonPath } } } + } } } diff --git a/Libs/Newtonsoft.Json/Linq/JsonSelectSettings.cs b/Libs/Newtonsoft.Json/Linq/JsonSelectSettings.cs deleted file mode 100644 index a5fa4f2..0000000 --- a/Libs/Newtonsoft.Json/Linq/JsonSelectSettings.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; - -namespace LC.Newtonsoft.Json.Linq -{ - /// - /// Specifies the settings used when selecting JSON. - /// - public class JsonSelectSettings - { -#if HAVE_REGEX_TIMEOUTS - /// - /// Gets or sets a timeout that will be used when executing regular expressions. - /// - /// The timeout that will be used when executing regular expressions. - public TimeSpan? RegexMatchTimeout { get; set; } -#endif - - /// - /// Gets or sets a flag that indicates whether an error should be thrown if - /// no tokens are found when evaluating part of the expression. - /// - /// - /// A flag that indicates whether an error should be thrown if - /// no tokens are found when evaluating part of the expression. - /// - public bool ErrorWhenNoMatch { get; set; } - } -} diff --git a/Libs/Newtonsoft.Json/Schema/Extensions.cs b/Libs/Newtonsoft.Json/Schema/Extensions.cs index 68ac120..7059273 100644 --- a/Libs/Newtonsoft.Json/Schema/Extensions.cs +++ b/Libs/Newtonsoft.Json/Schema/Extensions.cs @@ -28,8 +28,6 @@ using System.Collections.Generic; using LC.Newtonsoft.Json.Linq; using LC.Newtonsoft.Json.Utilities; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchema.cs b/Libs/Newtonsoft.Json/Schema/JsonSchema.cs index 56c7aca..cda85bd 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchema.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchema.cs @@ -30,8 +30,6 @@ using LC.Newtonsoft.Json.Linq; using LC.Newtonsoft.Json.Utilities; using System.Globalization; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index 52ca727..93aa0b2 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -35,8 +35,6 @@ using System.Globalization; using LC.Newtonsoft.Json.Utilities; using LC.Newtonsoft.Json.Linq; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] @@ -221,7 +219,7 @@ namespace LC.Newtonsoft.Json.Schema } string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty); - if (!StringUtils.IsNullOrEmpty(location)) + if (!string.IsNullOrEmpty(location)) { location = "/" + location; } diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaConstants.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaConstants.cs index 5ac63b8..052f43c 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaConstants.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaConstants.cs @@ -26,8 +26,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaException.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaException.cs index cf0af7e..e40f8d8 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaException.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaException.cs @@ -26,8 +26,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index 268b5d2..90ac138 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -37,8 +37,6 @@ using System.Linq; #endif -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// @@ -175,7 +173,7 @@ namespace LC.Newtonsoft.Json.Schema { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); - if (!StringUtils.IsNullOrEmpty(containerAttribute?.Title)) + if (!string.IsNullOrEmpty(containerAttribute?.Title)) { return containerAttribute.Title; } @@ -187,7 +185,7 @@ namespace LC.Newtonsoft.Json.Schema { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); - if (!StringUtils.IsNullOrEmpty(containerAttribute?.Description)) + if (!string.IsNullOrEmpty(containerAttribute?.Description)) { return containerAttribute.Description; } @@ -204,7 +202,7 @@ namespace LC.Newtonsoft.Json.Schema { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); - if (!StringUtils.IsNullOrEmpty(containerAttribute?.Id)) + if (!string.IsNullOrEmpty(containerAttribute?.Id)) { return containerAttribute.Id; } @@ -232,7 +230,7 @@ namespace LC.Newtonsoft.Json.Schema string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); - if (!StringUtils.IsNullOrEmpty(resolvedId)) + if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaModel.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaModel.cs index bc38ecb..be875ff 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaModel.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaModel.cs @@ -28,8 +28,6 @@ using System.Collections.Generic; using LC.Newtonsoft.Json.Linq; using LC.Newtonsoft.Json.Utilities; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs index 39a19e7..2a77937 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs @@ -32,8 +32,6 @@ using System.Linq; #endif -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaNode.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaNode.cs index 8088ca8..0f4f440 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaNode.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaNode.cs @@ -33,8 +33,6 @@ using System.Linq; #endif -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs index b5e49bb..b7042b2 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs @@ -26,8 +26,6 @@ using System; using System.Collections.ObjectModel; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaResolver.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaResolver.cs index 9737875..f9da02d 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaResolver.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaResolver.cs @@ -32,8 +32,6 @@ using System.Linq; #endif -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaType.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaType.cs index 5a8c2d3..3ec480b 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaType.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaType.cs @@ -25,8 +25,6 @@ using System; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/JsonSchemaWriter.cs b/Libs/Newtonsoft.Json/Schema/JsonSchemaWriter.cs index 5665c27..110295e 100644 --- a/Libs/Newtonsoft.Json/Schema/JsonSchemaWriter.cs +++ b/Libs/Newtonsoft.Json/Schema/JsonSchemaWriter.cs @@ -35,8 +35,6 @@ using System.Linq; #endif -#nullable disable - namespace LC.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/Libs/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs b/Libs/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs index ab51e6a..d535a35 100644 --- a/Libs/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs +++ b/Libs/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs @@ -25,8 +25,6 @@ using System; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/ValidationEventArgs.cs b/Libs/Newtonsoft.Json/Schema/ValidationEventArgs.cs index 83d81e8..70abf3e 100644 --- a/Libs/Newtonsoft.Json/Schema/ValidationEventArgs.cs +++ b/Libs/Newtonsoft.Json/Schema/ValidationEventArgs.cs @@ -26,8 +26,6 @@ using System; using LC.Newtonsoft.Json.Utilities; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Schema/ValidationEventHandler.cs b/Libs/Newtonsoft.Json/Schema/ValidationEventHandler.cs index 2e4e98c..846b1c8 100644 --- a/Libs/Newtonsoft.Json/Schema/ValidationEventHandler.cs +++ b/Libs/Newtonsoft.Json/Schema/ValidationEventHandler.cs @@ -25,8 +25,6 @@ using System; -#nullable disable - namespace LC.Newtonsoft.Json.Schema { /// diff --git a/Libs/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs b/Libs/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs index b4e372b..5f1f693 100644 --- a/Libs/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs +++ b/Libs/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs @@ -31,9 +31,9 @@ namespace LC.Newtonsoft.Json.Serialization { internal static class CachedAttributeGetter where T : Attribute { - private static readonly ThreadSafeStore TypeAttributeCache = new ThreadSafeStore(JsonTypeReflector.GetAttribute); + private static readonly ThreadSafeStore TypeAttributeCache = new ThreadSafeStore(JsonTypeReflector.GetAttribute); - public static T? GetAttribute(object type) + public static T GetAttribute(object type) { return TypeAttributeCache.Get(type); } diff --git a/Libs/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs b/Libs/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs index 582d3ac..ef908b3 100644 --- a/Libs/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs +++ b/Libs/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs @@ -37,7 +37,7 @@ namespace LC.Newtonsoft.Json.Serialization { private static readonly object TypeContractCacheLock = new object(); private static readonly DefaultJsonNameTable NameTable = new DefaultJsonNameTable(); - private static Dictionary, JsonContract>? _contractCache; + private static Dictionary, JsonContract> _contractCache; /// /// Initializes a new instance of the class. @@ -65,7 +65,7 @@ namespace LC.Newtonsoft.Json.Serialization // for backwards compadibility the CamelCasePropertyNamesContractResolver shares contracts between instances StructMultiKey key = new StructMultiKey(GetType(), type); - Dictionary, JsonContract>? cache = _contractCache; + Dictionary, JsonContract> cache = _contractCache; if (cache == null || !cache.TryGetValue(key, out JsonContract contract)) { contract = CreateContract(type); diff --git a/Libs/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Libs/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 6d21f84..68e9c09 100644 --- a/Libs/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Libs/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -168,7 +168,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the naming strategy used to resolve how property names and dictionary keys are serialized. /// /// The naming strategy used to resolve how property names and dictionary keys are serialized. - public NamingStrategy? NamingStrategy { get; set; } + public NamingStrategy NamingStrategy { get; set; } /// /// Initializes a new instance of the class. @@ -233,21 +233,18 @@ namespace LC.Newtonsoft.Json.Serialization MemberSerialization memberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute); - // Exclude index properties - // Do not filter ByRef types here because accessing FieldType/PropertyType can trigger additonal assembly loads IEnumerable allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) - .Where(m => m is PropertyInfo p ? !ReflectionUtils.IsIndexedProperty(p) : true); + .Where(FilterMembers); List serializableMembers = new List(); if (memberSerialization != MemberSerialization.Fields) { #if HAVE_DATA_CONTRACTS - DataContractAttribute? dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType); + DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType); #endif #pragma warning disable 618 - // Exclude index properties and ByRef types List defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags) .Where(FilterMembers).ToList(); #pragma warning restore 618 @@ -352,9 +349,9 @@ namespace LC.Newtonsoft.Json.Serialization contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType, ignoreSerializableAttribute); contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization)); - Func? extensionDataNameResolver = null; + Func extensionDataNameResolver = null; - JsonObjectAttribute? attribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); + JsonObjectAttribute attribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); if (attribute != null) { contract.ItemRequired = attribute._itemRequired; @@ -363,7 +360,7 @@ namespace LC.Newtonsoft.Json.Serialization if (attribute.NamingStrategyType != null) { - NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(attribute)!; + NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(attribute); extensionDataNameResolver = s => namingStrategy.GetDictionaryKey(s); } } @@ -377,7 +374,7 @@ namespace LC.Newtonsoft.Json.Serialization if (contract.IsInstantiable) { - ConstructorInfo? overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); // check if a JsonConstructorAttribute has been defined and use that if (overrideConstructor != null) @@ -398,7 +395,7 @@ namespace LC.Newtonsoft.Json.Serialization } else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic) { - ConstructorInfo? constructor = GetParameterizedConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo constructor = GetParameterizedConstructor(contract.NonNullableUnderlyingType); if (constructor != null) { contract.ParameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor); @@ -409,7 +406,7 @@ namespace LC.Newtonsoft.Json.Serialization { // value types always have default constructor // check whether there is a constructor that matches with non-writable properties on value type - ConstructorInfo? constructor = GetImmutableConstructor(contract.NonNullableUnderlyingType, contract.Properties); + ConstructorInfo constructor = GetImmutableConstructor(contract.NonNullableUnderlyingType, contract.Properties); if (constructor != null) { contract.OverrideCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor); @@ -471,7 +468,7 @@ namespace LC.Newtonsoft.Json.Serialization Type t = ReflectionUtils.GetMemberUnderlyingType(m); - if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type? dictionaryType)) + if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType)) { Type keyType = dictionaryType.GetGenericArguments()[0]; Type valueType = dictionaryType.GetGenericArguments()[1]; @@ -490,7 +487,7 @@ namespace LC.Newtonsoft.Json.Serialization private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member) { - JsonExtensionDataAttribute? extensionDataAttribute = ReflectionUtils.GetAttribute(member); + JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute(member); if (extensionDataAttribute == null) { return; @@ -498,10 +495,10 @@ namespace LC.Newtonsoft.Json.Serialization Type t = ReflectionUtils.GetMemberUnderlyingType(member); - ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type? dictionaryType); + ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType); - Type keyType = dictionaryType!.GetGenericArguments()[0]; - Type valueType = dictionaryType!.GetGenericArguments()[1]; + Type keyType = dictionaryType.GetGenericArguments()[0]; + Type valueType = dictionaryType.GetGenericArguments()[1]; Type createdType; @@ -515,27 +512,27 @@ namespace LC.Newtonsoft.Json.Serialization createdType = t; } - Func getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(member); + Func getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(member); if (extensionDataAttribute.ReadData) { - Action? setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false)) + Action setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false)) ? JsonTypeReflector.ReflectionDelegateFactory.CreateSet(member) : null; Func createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor(createdType); - MethodInfo? setMethod = t.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); + MethodInfo setMethod = t.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); if (setMethod == null) { // Item is explicitly implemented and non-public // get from dictionary interface - setMethod = dictionaryType!.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); + setMethod = dictionaryType.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); } - MethodCall setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMethod!); + MethodCall setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMethod); ExtensionDataSetter extensionDataSetter = (o, key, value) => { - object? dictionary = getExtensionDataDictionary(o); + object dictionary = getExtensionDataDictionary(o); if (dictionary == null) { if (setExtensionDataDictionary == null) @@ -561,7 +558,7 @@ namespace LC.Newtonsoft.Json.Serialization ExtensionDataGetter extensionDataGetter = o => { - object? dictionary = getExtensionDataDictionary(o); + object dictionary = getExtensionDataDictionary(o); if (dictionary == null) { return null; @@ -592,7 +589,7 @@ namespace LC.Newtonsoft.Json.Serialization { foreach (KeyValuePair item in _e) { - yield return new KeyValuePair(item.Key!, item.Value!); + yield return new KeyValuePair(item.Key, item.Value); } } @@ -602,7 +599,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private ConstructorInfo? GetAttributeConstructor(Type objectType) + private ConstructorInfo GetAttributeConstructor(Type objectType) { IEnumerator en = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).GetEnumerator(); @@ -626,7 +623,7 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - private ConstructorInfo? GetImmutableConstructor(Type objectType, JsonPropertyCollection memberProperties) + private ConstructorInfo GetImmutableConstructor(Type objectType, JsonPropertyCollection memberProperties) { IEnumerable constructors = objectType.GetConstructors(); IEnumerator en = constructors.GetEnumerator(); @@ -640,7 +637,7 @@ namespace LC.Newtonsoft.Json.Serialization { foreach (ParameterInfo parameterInfo in parameters) { - JsonProperty? memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + JsonProperty memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); if (memberProperty == null || memberProperty.Writable) { return null; @@ -655,7 +652,7 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - private ConstructorInfo? GetParameterizedConstructor(Type objectType) + private ConstructorInfo GetParameterizedConstructor(Type objectType) { #if PORTABLE IEnumerable constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance); @@ -692,12 +689,7 @@ namespace LC.Newtonsoft.Json.Serialization foreach (ParameterInfo parameterInfo in constructorParameters) { - if (parameterInfo.Name == null) - { - continue; - } - - JsonProperty? matchingMemberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + JsonProperty matchingMemberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); // ensure that property will have a name from matching property or from parameterinfo // parameterinfo could have no name if generated by a proxy (I'm looking at you Castle) @@ -715,7 +707,7 @@ namespace LC.Newtonsoft.Json.Serialization return parameterCollection; } - private JsonProperty? MatchProperty(JsonPropertyCollection properties, string name, Type type) + private JsonProperty MatchProperty(JsonPropertyCollection properties, string name, Type type) { // it is possible to generate a member with a null name using Reflection.Emit // protect against an ArgumentNullException from GetClosestMatchProperty by testing for null here @@ -724,7 +716,7 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - JsonProperty? property = properties.GetClosestMatchProperty(name); + JsonProperty property = properties.GetClosestMatchProperty(name); // must match type as well as name if (property == null || property.PropertyType != type) { @@ -740,7 +732,7 @@ namespace LC.Newtonsoft.Json.Serialization /// The matching member property. /// The constructor parameter. /// A created for the given . - protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty? matchingMemberProperty, ParameterInfo parameterInfo) + protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo) { JsonProperty property = new JsonProperty(); property.PropertyType = parameterInfo.ParameterType; @@ -779,7 +771,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// Type of the object. /// The contract's default . - protected virtual JsonConverter? ResolveContractConverter(Type objectType) + protected virtual JsonConverter ResolveContractConverter(Type objectType) { return JsonTypeReflector.GetJsonConverter(objectType); } @@ -794,7 +786,7 @@ namespace LC.Newtonsoft.Json.Serialization #endif private void InitializeContract(JsonContract contract) { - JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); if (containerAttribute != null) { contract.IsReference = containerAttribute._isReference; @@ -802,7 +794,7 @@ namespace LC.Newtonsoft.Json.Serialization #if HAVE_DATA_CONTRACTS else { - DataContractAttribute? dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType); + DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType); // doesn't have a null value if (dataContractAttribute != null && dataContractAttribute.IsReference) { @@ -832,11 +824,11 @@ namespace LC.Newtonsoft.Json.Serialization { GetCallbackMethodsForType( t, - out List? onSerializing, - out List? onSerialized, - out List? onDeserializing, - out List? onDeserialized, - out List? onError); + out List onSerializing, + out List onSerialized, + out List onDeserializing, + out List onDeserialized, + out List onError); if (onSerializing != null) { @@ -864,7 +856,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private void GetCallbackMethodsForType(Type type, out List? onSerializing, out List? onSerialized, out List? onDeserializing, out List? onDeserialized, out List? onError) + private void GetCallbackMethodsForType(Type type, out List onSerializing, out List onSerialized, out List onDeserializing, out List onDeserialized, out List onError) { onSerializing = null; onSerialized = null; @@ -875,11 +867,11 @@ namespace LC.Newtonsoft.Json.Serialization foreach (Type baseType in GetClassHierarchyForType(type)) { // while we allow more than one OnSerialized total, only one can be defined per class - MethodInfo? currentOnSerializing = null; - MethodInfo? currentOnSerialized = null; - MethodInfo? currentOnDeserializing = null; - MethodInfo? currentOnDeserialized = null; - MethodInfo? currentOnError = null; + MethodInfo currentOnSerializing = null; + MethodInfo currentOnSerialized = null; + MethodInfo currentOnDeserializing = null; + MethodInfo currentOnDeserialized = null; + MethodInfo currentOnError = null; bool skipSerializing = ShouldSkipSerializing(baseType); bool skipDeserialized = ShouldSkipDeserialized(baseType); @@ -893,7 +885,7 @@ namespace LC.Newtonsoft.Json.Serialization continue; } - Type? prevAttributeType = null; + Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); if (!skipSerializing && IsValidCallback(method, parameters, typeof(OnSerializingAttribute), currentOnSerializing, ref prevAttributeType)) @@ -1011,10 +1003,10 @@ namespace LC.Newtonsoft.Json.Serialization JsonDictionaryContract contract = new JsonDictionaryContract(objectType); InitializeContract(contract); - JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetAttribute(objectType); + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetAttribute(objectType); if (containerAttribute?.NamingStrategyType != null) { - NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute)!; + NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute); contract.DictionaryKeyResolver = s => namingStrategy.GetDictionaryKey(s); } else @@ -1022,7 +1014,7 @@ namespace LC.Newtonsoft.Json.Serialization contract.DictionaryKeyResolver = ResolveDictionaryKey; } - ConstructorInfo? overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); if (overrideConstructor != null) { @@ -1060,7 +1052,7 @@ namespace LC.Newtonsoft.Json.Serialization JsonArrayContract contract = new JsonArrayContract(objectType); InitializeContract(contract); - ConstructorInfo? overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); if (overrideConstructor != null) { @@ -1151,10 +1143,10 @@ namespace LC.Newtonsoft.Json.Serialization JsonDynamicContract contract = new JsonDynamicContract(objectType); InitializeContract(contract); - JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetAttribute(objectType); + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetAttribute(objectType); if (containerAttribute?.NamingStrategyType != null) { - NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute)!; + NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute); contract.PropertyNameResolver = s => namingStrategy.GetDictionaryKey(s); } else @@ -1196,7 +1188,7 @@ namespace LC.Newtonsoft.Json.Serialization } t = ReflectionUtils.EnsureNotNullableType(t); - JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetCachedAttribute(t); + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(t); if (containerAttribute is JsonObjectAttribute) { @@ -1295,7 +1287,7 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo? currentCallback, ref Type? prevAttributeType) + private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (!method.IsDefined(attributeType, false)) { @@ -1379,7 +1371,7 @@ namespace LC.Newtonsoft.Json.Serialization // nametable is not thread-safe for multiple writers lock (nameTable) { - property.PropertyName = nameTable.Add(property.PropertyName!); + property.PropertyName = nameTable.Add(property.PropertyName); } properties.AddProperty(property); @@ -1467,11 +1459,11 @@ namespace LC.Newtonsoft.Json.Serialization private void SetPropertySettingsFromAttributes(JsonProperty property, object attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess) { #if HAVE_DATA_CONTRACTS - DataContractAttribute? dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); + DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); - MemberInfo? memberInfo = attributeProvider as MemberInfo; + MemberInfo memberInfo = attributeProvider as MemberInfo; - DataMemberAttribute? dataMemberAttribute; + DataMemberAttribute dataMemberAttribute; if (dataContractAttribute != null && memberInfo != null) { dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo); @@ -1482,8 +1474,8 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - JsonPropertyAttribute? propertyAttribute = JsonTypeReflector.GetAttribute(attributeProvider); - JsonRequiredAttribute? requiredAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + JsonRequiredAttribute requiredAttribute = JsonTypeReflector.GetAttribute(attributeProvider); string mappedName; bool hasSpecifiedName; @@ -1505,9 +1497,9 @@ namespace LC.Newtonsoft.Json.Serialization hasSpecifiedName = false; } - JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetAttribute(declaringType); + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetAttribute(declaringType); - NamingStrategy? namingStrategy; + NamingStrategy namingStrategy; if (propertyAttribute?.NamingStrategyType != null) { namingStrategy = JsonTypeReflector.CreateNamingStrategyInstance(propertyAttribute.NamingStrategyType, propertyAttribute.NamingStrategyParameters); @@ -1610,7 +1602,7 @@ namespace LC.Newtonsoft.Json.Serialization // the class type might have a converter but the property converter takes precedence property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider); - DefaultValueAttribute? defaultValueAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute(attributeProvider); if (defaultValueAttribute != null) { property.DefaultValue = defaultValueAttribute.Value; @@ -1633,7 +1625,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private Predicate? CreateShouldSerializeTest(MemberInfo member) + private Predicate CreateShouldSerializeTest(MemberInfo member) { MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); @@ -1642,15 +1634,15 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - MethodCall shouldSerializeCall = + MethodCall shouldSerializeCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(shouldSerializeMethod); - return o => (bool)shouldSerializeCall(o)!; + return o => (bool)shouldSerializeCall(o); } private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess) { - MemberInfo? specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (specifiedMember == null) { specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); @@ -1661,7 +1653,7 @@ namespace LC.Newtonsoft.Json.Serialization return; } - Func specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(specifiedMember)!; + Func specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(specifiedMember); property.GetIsSpecified = o => (bool)specifiedPropertyGet(o); diff --git a/Libs/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/Libs/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index 6c9e0d6..24fc813 100644 --- a/Libs/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/Libs/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -43,19 +43,19 @@ namespace LC.Newtonsoft.Json.Serialization { internal static readonly DefaultSerializationBinder Instance = new DefaultSerializationBinder(); - private readonly ThreadSafeStore, Type> _typeCache; + private readonly ThreadSafeStore, Type> _typeCache; /// /// Initializes a new instance of the class. /// public DefaultSerializationBinder() { - _typeCache = new ThreadSafeStore, Type>(GetTypeFromTypeNameKey); + _typeCache = new ThreadSafeStore, Type>(GetTypeFromTypeNameKey); } - private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) + private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) { - string? assemblyName = typeNameKey.Value1; + string assemblyName = typeNameKey.Value1; string typeName = typeNameKey.Value2; if (assemblyName != null) @@ -96,7 +96,7 @@ namespace LC.Newtonsoft.Json.Serialization throw new JsonSerializationException("Could not load assembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, assemblyName)); } - Type? type = assembly.GetType(typeName); + Type type = assembly.GetType(typeName); if (type == null) { // if generic type, try manually parsing the type arguments for the case of dynamically loaded assemblies @@ -127,9 +127,9 @@ namespace LC.Newtonsoft.Json.Serialization } } - private Type? GetGenericTypeFromTypeName(string typeName, Assembly assembly) + private Type GetGenericTypeFromTypeName(string typeName, Assembly assembly) { - Type? type = null; + Type type = null; int openBracketIndex = typeName.IndexOf('['); if (openBracketIndex >= 0) { @@ -159,7 +159,7 @@ namespace LC.Newtonsoft.Json.Serialization { string typeArgAssemblyQualifiedName = typeName.Substring(typeArgStartIndex, i - typeArgStartIndex); - StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(typeArgAssemblyQualifiedName); + StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(typeArgAssemblyQualifiedName); genericTypeArguments.Add(GetTypeByName(typeNameKey)); } break; @@ -173,7 +173,7 @@ namespace LC.Newtonsoft.Json.Serialization return type; } - private Type GetTypeByName(StructMultiKey typeNameKey) + private Type GetTypeByName(StructMultiKey typeNameKey) { return _typeCache.Get(typeNameKey); } @@ -186,9 +186,9 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The type of the object the formatter creates a new instance of. /// - public override Type BindToType(string? assemblyName, string typeName) + public override Type BindToType(string assemblyName, string typeName) { - return GetTypeByName(new StructMultiKey(assemblyName, typeName)); + return GetTypeByName(new StructMultiKey(assemblyName, typeName)); } /// @@ -201,7 +201,7 @@ namespace LC.Newtonsoft.Json.Serialization #if HAVE_SERIALIZATION_BINDER_BIND_TO_NAME override #endif - void BindToName(Type serializedType, out string? assemblyName, out string? typeName) + void BindToName(Type serializedType, out string assemblyName, out string typeName) { #if !HAVE_FULL_REFLECTION assemblyName = serializedType.GetTypeInfo().Assembly.FullName; diff --git a/Libs/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs b/Libs/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs index d8047ba..2db1841 100644 --- a/Libs/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs +++ b/Libs/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs @@ -43,7 +43,7 @@ namespace LC.Newtonsoft.Json.Serialization /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. - public void Trace(TraceLevel level, string message, Exception? ex) + public void Trace(TraceLevel level, string message, Exception ex) { if (level == TraceLevel.Off) { diff --git a/Libs/Newtonsoft.Json/Serialization/DynamicValueProvider.cs b/Libs/Newtonsoft.Json/Serialization/DynamicValueProvider.cs index 9840d98..60815ab 100644 --- a/Libs/Newtonsoft.Json/Serialization/DynamicValueProvider.cs +++ b/Libs/Newtonsoft.Json/Serialization/DynamicValueProvider.cs @@ -42,8 +42,8 @@ namespace LC.Newtonsoft.Json.Serialization public class DynamicValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; - private Func? _getter; - private Action? _setter; + private Func _getter; + private Action _setter; /// /// Initializes a new instance of the class. @@ -60,7 +60,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to set the value on. /// The value to set on the target. - public void SetValue(object target, object? value) + public void SetValue(object target, object value) { try { @@ -98,7 +98,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to get the value from. /// The value. - public object? GetValue(object target) + public object GetValue(object target) { try { diff --git a/Libs/Newtonsoft.Json/Serialization/ErrorContext.cs b/Libs/Newtonsoft.Json/Serialization/ErrorContext.cs index 82c75ec..698e363 100644 --- a/Libs/Newtonsoft.Json/Serialization/ErrorContext.cs +++ b/Libs/Newtonsoft.Json/Serialization/ErrorContext.cs @@ -32,7 +32,7 @@ namespace LC.Newtonsoft.Json.Serialization /// public class ErrorContext { - internal ErrorContext(object? originalObject, object? member, string path, Exception error) + internal ErrorContext(object originalObject, object member, string path, Exception error) { OriginalObject = originalObject; Member = member; @@ -52,13 +52,13 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets the original object that caused the error. /// /// The original object that caused the error. - public object? OriginalObject { get; } + public object OriginalObject { get; } /// /// Gets the member that caused the error. /// /// The member that caused the error. - public object? Member { get; } + public object Member { get; } /// /// Gets the path of the JSON location where the error occurred. diff --git a/Libs/Newtonsoft.Json/Serialization/ErrorEventArgs.cs b/Libs/Newtonsoft.Json/Serialization/ErrorEventArgs.cs index 54556a0..e0d4ddb 100644 --- a/Libs/Newtonsoft.Json/Serialization/ErrorEventArgs.cs +++ b/Libs/Newtonsoft.Json/Serialization/ErrorEventArgs.cs @@ -36,7 +36,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets the current object the error event is being raised against. /// /// The current object the error event is being raised against. - public object? CurrentObject { get; } + public object CurrentObject { get; } /// /// Gets the error context. @@ -49,7 +49,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The current object. /// The error context. - public ErrorEventArgs(object? currentObject, ErrorContext errorContext) + public ErrorEventArgs(object currentObject, ErrorContext errorContext) { CurrentObject = currentObject; ErrorContext = errorContext; diff --git a/Libs/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs b/Libs/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs index 9467e89..2ad5682 100644 --- a/Libs/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs +++ b/Libs/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs @@ -43,8 +43,8 @@ namespace LC.Newtonsoft.Json.Serialization public class ExpressionValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; - private Func? _getter; - private Action? _setter; + private Func _getter; + private Action _setter; /// /// Initializes a new instance of the class. @@ -61,7 +61,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to set the value on. /// The value to set on the target. - public void SetValue(object target, object? value) + public void SetValue(object target, object value) { try { @@ -99,7 +99,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to get the value from. /// The value. - public object? GetValue(object target) + public object GetValue(object target) { try { diff --git a/Libs/Newtonsoft.Json/Serialization/ISerializationBinder.cs b/Libs/Newtonsoft.Json/Serialization/ISerializationBinder.cs index c4f3984..19f0232 100644 --- a/Libs/Newtonsoft.Json/Serialization/ISerializationBinder.cs +++ b/Libs/Newtonsoft.Json/Serialization/ISerializationBinder.cs @@ -40,7 +40,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Specifies the name of the serialized object. /// Specifies the name of the serialized object /// The type of the object the formatter creates a new instance of. - Type BindToType(string? assemblyName, string typeName); + Type BindToType(string assemblyName, string typeName); /// /// When implemented, controls the binding of a serialized object to a type. @@ -48,6 +48,6 @@ namespace LC.Newtonsoft.Json.Serialization /// The type of the object the formatter creates a new instance of. /// Specifies the name of the serialized object. /// Specifies the name of the serialized object. - void BindToName(Type serializedType, out string? assemblyName, out string? typeName); + void BindToName(Type serializedType, out string assemblyName, out string typeName); } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Serialization/ITraceWriter.cs b/Libs/Newtonsoft.Json/Serialization/ITraceWriter.cs index b29ad68..1570039 100644 --- a/Libs/Newtonsoft.Json/Serialization/ITraceWriter.cs +++ b/Libs/Newtonsoft.Json/Serialization/ITraceWriter.cs @@ -23,6 +23,6 @@ namespace LC.Newtonsoft.Json.Serialization /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. - void Trace(TraceLevel level, string message, Exception? ex); + void Trace(TraceLevel level, string message, Exception ex); } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Serialization/IValueProvider.cs b/Libs/Newtonsoft.Json/Serialization/IValueProvider.cs index 0f72330..319d1ae 100644 --- a/Libs/Newtonsoft.Json/Serialization/IValueProvider.cs +++ b/Libs/Newtonsoft.Json/Serialization/IValueProvider.cs @@ -35,13 +35,13 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to set the value on. /// The value to set on the target. - void SetValue(object target, object? value); + void SetValue(object target, object value); /// /// Gets the value. /// /// The target to get the value from. /// The value. - object? GetValue(object target); + object GetValue(object target); } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonArrayContract.cs index 6cbf93d..67e5a82 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -31,7 +31,6 @@ using System.Globalization; using System.Reflection; using LC.Newtonsoft.Json.Utilities; using System.Collections; -using System.Diagnostics; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -50,7 +49,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets the of the collection items. /// /// The of the collection items. - public Type? CollectionItemType { get; } + public Type CollectionItemType { get; } /// /// Gets a value indicating whether the collection type is a multidimensional array. @@ -58,26 +57,26 @@ namespace LC.Newtonsoft.Json.Serialization /// true if the collection type is a multidimensional array; otherwise, false. public bool IsMultidimensionalArray { get; } - private readonly Type? _genericCollectionDefinitionType; + private readonly Type _genericCollectionDefinitionType; - private Type? _genericWrapperType; - private ObjectConstructor? _genericWrapperCreator; - private Func? _genericTemporaryCollectionCreator; + private Type _genericWrapperType; + private ObjectConstructor _genericWrapperCreator; + private Func _genericTemporaryCollectionCreator; internal bool IsArray { get; } internal bool ShouldCreateWrapper { get; } internal bool CanDeserialize { get; private set; } - private readonly ConstructorInfo? _parameterizedConstructor; + private readonly ConstructorInfo _parameterizedConstructor; - private ObjectConstructor? _parameterizedCreator; - private ObjectConstructor? _overrideCreator; + private ObjectConstructor _parameterizedCreator; + private ObjectConstructor _overrideCreator; - internal ObjectConstructor? ParameterizedCreator + internal ObjectConstructor ParameterizedCreator { get { - if (_parameterizedCreator == null && _parameterizedConstructor != null) + if (_parameterizedCreator == null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } @@ -90,7 +89,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the function used to create the object. When set this function will override . /// /// The function used to create the object. - public ObjectConstructor? OverrideCreator + public ObjectConstructor OverrideCreator { get => _overrideCreator; set @@ -117,14 +116,11 @@ namespace LC.Newtonsoft.Json.Serialization : base(underlyingType) { ContractType = JsonContractType.Array; - - // netcoreapp3.0 uses EmptyPartition for empty enumerable. Treat as an empty array. - IsArray = CreatedType.IsArray || - (NonNullableUnderlyingType.IsGenericType() && NonNullableUnderlyingType.GetGenericTypeDefinition().FullName == "System.Linq.EmptyPartition`1"); + IsArray = CreatedType.IsArray; bool canDeserialize; - Type? tempCollectionType; + Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); @@ -132,7 +128,7 @@ namespace LC.Newtonsoft.Json.Serialization _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; - IsMultidimensionalArray = (CreatedType.IsArray && UnderlyingType.GetArrayRank() > 1); + IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(NonNullableUnderlyingType)) { @@ -255,12 +251,11 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - if (CollectionItemType != null && - ImmutableCollectionsUtils.TryBuildImmutableForArrayContract( + if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract( NonNullableUnderlyingType, CollectionItemType, - out Type? immutableCreatedType, - out ObjectConstructor? immutableParameterizedCreator)) + out Type immutableCreatedType, + out ObjectConstructor immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; @@ -273,8 +268,6 @@ namespace LC.Newtonsoft.Json.Serialization { if (_genericWrapperCreator == null) { - MiscellaneousUtils.Assert(_genericCollectionDefinitionType != null); - _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; @@ -318,7 +311,7 @@ namespace LC.Newtonsoft.Json.Serialization if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); - _parameterizedCreator = FSharpUtils.Instance.CreateSeq(CollectionItemType!); + _parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType); } } #endif diff --git a/Libs/Newtonsoft.Json/Serialization/JsonContainerContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonContainerContract.cs index 826b027..47fec83 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonContainerContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonContainerContract.cs @@ -42,11 +42,11 @@ namespace LC.Newtonsoft.Json.Serialization /// public class JsonContainerContract : JsonContract { - private JsonContract? _itemContract; - private JsonContract? _finalItemContract; + private JsonContract _itemContract; + private JsonContract _finalItemContract; // will be null for containers that don't have an item type (e.g. IList) or for complex objects - internal JsonContract? ItemContract + internal JsonContract ItemContract { get => _itemContract; set @@ -64,13 +64,13 @@ namespace LC.Newtonsoft.Json.Serialization } // the final (i.e. can't be inherited from like a sealed class or valuetype) item contract - internal JsonContract? FinalItemContract => _finalItemContract; + internal JsonContract FinalItemContract => _finalItemContract; /// /// Gets or sets the default collection items . /// /// The converter. - public JsonConverter? ItemConverter { get; set; } + public JsonConverter ItemConverter { get; set; } /// /// Gets or sets a value indicating whether the collection items preserve object references. @@ -97,7 +97,7 @@ namespace LC.Newtonsoft.Json.Serialization internal JsonContainerContract(Type underlyingType) : base(underlyingType) { - JsonContainerAttribute? jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute(underlyingType); + JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute(underlyingType); if (jsonContainerAttribute != null) { diff --git a/Libs/Newtonsoft.Json/Serialization/JsonContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonContract.cs index d0493a0..120d93e 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonContract.cs @@ -67,13 +67,13 @@ namespace LC.Newtonsoft.Json.Serialization /// The object to set extension data on. /// The extension data key. /// The extension data value. - public delegate void ExtensionDataSetter(object o, string key, object? value); + public delegate void ExtensionDataSetter(object o, string key, object value); /// /// Gets extension data for an object during serialization. /// /// The object to set extension data on. - public delegate IEnumerable>? ExtensionDataGetter(object o); + public delegate IEnumerable> ExtensionDataGetter(object o); /// /// Contract details for a used by the . @@ -90,11 +90,11 @@ namespace LC.Newtonsoft.Json.Serialization internal bool IsSealed; internal bool IsInstantiable; - private List? _onDeserializedCallbacks; - private List? _onDeserializingCallbacks; - private List? _onSerializedCallbacks; - private List? _onSerializingCallbacks; - private List? _onErrorCallbacks; + private List _onDeserializedCallbacks; + private IList _onDeserializingCallbacks; + private IList _onSerializedCallbacks; + private IList _onSerializingCallbacks; + private IList _onErrorCallbacks; private Type _createdType; /// @@ -112,7 +112,6 @@ namespace LC.Newtonsoft.Json.Serialization get => _createdType; set { - ValidationUtils.ArgumentNotNull(value, nameof(value)); _createdType = value; IsSealed = _createdType.IsSealed(); @@ -130,14 +129,14 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the default for this contract. /// /// The converter. - public JsonConverter? Converter { get; set; } + public JsonConverter Converter { get; set; } /// /// Gets the internally resolved for the contract's type. /// This converter is used as a fallback converter when no other converter is resolved. /// Setting will always override this converter. /// - public JsonConverter? InternalConverter { get; internal set; } + public JsonConverter InternalConverter { get; internal set; } /// /// Gets or sets all methods called immediately after deserialization of the object. @@ -228,7 +227,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the default creator method used to create the object. /// /// The default creator method used to create the object. - public Func? DefaultCreator { get; set; } + public Func DefaultCreator { get; set; } /// /// Gets or sets a value indicating whether the default creator is non-public. @@ -250,7 +249,7 @@ namespace LC.Newtonsoft.Json.Serialization NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; - _createdType = CreatedType = NonNullableUnderlyingType; + CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); diff --git a/Libs/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index c28f415..5ced6bc 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -45,41 +45,41 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the dictionary key resolver. /// /// The dictionary key resolver. - public Func? DictionaryKeyResolver { get; set; } + public Func DictionaryKeyResolver { get; set; } /// /// Gets the of the dictionary keys. /// /// The of the dictionary keys. - public Type? DictionaryKeyType { get; } + public Type DictionaryKeyType { get; } /// /// Gets the of the dictionary values. /// /// The of the dictionary values. - public Type? DictionaryValueType { get; } + public Type DictionaryValueType { get; } - internal JsonContract? KeyContract { get; set; } + internal JsonContract KeyContract { get; set; } - private readonly Type? _genericCollectionDefinitionType; + private readonly Type _genericCollectionDefinitionType; - private Type? _genericWrapperType; - private ObjectConstructor? _genericWrapperCreator; + private Type _genericWrapperType; + private ObjectConstructor _genericWrapperCreator; - private Func? _genericTemporaryDictionaryCreator; + private Func _genericTemporaryDictionaryCreator; internal bool ShouldCreateWrapper { get; } - private readonly ConstructorInfo? _parameterizedConstructor; + private readonly ConstructorInfo _parameterizedConstructor; - private ObjectConstructor? _overrideCreator; - private ObjectConstructor? _parameterizedCreator; + private ObjectConstructor _overrideCreator; + private ObjectConstructor _parameterizedCreator; - internal ObjectConstructor? ParameterizedCreator + internal ObjectConstructor ParameterizedCreator { get { - if (_parameterizedCreator == null && _parameterizedConstructor != null) + if (_parameterizedCreator == null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } @@ -92,7 +92,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the function used to create the object. When set this function will override . /// /// The function used to create the object. - public ObjectConstructor? OverrideCreator + public ObjectConstructor OverrideCreator { get => _overrideCreator; set => _overrideCreator = value; @@ -115,24 +115,24 @@ namespace LC.Newtonsoft.Json.Serialization { ContractType = JsonContractType.Dictionary; - Type? keyType; - Type? valueType; + Type keyType; + Type valueType; - if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) + if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; - if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IDictionary<,>))) + if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) { CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); } - else if (NonNullableUnderlyingType.IsGenericType()) + else if (underlyingType.IsGenericType()) { // ConcurrentDictionary<,> + IDictionary setter + null value = error // wrap to use generic setter // https://github.com/JamesNK/Newtonsoft.Json/issues/1582 - Type typeDefinition = NonNullableUnderlyingType.GetGenericTypeDefinition(); + Type typeDefinition = underlyingType.GetGenericTypeDefinition(); if (typeDefinition.FullName == JsonTypeReflector.ConcurrentDictionaryTypeName) { ShouldCreateWrapper = true; @@ -140,17 +140,17 @@ namespace LC.Newtonsoft.Json.Serialization } #if HAVE_READ_ONLY_COLLECTIONS - IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(NonNullableUnderlyingType, typeof(ReadOnlyDictionary<,>)); + IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if HAVE_READ_ONLY_COLLECTIONS - else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) + else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; - if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyDictionary<,>))) + if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) { CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); } @@ -160,9 +160,9 @@ namespace LC.Newtonsoft.Json.Serialization #endif else { - ReflectionUtils.GetDictionaryKeyValueTypes(NonNullableUnderlyingType, out keyType, out valueType); + ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); - if (NonNullableUnderlyingType == typeof(IDictionary)) + if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary); } @@ -176,10 +176,10 @@ namespace LC.Newtonsoft.Json.Serialization typeof(IDictionary<,>).MakeGenericType(keyType, valueType)); #if HAVE_FSHARP_TYPES - if (!HasParameterizedCreatorInternal && NonNullableUnderlyingType.Name == FSharpUtils.FSharpMapTypeName) + if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { - FSharpUtils.EnsureInitialized(NonNullableUnderlyingType.Assembly()); - _parameterizedCreator = FSharpUtils.Instance.CreateMap(keyType, valueType); + FSharpUtils.EnsureInitialized(underlyingType.Assembly()); + _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); } #endif } @@ -204,14 +204,12 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - if (DictionaryKeyType != null && - DictionaryValueType != null && - ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( - NonNullableUnderlyingType, - DictionaryKeyType, - DictionaryValueType, - out Type? immutableCreatedType, - out ObjectConstructor? immutableParameterizedCreator)) + if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( + underlyingType, + DictionaryKeyType, + DictionaryValueType, + out Type immutableCreatedType, + out ObjectConstructor immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; @@ -225,7 +223,7 @@ namespace LC.Newtonsoft.Json.Serialization { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); - ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! }); + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } diff --git a/Libs/Newtonsoft.Json/Serialization/JsonDynamicContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonDynamicContract.cs index 1332a7d..6c39af1 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonDynamicContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonDynamicContract.cs @@ -46,13 +46,13 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the property name resolver. /// /// The property name resolver. - public Func? PropertyNameResolver { get; set; } + public Func PropertyNameResolver { get; set; } private readonly ThreadSafeStore>> _callSiteGetters = new ThreadSafeStore>>(CreateCallSiteGetter); - private readonly ThreadSafeStore>> _callSiteSetters = - new ThreadSafeStore>>(CreateCallSiteSetter); + private readonly ThreadSafeStore>> _callSiteSetters = + new ThreadSafeStore>>(CreateCallSiteSetter); private static CallSite> CreateCallSiteGetter(string name) { @@ -61,11 +61,11 @@ namespace LC.Newtonsoft.Json.Serialization return CallSite>.Create(new NoThrowGetBinderMember(getMemberBinder)); } - private static CallSite> CreateCallSiteSetter(string name) + private static CallSite> CreateCallSiteSetter(string name) { SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils)); - return CallSite>.Create(new NoThrowSetBinderMember(binder)); + return CallSite>.Create(new NoThrowSetBinderMember(binder)); } /// @@ -80,7 +80,7 @@ namespace LC.Newtonsoft.Json.Serialization Properties = new JsonPropertyCollection(UnderlyingType); } - internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string name, out object? value) + internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string name, out object value) { ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider)); @@ -100,11 +100,11 @@ namespace LC.Newtonsoft.Json.Serialization } } - internal bool TrySetMember(IDynamicMetaObjectProvider dynamicProvider, string name, object? value) + internal bool TrySetMember(IDynamicMetaObjectProvider dynamicProvider, string name, object value) { ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider)); - CallSite> callSite = _callSiteSetters.Get(name); + CallSite> callSite = _callSiteSetters.Get(name); object result = callSite.Target(callSite, dynamicProvider, value); diff --git a/Libs/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Libs/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index edbb027..9ecd9ab 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -36,9 +36,9 @@ namespace LC.Newtonsoft.Json.Serialization { private readonly JsonSerializerInternalReader _reader; private readonly JsonISerializableContract _contract; - private readonly JsonProperty? _member; + private readonly JsonProperty _member; - public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty? member) + public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty member) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); ValidationUtils.ArgumentNotNull(contract, nameof(contract)); @@ -56,7 +56,7 @@ namespace LC.Newtonsoft.Json.Serialization return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture); } - public object? Convert(object value, Type type) + public object Convert(object value, Type type) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -72,9 +72,12 @@ namespace LC.Newtonsoft.Json.Serialization { ValidationUtils.ArgumentNotNull(value, nameof(value)); - object? resolvedValue = (value is JValue v) ? v.Value : value; + if (value is JValue v) + { + value = v.Value; + } - return System.Convert.ChangeType(resolvedValue, typeCode, CultureInfo.InvariantCulture); + return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); } public bool ToBoolean(object value) diff --git a/Libs/Newtonsoft.Json/Serialization/JsonISerializableContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonISerializableContract.cs index b863711..c9cc5c1 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonISerializableContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonISerializableContract.cs @@ -38,7 +38,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the object constructor. /// /// The object constructor. - public ObjectConstructor? ISerializableCreator { get; set; } + public ObjectConstructor ISerializableCreator { get; set; } /// /// Initializes a new instance of the class. diff --git a/Libs/Newtonsoft.Json/Serialization/JsonObjectContract.cs b/Libs/Newtonsoft.Json/Serialization/JsonObjectContract.cs index 50af656..9fa24ca 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonObjectContract.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonObjectContract.cs @@ -91,13 +91,13 @@ namespace LC.Newtonsoft.Json.Serialization /// This function is called with a collection of arguments which are defined by the collection. /// /// The function used to create the object. - public ObjectConstructor? OverrideCreator + public ObjectConstructor OverrideCreator { get => _overrideCreator; set => _overrideCreator = value; } - internal ObjectConstructor? ParameterizedCreator + internal ObjectConstructor ParameterizedCreator { get => _parameterizedCreator; set => _parameterizedCreator = value; @@ -106,17 +106,17 @@ namespace LC.Newtonsoft.Json.Serialization /// /// Gets or sets the extension data setter. /// - public ExtensionDataSetter? ExtensionDataSetter { get; set; } + public ExtensionDataSetter ExtensionDataSetter { get; set; } /// /// Gets or sets the extension data getter. /// - public ExtensionDataGetter? ExtensionDataGetter { get; set; } + public ExtensionDataGetter ExtensionDataGetter { get; set; } /// /// Gets or sets the extension data value type. /// - public Type? ExtensionDataValueType + public Type ExtensionDataValueType { get => _extensionDataValueType; set @@ -130,14 +130,14 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the extension data name resolver. /// /// The extension data name resolver. - public Func? ExtensionDataNameResolver { get; set; } + public Func ExtensionDataNameResolver { get; set; } internal bool ExtensionDataIsJToken; private bool? _hasRequiredOrDefaultValueProperties; - private ObjectConstructor? _overrideCreator; - private ObjectConstructor? _parameterizedCreator; - private JsonPropertyCollection? _creatorParameters; - private Type? _extensionDataValueType; + private ObjectConstructor _overrideCreator; + private ObjectConstructor _parameterizedCreator; + private JsonPropertyCollection _creatorParameters; + private Type _extensionDataValueType; internal bool HasRequiredOrDefaultValueProperties { diff --git a/Libs/Newtonsoft.Json/Serialization/JsonProperty.cs b/Libs/Newtonsoft.Json/Serialization/JsonProperty.cs index d1017bc..e7309c7 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonProperty.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonProperty.cs @@ -24,7 +24,6 @@ #endregion using System; -using System.Diagnostics; using System.Reflection; using LC.Newtonsoft.Json.Utilities; @@ -42,20 +41,20 @@ namespace LC.Newtonsoft.Json.Serialization internal Required? _required; internal bool _hasExplicitDefaultValue; - private object? _defaultValue; + private object _defaultValue; private bool _hasGeneratedDefaultValue; - private string? _propertyName; + private string _propertyName; internal bool _skipPropertyNameEscape; - private Type? _propertyType; + private Type _propertyType; // use to cache contract during deserialization - internal JsonContract? PropertyContract { get; set; } + internal JsonContract PropertyContract { get; set; } /// /// Gets or sets the name of the property. /// /// The name of the property. - public string? PropertyName + public string PropertyName { get => _propertyName; set @@ -69,7 +68,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the type that declared this property. /// /// The type that declared this property. - public Type? DeclaringType { get; set; } + public Type DeclaringType { get; set; } /// /// Gets or sets the order of serialization of a member. @@ -81,25 +80,25 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets the name of the underlying member or parameter. /// /// The name of the underlying member or parameter. - public string? UnderlyingName { get; set; } + public string UnderlyingName { get; set; } /// /// Gets the that will get and set the during serialization. /// /// The that will get and set the during serialization. - public IValueProvider? ValueProvider { get; set; } + public IValueProvider ValueProvider { get; set; } /// /// Gets or sets the for this property. /// /// The for this property. - public IAttributeProvider? AttributeProvider { get; set; } + public IAttributeProvider AttributeProvider { get; set; } /// /// Gets or sets the type of the property. /// /// The type of the property. - public Type? PropertyType + public Type PropertyType { get => _propertyType; set @@ -117,14 +116,14 @@ namespace LC.Newtonsoft.Json.Serialization /// If set this converter takes precedence over the contract converter for the property type. /// /// The converter. - public JsonConverter? Converter { get; set; } + public JsonConverter Converter { get; set; } /// /// Gets or sets the member converter. /// /// The member converter. [Obsolete("MemberConverter is obsolete. Use Converter instead.")] - public JsonConverter? MemberConverter + public JsonConverter MemberConverter { get => Converter; set => Converter = value; @@ -158,7 +157,7 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets the default value. /// /// The default value. - public object? DefaultValue + public object DefaultValue { get { @@ -176,7 +175,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - internal object? GetResolvedDefaultValue() + internal object GetResolvedDefaultValue() { if (_propertyType == null) { @@ -185,7 +184,7 @@ namespace LC.Newtonsoft.Json.Serialization if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue) { - _defaultValue = ReflectionUtils.GetDefaultValue(_propertyType); + _defaultValue = ReflectionUtils.GetDefaultValue(PropertyType); _hasGeneratedDefaultValue = true; } @@ -249,25 +248,25 @@ namespace LC.Newtonsoft.Json.Serialization /// Gets or sets a predicate used to determine whether the property should be serialized. /// /// A predicate used to determine whether the property should be serialized. - public Predicate? ShouldSerialize { get; set; } + public Predicate ShouldSerialize { get; set; } /// /// Gets or sets a predicate used to determine whether the property should be deserialized. /// /// A predicate used to determine whether the property should be deserialized. - public Predicate? ShouldDeserialize { get; set; } + public Predicate ShouldDeserialize { get; set; } /// /// Gets or sets a predicate used to determine whether the property should be serialized. /// /// A predicate used to determine whether the property should be serialized. - public Predicate? GetIsSpecified { get; set; } + public Predicate GetIsSpecified { get; set; } /// /// Gets or sets an action used to set whether the property has been deserialized. /// /// An action used to set whether the property has been deserialized. - public Action? SetIsSpecified { get; set; } + public Action SetIsSpecified { get; set; } /// /// Returns a that represents this instance. @@ -277,14 +276,14 @@ namespace LC.Newtonsoft.Json.Serialization /// public override string ToString() { - return PropertyName ?? string.Empty; + return PropertyName; } /// /// Gets or sets the converter used when serializing the property's collection items. /// /// The collection's items converter. - public JsonConverter? ItemConverter { get; set; } + public JsonConverter ItemConverter { get; set; } /// /// Gets or sets whether this property's collection items are serialized as a reference. @@ -306,16 +305,13 @@ namespace LC.Newtonsoft.Json.Serialization internal void WritePropertyName(JsonWriter writer) { - string? propertyName = PropertyName; - MiscellaneousUtils.Assert(propertyName != null); - if (_skipPropertyNameEscape) { - writer.WritePropertyName(propertyName, false); + writer.WritePropertyName(PropertyName, false); } else { - writer.WritePropertyName(propertyName); + writer.WritePropertyName(PropertyName); } } } diff --git a/Libs/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs b/Libs/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs index cc1a55c..8ef0ead 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs @@ -29,9 +29,6 @@ using System.Text; using System.Collections.ObjectModel; using LC.Newtonsoft.Json.Utilities; using System.Globalization; -using System.Runtime.CompilerServices; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; namespace LC.Newtonsoft.Json.Serialization { @@ -64,7 +61,7 @@ namespace LC.Newtonsoft.Json.Serialization /// The key for the specified element. protected override string GetKeyForItem(JsonProperty item) { - return item.PropertyName!; + return item.PropertyName; } /// @@ -73,8 +70,6 @@ namespace LC.Newtonsoft.Json.Serialization /// The property to add to the collection. public void AddProperty(JsonProperty property) { - MiscellaneousUtils.Assert(property.PropertyName != null); - if (Contains(property.PropertyName)) { // don't overwrite existing property with ignored property @@ -134,9 +129,9 @@ namespace LC.Newtonsoft.Json.Serialization /// /// Name of the property. /// A matching property if found. - public JsonProperty? GetClosestMatchProperty(string propertyName) + public JsonProperty GetClosestMatchProperty(string propertyName) { - JsonProperty? property = GetProperty(propertyName, StringComparison.Ordinal); + JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal); if (property == null) { property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase); @@ -145,7 +140,7 @@ namespace LC.Newtonsoft.Json.Serialization return property; } - private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) + private bool TryGetValue(string key, out JsonProperty item) { if (Dictionary == null) { @@ -162,12 +157,12 @@ namespace LC.Newtonsoft.Json.Serialization /// The name of the property to get. /// Type property name string comparison. /// A matching property if found. - public JsonProperty? GetProperty(string propertyName, StringComparison comparisonType) + public JsonProperty GetProperty(string propertyName, StringComparison comparisonType) { // KeyedCollection has an ordinal comparer if (comparisonType == StringComparison.Ordinal) { - if (TryGetValue(propertyName, out JsonProperty? property)) + if (TryGetValue(propertyName, out JsonProperty property)) { return property; } diff --git a/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs b/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs index 9aa44d2..fbc14aa 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs @@ -47,12 +47,12 @@ namespace LC.Newtonsoft.Json.Serialization } } - private ErrorContext? _currentErrorContext; - private BidirectionalDictionary? _mappings; + private ErrorContext _currentErrorContext; + private BidirectionalDictionary _mappings; internal readonly JsonSerializer Serializer; - internal readonly ITraceWriter? TraceWriter; - protected JsonSerializerProxy? InternalSerializer; + internal readonly ITraceWriter TraceWriter; + protected JsonSerializerProxy InternalSerializer; protected JsonSerializerInternalBase(JsonSerializer serializer) { @@ -81,7 +81,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - protected NullValueHandling ResolvedNullValueHandling(JsonObjectContract? containerContract, JsonProperty property) + protected NullValueHandling ResolvedNullValueHandling(JsonObjectContract containerContract, JsonProperty property) { NullValueHandling resolvedNullValueHandling = property.NullValueHandling @@ -91,7 +91,7 @@ namespace LC.Newtonsoft.Json.Serialization return resolvedNullValueHandling; } - private ErrorContext GetErrorContext(object? currentObject, object? member, string path, Exception error) + private ErrorContext GetErrorContext(object currentObject, object member, string path, Exception error) { if (_currentErrorContext == null) { @@ -116,7 +116,7 @@ namespace LC.Newtonsoft.Json.Serialization _currentErrorContext = null; } - protected bool IsErrorHandled(object? currentObject, JsonContract? contract, object? keyValue, IJsonLineInfo? lineInfo, string path, Exception ex) + protected bool IsErrorHandled(object currentObject, JsonContract contract, object keyValue, IJsonLineInfo lineInfo, string path, Exception ex) { ErrorContext errorContext = GetErrorContext(currentObject, keyValue, path, ex); diff --git a/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 7f51152..d3817dc 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -40,12 +40,11 @@ using System.Reflection; using System.Runtime.Serialization; using LC.Newtonsoft.Json.Linq; using LC.Newtonsoft.Json.Utilities; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace LC.Newtonsoft.Json.Serialization @@ -94,10 +93,10 @@ namespace LC.Newtonsoft.Json.Serialization { reader.ReadAndAssert(); - string? id = null; + string id = null; if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore && reader.TokenType == JsonToken.PropertyName - && string.Equals(reader.Value!.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) + && string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); id = reader.Value?.ToString(); @@ -124,33 +123,28 @@ namespace LC.Newtonsoft.Json.Serialization } } - private JsonContract? GetContractSafe(Type? type) + private JsonContract GetContractSafe(Type type) { if (type == null) { return null; } - return GetContract(type); - } - - private JsonContract GetContract(Type type) - { return Serializer._contractResolver.ResolveContract(type); } - public object? Deserialize(JsonReader reader, Type? objectType, bool checkAdditionalContent) + public object Deserialize(JsonReader reader, Type objectType, bool checkAdditionalContent) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } - JsonContract? contract = GetContractSafe(objectType); + JsonContract contract = GetContractSafe(objectType); try { - JsonConverter? converter = GetConverter(contract, null, null, null); + JsonConverter converter = GetConverter(contract, null, null, null); if (reader.TokenType == JsonToken.None && !reader.ReadForType(contract, converter != null)) { @@ -162,11 +156,11 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - object? deserializedValue; + object deserializedValue; if (converter != null && converter.CanRead) { - deserializedValue = DeserializeConvertable(converter, reader, objectType!, null); + deserializedValue = DeserializeConvertable(converter, reader, objectType, null); } else { @@ -214,7 +208,7 @@ namespace LC.Newtonsoft.Json.Serialization return InternalSerializer; } - private JToken? CreateJToken(JsonReader reader, JsonContract? contract) + private JToken CreateJToken(JsonReader reader, JsonContract contract) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -231,22 +225,13 @@ namespace LC.Newtonsoft.Json.Serialization } } - JToken? token; + JToken token; using (JTokenWriter writer = new JTokenWriter()) { writer.WriteToken(reader); token = writer.Token; } - if (contract != null && token != null) - { - if (!contract.UnderlyingType.IsAssignableFrom(token.GetType())) - { - throw JsonSerializationException.Create(reader, "Deserialized JSON type '{0}' is not compatible with expected type '{1}'." - .FormatWith(CultureInfo.InvariantCulture, token.GetType().FullName, contract.UnderlyingType.FullName)); - } - } - return token; } @@ -263,7 +248,7 @@ namespace LC.Newtonsoft.Json.Serialization { if (reader.TokenType == JsonToken.PropertyName) { - string propertyName = (string)reader.Value!; + string propertyName = (string)reader.Value; if (!reader.ReadAndMoveToContent()) { break; @@ -284,7 +269,7 @@ namespace LC.Newtonsoft.Json.Serialization else { writer.WriteEndObject(); - return writer.Token!; + return writer.Token; } } while (reader.Read()); @@ -292,7 +277,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private object? CreateValueInternal(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) + private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) { if (contract != null && contract.ContractType == JsonContractType.Linq) { @@ -316,7 +301,7 @@ namespace LC.Newtonsoft.Json.Serialization case JsonToken.Bytes: return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.String: - string s = (string)reader.Value!; + string s = (string)reader.Value; // string that needs to be returned as a byte array should be base 64 decoded if (objectType == typeof(byte[])) @@ -332,7 +317,7 @@ namespace LC.Newtonsoft.Json.Serialization return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.StartConstructor: - string constructorName = reader.Value!.ToString(); + string constructorName = reader.Value.ToString(); return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Null: @@ -346,7 +331,7 @@ namespace LC.Newtonsoft.Json.Serialization return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Raw: - return new JRaw((string?)reader.Value); + return new JRaw((string)reader.Value); case JsonToken.Comment: // ignore break; @@ -358,9 +343,9 @@ namespace LC.Newtonsoft.Json.Serialization throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } - private static bool CoerceEmptyStringToNull(Type? objectType, JsonContract? contract, string s) + private static bool CoerceEmptyStringToNull(Type objectType, JsonContract contract, string s) { - return StringUtils.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable; + return string.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable; } internal string GetExpectedDescription(JsonContract contract) @@ -387,9 +372,9 @@ namespace LC.Newtonsoft.Json.Serialization } } - private JsonConverter? GetConverter(JsonContract? contract, JsonConverter? memberConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty) + private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty) { - JsonConverter? converter = null; + JsonConverter converter = null; if (memberConverter != null) { // member attribute converter @@ -405,12 +390,13 @@ namespace LC.Newtonsoft.Json.Serialization } else if (contract != null) { + JsonConverter matchingConverter; if (contract.Converter != null) { // class attribute converter converter = contract.Converter; } - else if (Serializer.GetMatchingConverter(contract.UnderlyingType) is JsonConverter matchingConverter) + else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null) { // passed in converters converter = matchingConverter; @@ -424,10 +410,10 @@ namespace LC.Newtonsoft.Json.Serialization return converter; } - private object? CreateObject(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) + private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) { - string? id; - Type? resolvedObjectType = objectType; + string id; + Type resolvedObjectType = objectType; if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.Ignore) { @@ -454,7 +440,7 @@ namespace LC.Newtonsoft.Json.Serialization reader = tokenReader; } - if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object? newValue, out id)) + if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object newValue, out id)) { return newValue; } @@ -462,7 +448,7 @@ namespace LC.Newtonsoft.Json.Serialization else { reader.ReadAndAssert(); - if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object? newValue, out id)) + if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object newValue, out id)) { return newValue; } @@ -473,9 +459,6 @@ namespace LC.Newtonsoft.Json.Serialization return CreateJObject(reader); } - MiscellaneousUtils.Assert(resolvedObjectType != null); - MiscellaneousUtils.Assert(contract != null); - switch (contract.ContractType) { case JsonContractType.Object: @@ -507,7 +490,7 @@ namespace LC.Newtonsoft.Json.Serialization // if the content is inside $value then read past it if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore && reader.TokenType == JsonToken.PropertyName - && string.Equals(reader.Value!.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal)) + && string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); @@ -518,7 +501,7 @@ namespace LC.Newtonsoft.Json.Serialization throw JsonSerializationException.Create(reader, "Unexpected token when deserializing primitive value: " + reader.TokenType); } - object? value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue); + object value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue); reader.ReadAndAssert(); return value; @@ -561,7 +544,7 @@ namespace LC.Newtonsoft.Json.Serialization if (createdFromNonDefaultCreator) { - ObjectConstructor creator = (dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator)!; + ObjectConstructor creator = dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator; return creator(dictionary); } @@ -570,8 +553,8 @@ namespace LC.Newtonsoft.Json.Serialization return wrappedDictionary.UnderlyingDictionary; } - targetDictionary = dictionary; - } + targetDictionary = dictionary; + } else { targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper || !(existingValue is IDictionary) ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id); @@ -598,29 +581,38 @@ namespace LC.Newtonsoft.Json.Serialization throw JsonSerializationException.Create(reader, message); } - private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) + private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) { id = null; newValue = null; if (reader.TokenType == JsonToken.StartObject) { - JObject current = (JObject)reader.CurrentToken!; + JObject current = (JObject)reader.CurrentToken; - JProperty? refProperty = current.Property(JsonTypeReflector.RefPropertyName, StringComparison.Ordinal); - if (refProperty != null) + JToken refToken = current[JsonTypeReflector.RefPropertyName]; + if (refToken != null) { - JToken refToken = refProperty.Value; if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null) { throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); } - string? reference = (string?)refProperty; + JToken property = refToken.Parent; + JToken additionalContent = null; + if (property.Next != null) + { + additionalContent = property.Next; + } + else if (property.Previous != null) + { + additionalContent = property.Previous; + } + + string reference = (string)refToken; if (reference != null) { - JToken? additionalContent = refProperty.Next ?? refProperty.Previous; if (additionalContent != null) { throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); @@ -637,15 +629,15 @@ namespace LC.Newtonsoft.Json.Serialization return true; } } - JToken? typeToken = current[JsonTypeReflector.TypePropertyName]; + JToken typeToken = current[JsonTypeReflector.TypePropertyName]; if (typeToken != null) { - string? qualifiedTypeName = (string?)typeToken; + string qualifiedTypeName = (string)typeToken; JsonReader typeTokenReader = typeToken.CreateReader(); typeTokenReader.ReadAndAssert(); - ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName!); + ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); - JToken? valueToken = current[JsonTypeReflector.ValuePropertyName]; + JToken valueToken = current[JsonTypeReflector.ValuePropertyName]; if (valueToken != null) { while (true) @@ -653,7 +645,7 @@ namespace LC.Newtonsoft.Json.Serialization reader.ReadAndAssert(); if (reader.TokenType == JsonToken.PropertyName) { - if ((string)reader.Value! == JsonTypeReflector.ValuePropertyName) + if ((string)reader.Value == JsonTypeReflector.ValuePropertyName) { return false; } @@ -664,12 +656,12 @@ namespace LC.Newtonsoft.Json.Serialization } } } - JToken? idToken = current[JsonTypeReflector.IdPropertyName]; + JToken idToken = current[JsonTypeReflector.IdPropertyName]; if (idToken != null) { - id = (string?)idToken; + id = (string)idToken; } - JToken? valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; + JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; if (valuesToken != null) { JsonReader listReader = valuesToken.CreateReader(); @@ -685,14 +677,14 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) + private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) { id = null; newValue = null; if (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); if (propertyName.Length > 0 && propertyName[0] == '$') { @@ -702,7 +694,7 @@ namespace LC.Newtonsoft.Json.Serialization do { - propertyName = reader.Value!.ToString(); + propertyName = reader.Value.ToString(); if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) { @@ -712,7 +704,7 @@ namespace LC.Newtonsoft.Json.Serialization throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); } - string? reference = reader.Value?.ToString(); + string reference = reader.Value?.ToString(); reader.ReadAndAssert(); @@ -727,7 +719,7 @@ namespace LC.Newtonsoft.Json.Serialization if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { - TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue!.GetType())), null); + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); } return true; @@ -740,7 +732,7 @@ namespace LC.Newtonsoft.Json.Serialization else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); - string qualifiedTypeName = reader.Value!.ToString(); + string qualifiedTypeName = reader.Value.ToString(); ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); @@ -760,7 +752,7 @@ namespace LC.Newtonsoft.Json.Serialization else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); - object? list = CreateList(reader, objectType, contract, member, existingValue, id); + object list = CreateList(reader, objectType, contract, member, existingValue, id); reader.ReadAndAssert(); newValue = list; return true; @@ -775,7 +767,7 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - private void ResolveTypeName(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, string qualifiedTypeName) + private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, string qualifiedTypeName) { TypeNameHandling resolvedTypeNameHandling = member?.TypeNameHandling @@ -785,7 +777,7 @@ namespace LC.Newtonsoft.Json.Serialization if (resolvedTypeNameHandling != TypeNameHandling.None) { - StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName); + StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName); Type specifiedType; try @@ -817,7 +809,7 @@ namespace LC.Newtonsoft.Json.Serialization } objectType = specifiedType; - contract = GetContract(specifiedType); + contract = GetContractSafe(specifiedType); } } @@ -840,18 +832,15 @@ namespace LC.Newtonsoft.Json.Serialization return arrayContract; } - private object? CreateList(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, object? existingValue, string? id) + private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string id) { - object? value; + object value; if (HasNoDefinedType(contract)) { return CreateJToken(reader, contract); } - MiscellaneousUtils.Assert(objectType != null); - MiscellaneousUtils.Assert(contract != null); - JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract); if (existingValue == null) @@ -894,7 +883,7 @@ namespace LC.Newtonsoft.Json.Serialization { if (arrayContract.IsMultidimensionalArray) { - list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType!, contract.CreatedType.GetArrayRank()); + list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType, contract.CreatedType.GetArrayRank()); } else if (arrayContract.IsArray) { @@ -904,7 +893,7 @@ namespace LC.Newtonsoft.Json.Serialization } else { - ObjectConstructor creator = (arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator)!; + ObjectConstructor creator = arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator; return creator(list); } @@ -929,7 +918,7 @@ namespace LC.Newtonsoft.Json.Serialization return value; } - private bool HasNoDefinedType(JsonContract? contract) + private bool HasNoDefinedType(JsonContract contract) { return (contract == null || contract.UnderlyingType == typeof(object) || contract.ContractType == JsonContractType.Linq #if HAVE_DYNAMIC @@ -938,15 +927,14 @@ namespace LC.Newtonsoft.Json.Serialization ); } - private object? EnsureType(JsonReader reader, object? value, CultureInfo culture, JsonContract? contract, Type? targetType) + private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType) { if (targetType == null) { return value; } - MiscellaneousUtils.Assert(contract != null); - Type? valueType = ReflectionUtils.GetObjectType(value); + Type valueType = ReflectionUtils.GetObjectType(value); // type of value and type of target don't match // attempt to convert value's type to target's type @@ -967,11 +955,7 @@ namespace LC.Newtonsoft.Json.Serialization { if (value is string s) { - return EnumUtils.ParseEnum( - contract.NonNullableUnderlyingType, - null, - s, - false); + return EnumUtils.ParseEnum(contract.NonNullableUnderlyingType, null, s, false); } if (ConvertUtils.IsInteger(primitiveContract.TypeCode)) { @@ -1009,7 +993,7 @@ namespace LC.Newtonsoft.Json.Serialization return value; } - private bool SetPropertyValue(JsonProperty property, JsonConverter? propertyConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty, JsonReader reader, object target) + private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) { bool skipSettingProperty = CalculatePropertyDetails( property, @@ -1019,8 +1003,8 @@ namespace LC.Newtonsoft.Json.Serialization reader, target, out bool useExistingValue, - out object? currentValue, - out JsonContract? propertyContract, + out object currentValue, + out JsonContract propertyContract, out bool gottenCurrentValue, out bool ignoredValue); @@ -1036,16 +1020,16 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - object? value; + object value; if (propertyConverter != null && propertyConverter.CanRead) { - if (!gottenCurrentValue && property.Readable) + if (!gottenCurrentValue && target != null && property.Readable) { - currentValue = property.ValueProvider!.GetValue(target); + currentValue = property.ValueProvider.GetValue(target); } - value = DeserializeConvertable(propertyConverter, reader, property.PropertyType!, currentValue); + value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, currentValue); } else { @@ -1058,7 +1042,7 @@ namespace LC.Newtonsoft.Json.Serialization if ((!useExistingValue || value != currentValue) && ShouldSetPropertyValue(property, containerContract as JsonObjectContract, value)) { - property.ValueProvider!.SetValue(target, value); + property.ValueProvider.SetValue(target, value); if (property.SetIsSpecified != null) { @@ -1079,14 +1063,14 @@ namespace LC.Newtonsoft.Json.Serialization private bool CalculatePropertyDetails( JsonProperty property, - ref JsonConverter? propertyConverter, - JsonContainerContract? containerContract, - JsonProperty? containerProperty, + ref JsonConverter propertyConverter, + JsonContainerContract containerContract, + JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, - out object? currentValue, - out JsonContract? propertyContract, + out object currentValue, + out JsonContract propertyContract, out bool gottenCurrentValue, out bool ignoredValue) { @@ -1115,12 +1099,12 @@ namespace LC.Newtonsoft.Json.Serialization && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject || propertyConverter != null) && property.Readable) { - currentValue = property.ValueProvider!.GetValue(target); + currentValue = property.ValueProvider.GetValue(target); gottenCurrentValue = true; if (currentValue != null) { - propertyContract = GetContract(currentValue.GetType()); + propertyContract = GetContractSafe(currentValue.GetType()); useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType()); } @@ -1159,7 +1143,7 @@ namespace LC.Newtonsoft.Json.Serialization } else { - propertyContract = GetContract(currentValue.GetType()); + propertyContract = GetContractSafe(currentValue.GetType()); if (propertyContract != property.PropertyContract) { @@ -1192,7 +1176,7 @@ namespace LC.Newtonsoft.Json.Serialization return ((value & flag) == flag); } - private bool ShouldSetPropertyValue(JsonProperty property, JsonObjectContract? contract, object? value) + private bool ShouldSetPropertyValue(JsonProperty property, JsonObjectContract contract, object value) { if (value == null && ResolvedNullValueHandling(contract, property) == NullValueHandling.Ignore) { @@ -1350,7 +1334,7 @@ namespace LC.Newtonsoft.Json.Serialization contract.InvokeOnDeserialized(value, Serializer._context); } - private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty? containerProperty, string? id) + private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id) { object underlyingDictionary = dictionary is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : dictionary; @@ -1373,7 +1357,7 @@ namespace LC.Newtonsoft.Json.Serialization contract.ItemContract = GetContractSafe(contract.DictionaryValueType); } - JsonConverter? dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); + JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract keyContract) ? keyContract.TypeCode : PrimitiveTypeCode.Empty; bool finished = false; @@ -1382,7 +1366,7 @@ namespace LC.Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - object keyValue = reader.Value!; + object keyValue = reader.Value; if (CheckPropertyName(reader, keyValue.ToString())) { continue; @@ -1400,7 +1384,7 @@ namespace LC.Newtonsoft.Json.Serialization { keyValue = DateTimeUtils.TryParseDateTime(keyValue.ToString(), reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out DateTime dt) ? dt - : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; + : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); break; } #if HAVE_DATE_TIME_OFFSET @@ -1409,14 +1393,12 @@ namespace LC.Newtonsoft.Json.Serialization { keyValue = DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString(), reader.DateFormatString, reader.Culture, out DateTimeOffset dt) ? dt - : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; + : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); break; } #endif default: - keyValue = contract.KeyContract != null && contract.KeyContract.IsEnum - ? EnumUtils.ParseEnum(contract.KeyContract.NonNullableUnderlyingType, (Serializer._contractResolver as DefaultContractResolver)?.NamingStrategy, keyValue.ToString(), false) - : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; + keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); break; } } @@ -1430,10 +1412,10 @@ namespace LC.Newtonsoft.Json.Serialization throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } - object? itemValue; + object itemValue; if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead) { - itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType!, null); + itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType, null); } else { @@ -1473,7 +1455,7 @@ namespace LC.Newtonsoft.Json.Serialization return underlyingDictionary; } - private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) + private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) { int rank = contract.UnderlyingType.GetArrayRank(); @@ -1484,8 +1466,8 @@ namespace LC.Newtonsoft.Json.Serialization OnDeserializing(reader, contract, list); - JsonContract? collectionItemContract = GetContractSafe(contract.CollectionItemType); - JsonConverter? collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty); + JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType); + JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty); int? previousErrorIndex = null; Stack listStack = new Stack(); @@ -1513,11 +1495,11 @@ namespace LC.Newtonsoft.Json.Serialization case JsonToken.Comment: break; default: - object? value; + object value; if (collectionItemConverter != null && collectionItemConverter.CanRead) { - value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType!, null); + value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null); } else { @@ -1604,7 +1586,7 @@ namespace LC.Newtonsoft.Json.Serialization return list; } - private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contract, object? currentObject, string message) + private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contract, object currentObject, string message) { try { @@ -1623,9 +1605,8 @@ namespace LC.Newtonsoft.Json.Serialization } } - private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) + private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) { -#pragma warning disable CS8600, CS8602, CS8603, CS8604 object underlyingList = list is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : list; if (id != null) @@ -1649,7 +1630,7 @@ namespace LC.Newtonsoft.Json.Serialization contract.ItemContract = GetContractSafe(contract.CollectionItemType); } - JsonConverter? collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty); + JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty); int? previousErrorIndex = null; @@ -1668,7 +1649,7 @@ namespace LC.Newtonsoft.Json.Serialization case JsonToken.Comment: break; default: - object? value; + object value; if (collectionItemConverter != null && collectionItemConverter.CanRead) { @@ -1721,11 +1702,10 @@ namespace LC.Newtonsoft.Json.Serialization OnDeserialized(reader, contract, underlyingList); return underlyingList; -#pragma warning restore CS8600, CS8602, CS8603, CS8604 } #if HAVE_BINARY_SERIALIZATION - private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty? member, string? id) + private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, string id) { Type objectType = contract.UnderlyingType; @@ -1751,7 +1731,7 @@ namespace LC.Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value.ToString(); if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); @@ -1797,15 +1777,15 @@ namespace LC.Newtonsoft.Json.Serialization return createdObject; } - internal object? CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty? member) + internal object CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty member) { - JsonContract? itemContract = GetContractSafe(type); - JsonConverter? itemConverter = GetConverter(itemContract, null, contract, member); + JsonContract itemContract = GetContractSafe(type); + JsonConverter itemConverter = GetConverter(itemContract, null, contract, member); JsonReader tokenReader = token.CreateReader(); tokenReader.ReadAndAssert(); // Move to first token - object? result; + object result; if (itemConverter != null && itemConverter.CanRead) { result = DeserializeConvertable(itemConverter, tokenReader, type, null); @@ -1820,7 +1800,7 @@ namespace LC.Newtonsoft.Json.Serialization #endif #if HAVE_DYNAMIC - private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty? member, string? id) + private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty member, string id) { IDynamicMetaObjectProvider newObject; @@ -1854,7 +1834,7 @@ namespace LC.Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value.ToString(); try { @@ -1864,7 +1844,7 @@ namespace LC.Newtonsoft.Json.Serialization } // first attempt to find a settable property, otherwise fall back to a dynamic set without type - JsonProperty? property = contract.Properties.GetClosestMatchProperty(memberName); + JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); if (property != null && property.Writable && !property.Ignored) { @@ -1873,7 +1853,7 @@ namespace LC.Newtonsoft.Json.Serialization property.PropertyContract = GetContractSafe(property.PropertyType); } - JsonConverter? propertyConverter = GetConverter(property.PropertyContract, property.Converter, null, null); + JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.Converter, null, null); if (!SetPropertyValue(property, propertyConverter, null, member, reader, newObject)) { @@ -1882,15 +1862,15 @@ namespace LC.Newtonsoft.Json.Serialization } else { - Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType! : typeof(IDynamicMetaObjectProvider); + Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider); - JsonContract? dynamicMemberContract = GetContractSafe(t); - JsonConverter? dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); + JsonContract dynamicMemberContract = GetContractSafe(t); + JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); - object? value; + object value; if (dynamicMemberConverter != null && dynamicMemberConverter.CanRead) { - value = DeserializeConvertable(dynamicMemberConverter!, reader, t, null); + value = DeserializeConvertable(dynamicMemberConverter, reader, t, null); } else { @@ -1933,20 +1913,15 @@ namespace LC.Newtonsoft.Json.Serialization internal class CreatorPropertyContext { - public readonly string Name; - public JsonProperty? Property; - public JsonProperty? ConstructorProperty; + public string Name; + public JsonProperty Property; + public JsonProperty ConstructorProperty; public PropertyPresence? Presence; - public object? Value; + public object Value; public bool Used; - - public CreatorPropertyContext(string name) - { - Name = name; - } } - private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty? containerProperty, ObjectConstructor creator, string? id) + private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor creator, string id) { ValidationUtils.ArgumentNotNull(creator, nameof(creator)); @@ -1974,9 +1949,10 @@ namespace LC.Newtonsoft.Json.Serialization { if (propertyContexts.All(p => p.Property != property)) { - propertyContexts.Add(new CreatorPropertyContext(property.PropertyName!) + propertyContexts.Add(new CreatorPropertyContext { Property = property, + Name = property.PropertyName, Presence = PropertyPresence.None }); } @@ -1984,7 +1960,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - object?[] creatorParameterValues = new object?[contract.CreatorParameters.Count]; + object[] creatorParameterValues = new object[contract.CreatorParameters.Count]; foreach (CreatorPropertyContext context in propertyContexts) { @@ -1993,7 +1969,7 @@ namespace LC.Newtonsoft.Json.Serialization { if (context.Property != null && context.Presence == null) { - object? v = context.Value; + object v = context.Value; PropertyPresence propertyPresence; if (v == null) { @@ -2014,10 +1990,10 @@ namespace LC.Newtonsoft.Json.Serialization } } - JsonProperty? constructorProperty = context.ConstructorProperty; + JsonProperty constructorProperty = context.ConstructorProperty; if (constructorProperty == null && context.Property != null) { - constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName!, context.Property.UnderlyingName!); + constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, context.Property.UnderlyingName); } if (constructorProperty != null && !constructorProperty.Ignored) @@ -2039,7 +2015,7 @@ namespace LC.Newtonsoft.Json.Serialization reader, constructorProperty.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, - constructorProperty.PropertyContract!, + constructorProperty.PropertyContract, constructorProperty.PropertyType); } } @@ -2073,17 +2049,17 @@ namespace LC.Newtonsoft.Json.Serialization } JsonProperty property = context.Property; - object? value = context.Value; + object value = context.Value; if (ShouldSetPropertyValue(property, contract, value)) { - property.ValueProvider!.SetValue(createdObject, value); + property.ValueProvider.SetValue(createdObject, value); context.Used = true; } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties - JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType!); + JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); if (propertyContract.ContractType == JsonContractType.Array) { @@ -2091,22 +2067,15 @@ namespace LC.Newtonsoft.Json.Serialization if (propertyArrayContract.CanDeserialize && !propertyArrayContract.IsReadOnlyOrFixedSize) { - object? createdObjectCollection = property.ValueProvider!.GetValue(createdObject); + object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null) { - propertyArrayContract = (JsonArrayContract)GetContract(createdObjectCollection.GetType()); - IList createdObjectCollectionWrapper = (propertyArrayContract.ShouldCreateWrapper) ? propertyArrayContract.CreateWrapper(createdObjectCollection) : (IList)createdObjectCollection; + IList newValues = (propertyArrayContract.ShouldCreateWrapper) ? propertyArrayContract.CreateWrapper(value) : (IList)value; - // Don't attempt to populate array/read-only list - if (!createdObjectCollectionWrapper.IsFixedSize) + foreach (object newValue in newValues) { - IList newValues = (propertyArrayContract.ShouldCreateWrapper) ? propertyArrayContract.CreateWrapper(value) : (IList)value; - - foreach (object newValue in newValues) - { - createdObjectCollectionWrapper.Add(newValue); - } + createdObjectCollectionWrapper.Add(newValue); } } } @@ -2117,7 +2086,7 @@ namespace LC.Newtonsoft.Json.Serialization if (!dictionaryContract.IsReadOnlyOrFixedSize) { - object? createdObjectDictionary = property.ValueProvider!.GetValue(createdObject); + object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); if (createdObjectDictionary != null) { IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary; @@ -2180,14 +2149,14 @@ namespace LC.Newtonsoft.Json.Serialization return createdObject; } - private object? DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object? existingValue) + private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); } - object? value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); + object value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { @@ -2197,7 +2166,7 @@ namespace LC.Newtonsoft.Json.Serialization return value; } - private List ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty? containerProperty, JsonReader reader, Type objectType) + private List ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType) { List propertyValues = new List(); bool exit = false; @@ -2206,43 +2175,41 @@ namespace LC.Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value.ToString(); - CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext(memberName) + CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext { + Name = memberName, ConstructorProperty = contract.CreatorParameters.GetClosestMatchProperty(memberName), Property = contract.Properties.GetClosestMatchProperty(memberName) }; propertyValues.Add(creatorPropertyContext); - JsonProperty? property = creatorPropertyContext.ConstructorProperty ?? creatorPropertyContext.Property; - if (property != null) + JsonProperty property = creatorPropertyContext.ConstructorProperty ?? creatorPropertyContext.Property; + if (property != null && !property.Ignored) { - if (!property.Ignored) + if (property.PropertyContract == null) { - if (property.PropertyContract == null) - { - property.PropertyContract = GetContractSafe(property.PropertyType); - } - - JsonConverter? propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, containerProperty); - - if (!reader.ReadForType(property.PropertyContract, propertyConverter != null)) - { - throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); - } - - if (propertyConverter != null && propertyConverter.CanRead) - { - creatorPropertyContext.Value = DeserializeConvertable(propertyConverter, reader, property.PropertyType!, null); - } - else - { - creatorPropertyContext.Value = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null); - } - - continue; + property.PropertyContract = GetContractSafe(property.PropertyType); } + + JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, containerProperty); + + if (!reader.ReadForType(property.PropertyContract, propertyConverter != null)) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + + if (propertyConverter != null && propertyConverter.CanRead) + { + creatorPropertyContext.Value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, null); + } + else + { + creatorPropertyContext.Value = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null); + } + + continue; } else { @@ -2289,9 +2256,9 @@ namespace LC.Newtonsoft.Json.Serialization return propertyValues; } - public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty? containerMember, JsonProperty? containerProperty, string? id, out bool createdFromNonDefaultCreator) + public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, string id, out bool createdFromNonDefaultCreator) { - object? newObject = null; + object newObject = null; if (objectContract.OverrideCreator != null) { @@ -2332,12 +2299,12 @@ namespace LC.Newtonsoft.Json.Serialization return newObject; } - private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty? member, string? id) + private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id) { OnDeserializing(reader, contract, newObject); // only need to keep a track of properties' presence if they are required or a value should be defaulted if missing - Dictionary? propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) + Dictionary propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None) : null; @@ -2355,7 +2322,7 @@ namespace LC.Newtonsoft.Json.Serialization { case JsonToken.PropertyName: { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value.ToString(); if (CheckPropertyName(reader, propertyName)) { @@ -2366,7 +2333,7 @@ namespace LC.Newtonsoft.Json.Serialization { // attempt exact case match first // then try match ignoring case - JsonProperty? property = contract.Properties.GetClosestMatchProperty(propertyName); + JsonProperty property = contract.Properties.GetClosestMatchProperty(propertyName); if (property == null) { @@ -2406,7 +2373,7 @@ namespace LC.Newtonsoft.Json.Serialization property.PropertyContract = GetContractSafe(property.PropertyType); } - JsonConverter? propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, member); + JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, member); if (!reader.ReadForType(property.PropertyContract, propertyConverter != null)) { @@ -2500,13 +2467,13 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - private void SetExtensionData(JsonObjectContract contract, JsonProperty? member, JsonReader reader, string memberName, object o) + private void SetExtensionData(JsonObjectContract contract, JsonProperty member, JsonReader reader, string memberName, object o) { if (contract.ExtensionDataSetter != null) { try { - object? value = ReadExtensionDataValue(contract, member, reader); + object value = ReadExtensionDataValue(contract, member, reader); contract.ExtensionDataSetter(o, memberName, value); } @@ -2521,9 +2488,9 @@ namespace LC.Newtonsoft.Json.Serialization } } - private object? ReadExtensionDataValue(JsonObjectContract contract, JsonProperty? member, JsonReader reader) + private object ReadExtensionDataValue(JsonObjectContract contract, JsonProperty member, JsonReader reader) { - object? value; + object value; if (contract.ExtensionDataIsJToken) { value = JToken.ReadFrom(reader); @@ -2560,7 +2527,7 @@ namespace LC.Newtonsoft.Json.Serialization if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable) { - property.ValueProvider!.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract!, property.PropertyType)); + property.ValueProvider.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); } } break; @@ -2590,7 +2557,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary? requiredProperties) + private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary requiredProperties) { if (property != null && requiredProperties != null) { @@ -2598,7 +2565,7 @@ namespace LC.Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.String: - propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value!)) + propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value)) ? PropertyPresence.Null : PropertyPresence.Value; break; diff --git a/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 3711477..b1b99e6 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -37,19 +37,18 @@ using System.Security; using LC.Newtonsoft.Json.Linq; using LC.Newtonsoft.Json.Utilities; using System.Runtime.Serialization; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace LC.Newtonsoft.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { - private Type? _rootType; + private Type _rootType; private int _rootLevel; private readonly List _serializeStack = new List(); @@ -58,7 +57,7 @@ namespace LC.Newtonsoft.Json.Serialization { } - public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) + public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { if (jsonWriter == null) { @@ -68,13 +67,13 @@ namespace LC.Newtonsoft.Json.Serialization _rootType = objectType; _rootLevel = _serializeStack.Count + 1; - JsonContract? contract = GetContractSafe(value); + JsonContract contract = GetContractSafe(value); try { if (ShouldWriteReference(value, null, contract, null, null)) { - WriteReference(jsonWriter, value!); + WriteReference(jsonWriter, value); } else { @@ -114,22 +113,17 @@ namespace LC.Newtonsoft.Json.Serialization return InternalSerializer; } - private JsonContract? GetContractSafe(object? value) + private JsonContract GetContractSafe(object value) { if (value == null) { return null; } - return GetContract(value); - } - - private JsonContract GetContract(object value) - { return Serializer._contractResolver.ResolveContract(value.GetType()); } - private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) + private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (contract.TypeCode == PrimitiveTypeCode.Bytes) { @@ -151,7 +145,7 @@ namespace LC.Newtonsoft.Json.Serialization JsonWriter.WriteValue(writer, contract.TypeCode, value); } - private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) + private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null) { @@ -159,9 +153,7 @@ namespace LC.Newtonsoft.Json.Serialization return; } - MiscellaneousUtils.Assert(valueContract != null); - - JsonConverter? converter = + JsonConverter converter = member?.Converter ?? containerProperty?.ItemConverter ?? containerContract?.ItemConverter ?? @@ -217,7 +209,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private bool? ResolveIsReference(JsonContract contract, JsonProperty? property, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) { bool? isReference = null; @@ -245,15 +237,12 @@ namespace LC.Newtonsoft.Json.Serialization return isReference; } - private bool ShouldWriteReference(object? value, JsonProperty? property, JsonContract? valueContract, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (value == null) { return false; } - - MiscellaneousUtils.Assert(valueContract != null); - if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) { return false; @@ -281,7 +270,7 @@ namespace LC.Newtonsoft.Json.Serialization return Serializer.GetReferenceResolver().IsReferenced(this, value); } - private bool ShouldWriteProperty(object? memberValue, JsonObjectContract? containerContract, JsonProperty property) + private bool ShouldWriteProperty(object memberValue, JsonObjectContract containerContract, JsonProperty property) { if (memberValue == null && ResolvedNullValueHandling(containerContract, property) == NullValueHandling.Ignore) { @@ -297,16 +286,9 @@ namespace LC.Newtonsoft.Json.Serialization return true; } - private bool CheckForCircularReference(JsonWriter writer, object? value, JsonProperty? property, JsonContract? contract, JsonContainerContract? containerContract, JsonProperty? containerProperty) + private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) { - if (value == null) - { - return true; - } - - MiscellaneousUtils.Assert(contract != null); - - if (contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) + if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) { return true; } @@ -394,7 +376,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - internal static bool TryConvertToString(object value, Type type, [NotNullWhen(true)]out string? s) + internal static bool TryConvertToString(object value, Type type, out string s) { #if HAVE_TYPE_DESCRIPTOR if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) @@ -412,9 +394,10 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - if (value is Type t) + type = value as Type; + if (type != null) { - s = t.AssemblyQualifiedName; + s = type.AssemblyQualifiedName; return true; } @@ -426,7 +409,7 @@ namespace LC.Newtonsoft.Json.Serialization { OnSerializing(writer, contract, value); - TryConvertToString(value, contract.UnderlyingType, out string? s); + TryConvertToString(value, contract.UnderlyingType, out string s); writer.WriteValue(s); OnSerialized(writer, contract, value); @@ -452,7 +435,7 @@ namespace LC.Newtonsoft.Json.Serialization contract.InvokeOnSerialized(value, Serializer._context); } - private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); @@ -467,7 +450,7 @@ namespace LC.Newtonsoft.Json.Serialization JsonProperty property = contract.Properties[index]; try { - if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract? memberContract, out object? memberValue)) + if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) { continue; } @@ -488,13 +471,13 @@ namespace LC.Newtonsoft.Json.Serialization } } - IEnumerable>? extensionData = contract.ExtensionDataGetter?.Invoke(value); + IEnumerable> extensionData = contract.ExtensionDataGetter?.Invoke(value); if (extensionData != null) { foreach (KeyValuePair e in extensionData) { - JsonContract keyContract = GetContract(e.Key); - JsonContract? valueContract = GetContractSafe(e.Value); + JsonContract keyContract = GetContractSafe(e.Key); + JsonContract valueContract = GetContractSafe(e.Value); string propertyName = GetPropertyName(writer, e.Key, keyContract, out _); @@ -505,7 +488,7 @@ namespace LC.Newtonsoft.Json.Serialization if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName); - WriteReference(writer, e.Value!); + WriteReference(writer, e.Value); } else { @@ -528,16 +511,16 @@ namespace LC.Newtonsoft.Json.Serialization OnSerialized(writer, contract, value); } - private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty? member, JsonProperty property, [NotNullWhen(true)]out JsonContract? memberContract, out object? memberValue) + private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) { - property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType!); + property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); } - memberValue = property.ValueProvider!.GetValue(value); + memberValue = property.ValueProvider.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, contract as JsonObjectContract, property)) @@ -545,7 +528,7 @@ namespace LC.Newtonsoft.Json.Serialization if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); - WriteReference(writer, memberValue!); + WriteReference(writer, memberValue); return false; } @@ -556,7 +539,7 @@ namespace LC.Newtonsoft.Json.Serialization if (memberValue == null) { - JsonObjectContract? objectContract = contract as JsonObjectContract; + JsonObjectContract objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? objectContract?.ItemRequired ?? Required.Default; if (resolvedRequired == Required.Always) { @@ -568,9 +551,7 @@ namespace LC.Newtonsoft.Json.Serialization } } -#pragma warning disable CS8762 // Parameter must have a non-null value when exiting in some condition. return true; -#pragma warning restore CS8762 // Parameter must have a non-null value when exiting in some condition. } } @@ -579,7 +560,7 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { writer.WriteStartObject(); @@ -595,14 +576,14 @@ namespace LC.Newtonsoft.Json.Serialization } } - private bool HasCreatorParameter(JsonContainerContract? contract, JsonProperty property) + private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property) { if (!(contract is JsonObjectContract objectContract)) { return false; } - return objectContract.CreatorParameters.Contains(property.PropertyName!); + return objectContract.CreatorParameters.Contains(property.PropertyName); } private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) @@ -646,7 +627,7 @@ namespace LC.Newtonsoft.Json.Serialization return ((value & flag) == flag); } - private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { @@ -677,7 +658,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values; @@ -697,7 +678,7 @@ namespace LC.Newtonsoft.Json.Serialization { try { - JsonContract? valueContract = contract.FinalItemContract ?? GetContractSafe(value); + JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { @@ -740,7 +721,7 @@ namespace LC.Newtonsoft.Json.Serialization OnSerialized(writer, contract, underlyingList); } - private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, values); @@ -760,7 +741,7 @@ namespace LC.Newtonsoft.Json.Serialization OnSerialized(writer, contract, values); } - private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, int initialDepth, int[] indices) + private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; @@ -782,7 +763,7 @@ namespace LC.Newtonsoft.Json.Serialization try { - JsonContract? valueContract = contract.FinalItemContract ?? GetContractSafe(value); + JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { @@ -817,7 +798,7 @@ namespace LC.Newtonsoft.Json.Serialization writer.WriteEndArray(); } - private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) + private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); // don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to @@ -853,7 +834,7 @@ namespace LC.Newtonsoft.Json.Serialization #if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE [SecuritySafeCritical] #endif - private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (!JsonTypeReflector.FullyTrusted) { @@ -874,7 +855,7 @@ namespace LC.Newtonsoft.Json.Serialization foreach (SerializationEntry serializationEntry in serializationInfo) { - JsonContract? valueContract = GetContractSafe(serializationEntry.Value); + JsonContract valueContract = GetContractSafe(serializationEntry.Value); if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) { @@ -896,7 +877,7 @@ namespace LC.Newtonsoft.Json.Serialization #endif #if HAVE_DYNAMIC - private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); @@ -914,7 +895,7 @@ namespace LC.Newtonsoft.Json.Serialization { try { - if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract? memberContract, out object? memberValue)) + if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) { continue; } @@ -938,11 +919,11 @@ namespace LC.Newtonsoft.Json.Serialization foreach (string memberName in value.GetDynamicMemberNames()) { - if (contract.TryGetMember(value, memberName, out object? memberValue)) + if (contract.TryGetMember(value, memberName, out object memberValue)) { try { - JsonContract? valueContract = GetContractSafe(memberValue); + JsonContract valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) { @@ -980,7 +961,7 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - private bool ShouldWriteDynamicProperty(object? memberValue) + private bool ShouldWriteDynamicProperty(object memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) { @@ -996,7 +977,7 @@ namespace LC.Newtonsoft.Json.Serialization return true; } - private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) + private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { TypeNameHandling resolvedTypeNameHandling = member?.TypeNameHandling @@ -1014,7 +995,7 @@ namespace LC.Newtonsoft.Json.Serialization { if (member != null) { - if (contract.NonNullableUnderlyingType != member.PropertyContract!.CreatedType) + if (contract.NonNullableUnderlyingType != member.PropertyContract.CreatedType) { return true; } @@ -1040,9 +1021,8 @@ namespace LC.Newtonsoft.Json.Serialization return false; } - private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) + private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { -#pragma warning disable CS8600, CS8602, CS8604 object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); @@ -1079,7 +1059,7 @@ namespace LC.Newtonsoft.Json.Serialization try { object value = entry.Value; - JsonContract? valueContract = contract.FinalItemContract ?? GetContractSafe(value); + JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { @@ -1121,7 +1101,6 @@ namespace LC.Newtonsoft.Json.Serialization _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); -#pragma warning restore CS8600, CS8602, CS8604 } private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) @@ -1171,7 +1150,7 @@ namespace LC.Newtonsoft.Json.Serialization { escape = true; - if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string? enumName)) + if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string enumName)) { return enumName; } @@ -1180,7 +1159,7 @@ namespace LC.Newtonsoft.Json.Serialization } } } - else if (TryConvertToString(name, name.GetType(), out string? propertyName)) + else if (TryConvertToString(name, name.GetType(), out string propertyName)) { escape = true; return propertyName; diff --git a/Libs/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs b/Libs/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs index a0aab19..7449e19 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs @@ -34,29 +34,29 @@ namespace LC.Newtonsoft.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { - private readonly JsonSerializerInternalReader? _serializerReader; - private readonly JsonSerializerInternalWriter? _serializerWriter; + private readonly JsonSerializerInternalReader _serializerReader; + private readonly JsonSerializerInternalWriter _serializerWriter; private readonly JsonSerializer _serializer; - public override event EventHandler? Error + public override event EventHandler Error { add => _serializer.Error += value; remove => _serializer.Error -= value; } - public override IReferenceResolver? ReferenceResolver + public override IReferenceResolver ReferenceResolver { get => _serializer.ReferenceResolver; set => _serializer.ReferenceResolver = value; } - public override ITraceWriter? TraceWriter + public override ITraceWriter TraceWriter { get => _serializer.TraceWriter; set => _serializer.TraceWriter = value; } - public override IEqualityComparer? EqualityComparer + public override IEqualityComparer EqualityComparer { get => _serializer.EqualityComparer; set => _serializer.EqualityComparer = value; @@ -230,7 +230,7 @@ namespace LC.Newtonsoft.Json.Serialization } else { - return _serializerWriter!; + return _serializerWriter; } } @@ -250,7 +250,7 @@ namespace LC.Newtonsoft.Json.Serialization _serializer = serializerWriter.Serializer; } - internal override object? DeserializeInternal(JsonReader reader, Type? objectType) + internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) { @@ -274,7 +274,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - internal override void SerializeInternal(JsonWriter jsonWriter, object? value, Type? rootType) + internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) { diff --git a/Libs/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/Libs/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index 1995d86..0591f3d 100644 --- a/Libs/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/Libs/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -58,15 +58,15 @@ namespace LC.Newtonsoft.Json.Serialization public const string ConcurrentDictionaryTypeName = "System.Collections.Concurrent.ConcurrentDictionary`2"; - private static readonly ThreadSafeStore> CreatorCache = - new ThreadSafeStore>(GetCreator); + private static readonly ThreadSafeStore> CreatorCache = + new ThreadSafeStore>(GetCreator); #if !(NET20 || DOTNET) - private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); - private static ReflectionObject? _metadataTypeAttributeReflectionObject; + private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); + private static ReflectionObject _metadataTypeAttributeReflectionObject; #endif - public static T? GetCachedAttribute(object attributeProvider) where T : Attribute + public static T GetCachedAttribute(object attributeProvider) where T : Attribute { return CachedAttributeGetter.GetAttribute(attributeProvider); } @@ -96,14 +96,14 @@ namespace LC.Newtonsoft.Json.Serialization #endif #if HAVE_DATA_CONTRACTS - public static DataContractAttribute? GetDataContractAttribute(Type type) + public static DataContractAttribute GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance Type currentType = type; while (currentType != null) { - DataContractAttribute? result = CachedAttributeGetter.GetAttribute(currentType); + DataContractAttribute result = CachedAttributeGetter.GetAttribute(currentType); if (result != null) { return result; @@ -115,7 +115,7 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - public static DataMemberAttribute? GetDataMemberAttribute(MemberInfo memberInfo) + public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) { // DataMemberAttribute does not have inheritance @@ -127,7 +127,7 @@ namespace LC.Newtonsoft.Json.Serialization // search property and then search base properties if nothing is returned and the property is virtual PropertyInfo propertyInfo = (PropertyInfo)memberInfo; - DataMemberAttribute? result = CachedAttributeGetter.GetAttribute(propertyInfo); + DataMemberAttribute result = CachedAttributeGetter.GetAttribute(propertyInfo); if (result == null) { if (propertyInfo.IsVirtual()) @@ -153,14 +153,14 @@ namespace LC.Newtonsoft.Json.Serialization public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute) { - JsonObjectAttribute? objectAttribute = GetCachedAttribute(objectType); + JsonObjectAttribute objectAttribute = GetCachedAttribute(objectType); if (objectAttribute != null) { return objectAttribute.MemberSerialization; } #if HAVE_DATA_CONTRACTS - DataContractAttribute? dataContractAttribute = GetDataContractAttribute(objectType); + DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType); if (dataContractAttribute != null) { return MemberSerialization.OptIn; @@ -178,13 +178,13 @@ namespace LC.Newtonsoft.Json.Serialization return MemberSerialization.OptOut; } - public static JsonConverter? GetJsonConverter(object attributeProvider) + public static JsonConverter GetJsonConverter(object attributeProvider) { - JsonConverterAttribute? converterAttribute = GetCachedAttribute(attributeProvider); + JsonConverterAttribute converterAttribute = GetCachedAttribute(attributeProvider); if (converterAttribute != null) { - Func creator = CreatorCache.Get(converterAttribute.ConverterType); + Func creator = CreatorCache.Get(converterAttribute.ConverterType); if (creator != null) { return (JsonConverter)creator(converterAttribute.ConverterParameters); @@ -200,19 +200,19 @@ namespace LC.Newtonsoft.Json.Serialization /// The type to create. /// Optional arguments to pass to an initializing constructor of the JsonConverter. /// If null, the default constructor is used. - public static JsonConverter CreateJsonConverterInstance(Type converterType, object[]? args) + public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] args) { - Func converterCreator = CreatorCache.Get(converterType); + Func converterCreator = CreatorCache.Get(converterType); return (JsonConverter)converterCreator(args); } - public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[]? args) + public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[] args) { - Func converterCreator = CreatorCache.Get(namingStrategyType); + Func converterCreator = CreatorCache.Get(namingStrategyType); return (NamingStrategy)converterCreator(args); } - public static NamingStrategy? GetContainerNamingStrategy(JsonContainerAttribute containerAttribute) + public static NamingStrategy GetContainerNamingStrategy(JsonContainerAttribute containerAttribute) { if (containerAttribute.NamingStrategyInstance == null) { @@ -227,9 +227,9 @@ namespace LC.Newtonsoft.Json.Serialization return containerAttribute.NamingStrategyInstance; } - private static Func GetCreator(Type type) + private static Func GetCreator(Type type) { - Func? defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) + Func defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) ? ReflectionDelegateFactory.CreateDefaultConstructor(type) : null; @@ -276,12 +276,12 @@ namespace LC.Newtonsoft.Json.Serialization } #if !(NET20 || DOTNET) - private static Type? GetAssociatedMetadataType(Type type) + private static Type GetAssociatedMetadataType(Type type) { return AssociatedMetadataTypesCache.Get(type); } - private static Type? GetAssociateMetadataTypeFromAttribute(Type type) + private static Type GetAssociateMetadataTypeFromAttribute(Type type) { Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true); @@ -300,7 +300,7 @@ namespace LC.Newtonsoft.Json.Serialization _metadataTypeAttributeReflectionObject = ReflectionObject.Create(attributeType, metadataClassTypeName); } - return (Type?)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName); + return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName); } } @@ -308,12 +308,12 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - private static T? GetAttribute(Type type) where T : Attribute + private static T GetAttribute(Type type) where T : Attribute { - T? attribute; + T attribute; #if !(NET20 || DOTNET) - Type? metadataType = GetAssociatedMetadataType(type); + Type metadataType = GetAssociatedMetadataType(type); if (metadataType != null) { attribute = ReflectionUtils.GetAttribute(metadataType, true); @@ -342,12 +342,12 @@ namespace LC.Newtonsoft.Json.Serialization return null; } - private static T? GetAttribute(MemberInfo memberInfo) where T : Attribute + private static T GetAttribute(MemberInfo memberInfo) where T : Attribute { - T? attribute; + T attribute; #if !(NET20 || DOTNET) - Type? metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); + Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); if (metadataType != null) { MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); @@ -423,7 +423,7 @@ namespace LC.Newtonsoft.Json.Serialization } #endif - public static T? GetAttribute(object provider) where T : Attribute + public static T GetAttribute(object provider) where T : Attribute { if (provider is Type type) { diff --git a/Libs/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs b/Libs/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs deleted file mode 100644 index 0d98fa3..0000000 --- a/Libs/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs +++ /dev/null @@ -1,84 +0,0 @@ -#region License -// Copyright (c) 2007 James Newton-King -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -#endregion - -using LC.Newtonsoft.Json.Utilities; - -namespace LC.Newtonsoft.Json.Serialization -{ - /// - /// A kebab case naming strategy. - /// - public class KebabCaseNamingStrategy : NamingStrategy - { - /// - /// Initializes a new instance of the class. - /// - /// - /// A flag indicating whether dictionary keys should be processed. - /// - /// - /// A flag indicating whether explicitly specified property names should be processed, - /// e.g. a property name customized with a . - /// - public KebabCaseNamingStrategy(bool processDictionaryKeys, bool overrideSpecifiedNames) - { - ProcessDictionaryKeys = processDictionaryKeys; - OverrideSpecifiedNames = overrideSpecifiedNames; - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// A flag indicating whether dictionary keys should be processed. - /// - /// - /// A flag indicating whether explicitly specified property names should be processed, - /// e.g. a property name customized with a . - /// - /// - /// A flag indicating whether extension data names should be processed. - /// - public KebabCaseNamingStrategy(bool processDictionaryKeys, bool overrideSpecifiedNames, bool processExtensionDataNames) - : this(processDictionaryKeys, overrideSpecifiedNames) - { - ProcessExtensionDataNames = processExtensionDataNames; - } - - /// - /// Initializes a new instance of the class. - /// - public KebabCaseNamingStrategy() - { - } - - /// - /// Resolves the specified property name. - /// - /// The property name to resolve. - /// The resolved property name. - protected override string ResolvePropertyName(string name) => StringUtils.ToKebabCase(name); - } -} \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs b/Libs/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs index ea6f4fa..af43f63 100644 --- a/Libs/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs +++ b/Libs/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs @@ -41,7 +41,7 @@ namespace LC.Newtonsoft.Json.Serialization /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. - public void Trace(TraceLevel level, string message, Exception? ex) + public void Trace(TraceLevel level, string message, Exception ex) { StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture)); diff --git a/Libs/Newtonsoft.Json/Serialization/NamingStrategy.cs b/Libs/Newtonsoft.Json/Serialization/NamingStrategy.cs index d0aa684..6463a4c 100644 --- a/Libs/Newtonsoft.Json/Serialization/NamingStrategy.cs +++ b/Libs/Newtonsoft.Json/Serialization/NamingStrategy.cs @@ -130,7 +130,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// /// - protected bool Equals(NamingStrategy? other) + protected bool Equals(NamingStrategy other) { if (other == null) { diff --git a/Libs/Newtonsoft.Json/Serialization/ObjectConstructor.cs b/Libs/Newtonsoft.Json/Serialization/ObjectConstructor.cs index 27508bb..2f68941 100644 --- a/Libs/Newtonsoft.Json/Serialization/ObjectConstructor.cs +++ b/Libs/Newtonsoft.Json/Serialization/ObjectConstructor.cs @@ -29,5 +29,5 @@ namespace LC.Newtonsoft.Json.Serialization /// Represents a method that constructs an object. /// /// The object type to create. - public delegate object ObjectConstructor(params object?[] args); + public delegate object ObjectConstructor(params object[] args); } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs b/Libs/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs index f0b5f21..6780aba 100644 --- a/Libs/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs +++ b/Libs/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs @@ -52,7 +52,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to set the value on. /// The value to set on the target. - public void SetValue(object target, object? value) + public void SetValue(object target, object value) { try { @@ -69,7 +69,7 @@ namespace LC.Newtonsoft.Json.Serialization /// /// The target to get the value from. /// The value. - public object? GetValue(object target) + public object GetValue(object target) { try { diff --git a/Libs/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs b/Libs/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs index f2dceba..7a8bb39 100644 --- a/Libs/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs +++ b/Libs/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs @@ -41,12 +41,12 @@ namespace LC.Newtonsoft.Json.Serialization } #pragma warning restore 618 - public Type BindToType(string? assemblyName, string typeName) + public Type BindToType(string assemblyName, string typeName) { return SerializationBinder.BindToType(assemblyName, typeName); } - public void BindToName(Type serializedType, out string? assemblyName, out string? typeName) + public void BindToName(Type serializedType, out string assemblyName, out string typeName) { #if HAVE_SERIALIZATION_BINDER_BIND_TO_NAME SerializationBinder.BindToName(serializedType, out assemblyName, out typeName); diff --git a/Libs/Newtonsoft.Json/Serialization/TraceJsonReader.cs b/Libs/Newtonsoft.Json/Serialization/TraceJsonReader.cs index e01a639..832989d 100644 --- a/Libs/Newtonsoft.Json/Serialization/TraceJsonReader.cs +++ b/Libs/Newtonsoft.Json/Serialization/TraceJsonReader.cs @@ -68,16 +68,16 @@ namespace LC.Newtonsoft.Json.Serialization return value; } - public override string? ReadAsString() + public override string ReadAsString() { - string? value = _innerReader.ReadAsString(); + string value = _innerReader.ReadAsString(); WriteCurrentToken(); return value; } - public override byte[]? ReadAsBytes() + public override byte[] ReadAsBytes() { - byte[]? value = _innerReader.ReadAsBytes(); + byte[] value = _innerReader.ReadAsBytes(); WriteCurrentToken(); return value; } @@ -136,9 +136,9 @@ namespace LC.Newtonsoft.Json.Serialization public override JsonToken TokenType => _innerReader.TokenType; - public override object? Value => _innerReader.Value; + public override object Value => _innerReader.Value; - public override Type ?ValueType => _innerReader.ValueType; + public override Type ValueType => _innerReader.ValueType; public override void Close() { diff --git a/Libs/Newtonsoft.Json/Serialization/TraceJsonWriter.cs b/Libs/Newtonsoft.Json/Serialization/TraceJsonWriter.cs index 68c47ce..6d912b8 100644 --- a/Libs/Newtonsoft.Json/Serialization/TraceJsonWriter.cs +++ b/Libs/Newtonsoft.Json/Serialization/TraceJsonWriter.cs @@ -144,7 +144,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - public override void WriteValue(byte[]? value) + public override void WriteValue(byte[] value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); @@ -321,7 +321,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - public override void WriteValue(object? value) + public override void WriteValue(object value) { #if HAVE_BIG_INTEGER if (value is BigInteger) @@ -389,7 +389,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - public override void WriteValue(string? value) + public override void WriteValue(string value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); @@ -459,7 +459,7 @@ namespace LC.Newtonsoft.Json.Serialization } } - public override void WriteValue(Uri? value) + public override void WriteValue(Uri value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); @@ -501,7 +501,7 @@ namespace LC.Newtonsoft.Json.Serialization base.WriteWhitespace(ws); } - public override void WriteComment(string? text) + public override void WriteComment(string text) { _textWriter.WriteComment(text); _innerWriter.WriteComment(text); @@ -566,7 +566,7 @@ namespace LC.Newtonsoft.Json.Serialization base.WriteEndObject(); } - public override void WriteRawValue(string? json) + public override void WriteRawValue(string json) { _textWriter.WriteRawValue(json); _innerWriter.WriteRawValue(json); @@ -575,7 +575,7 @@ namespace LC.Newtonsoft.Json.Serialization InternalWriteValue(JsonToken.Undefined); } - public override void WriteRaw(string? json) + public override void WriteRaw(string json) { _textWriter.WriteRaw(json); _innerWriter.WriteRaw(json); diff --git a/Libs/Newtonsoft.Json/SerializationBinder.cs b/Libs/Newtonsoft.Json/SerializationBinder.cs index 4cc7f59..1fcd35a 100644 --- a/Libs/Newtonsoft.Json/SerializationBinder.cs +++ b/Libs/Newtonsoft.Json/SerializationBinder.cs @@ -17,7 +17,7 @@ namespace LC.Newtonsoft.Json /// Specifies the name of the serialized object. /// Specifies the name of the serialized object /// The type of the object the formatter creates a new instance of. - public abstract Type BindToType(string? assemblyName, string typeName); + public abstract Type BindToType(string assemblyName, string typeName); /// /// When overridden in a derived class, controls the binding of a serialized object to a type. @@ -25,7 +25,7 @@ namespace LC.Newtonsoft.Json /// The type of the object the formatter creates a new instance of. /// Specifies the name of the serialized object. /// Specifies the name of the serialized object. - public virtual void BindToName(Type serializedType, out string? assemblyName, out string? typeName) + public virtual void BindToName(Type serializedType, out string assemblyName, out string typeName) { assemblyName = null; typeName = null; diff --git a/Libs/Newtonsoft.Json/Utilities/AsyncUtils.cs b/Libs/Newtonsoft.Json/Utilities/AsyncUtils.cs index dc4a5eb..d3289d5 100644 --- a/Libs/Newtonsoft.Json/Utilities/AsyncUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/AsyncUtils.cs @@ -40,12 +40,12 @@ namespace LC.Newtonsoft.Json.Utilities internal static Task ToAsync(this bool value) => value ? True : False; - public static Task? CancelIfRequestedAsync(this CancellationToken cancellationToken) + public static Task CancelIfRequestedAsync(this CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : null; } - public static Task? CancelIfRequestedAsync(this CancellationToken cancellationToken) + public static Task CancelIfRequestedAsync(this CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : null; } @@ -54,16 +54,14 @@ namespace LC.Newtonsoft.Json.Utilities // previous frameworks. public static Task FromCanceled(this CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(cancellationToken.IsCancellationRequested); + Debug.Assert(cancellationToken.IsCancellationRequested); return new Task(() => {}, cancellationToken); } public static Task FromCanceled(this CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(cancellationToken.IsCancellationRequested); -#pragma warning disable CS8603 // Possible null reference return. + Debug.Assert(cancellationToken.IsCancellationRequested); return new Task(() => default, cancellationToken); -#pragma warning restore CS8603 // Possible null reference return. } // Task.Delay(0) is optimised as a cached task within the framework, and indeed @@ -73,25 +71,25 @@ namespace LC.Newtonsoft.Json.Utilities public static Task WriteAsync(this TextWriter writer, char value, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(writer != null); + Debug.Assert(writer != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value); } - public static Task WriteAsync(this TextWriter writer, string? value, CancellationToken cancellationToken) + public static Task WriteAsync(this TextWriter writer, string value, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(writer != null); + Debug.Assert(writer != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value); } public static Task WriteAsync(this TextWriter writer, char[] value, int start, int count, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(writer != null); + Debug.Assert(writer != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value, start, count); } public static Task ReadAsync(this TextReader reader, char[] buffer, int index, int count, CancellationToken cancellationToken) { - MiscellaneousUtils.Assert(reader != null); + Debug.Assert(reader != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : reader.ReadAsync(buffer, index, count); } diff --git a/Libs/Newtonsoft.Json/Utilities/Base64Encoder.cs b/Libs/Newtonsoft.Json/Utilities/Base64Encoder.cs index 4d9130f..d0e7bd7 100644 --- a/Libs/Newtonsoft.Json/Utilities/Base64Encoder.cs +++ b/Libs/Newtonsoft.Json/Utilities/Base64Encoder.cs @@ -40,7 +40,7 @@ namespace LC.Newtonsoft.Json.Utilities private readonly char[] _charsLine = new char[Base64LineSize]; private readonly TextWriter _writer; - private byte[]? _leftOverBytes; + private byte[] _leftOverBytes; private int _leftOverBytesCount; public Base64Encoder(TextWriter writer) @@ -128,7 +128,7 @@ namespace LC.Newtonsoft.Json.Utilities int leftOverBytesCount = _leftOverBytesCount; while (leftOverBytesCount < 3 && count > 0) { - _leftOverBytes![leftOverBytesCount++] = buffer[index++]; + _leftOverBytes[leftOverBytesCount++] = buffer[index++]; count--; } diff --git a/Libs/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs b/Libs/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs index 1e8bf88..fda093c 100644 --- a/Libs/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs +++ b/Libs/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs @@ -63,7 +63,7 @@ namespace LC.Newtonsoft.Json.Utilities { if (_firstToSecond.TryGetValue(first, out TSecond existingSecond)) { - if (!existingSecond!.Equals(second)) + if (!existingSecond.Equals(second)) { throw new ArgumentException(_duplicateFirstErrorMessage.FormatWith(CultureInfo.InvariantCulture, first)); } @@ -71,7 +71,7 @@ namespace LC.Newtonsoft.Json.Utilities if (_secondToFirst.TryGetValue(second, out TFirst existingFirst)) { - if (!existingFirst!.Equals(first)) + if (!existingFirst.Equals(first)) { throw new ArgumentException(_duplicateSecondErrorMessage.FormatWith(CultureInfo.InvariantCulture, second)); } diff --git a/Libs/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Libs/Newtonsoft.Json/Utilities/CollectionUtils.cs index d8fd400..6bf1ca0 100644 --- a/Libs/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -116,17 +116,17 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) + public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) { Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType); return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument); } - public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) + public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) { Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); - ConstructorInfo? match = null; + ConstructorInfo match = null; foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { @@ -248,7 +248,6 @@ namespace LC.Newtonsoft.Json.Utilities return i; } } - return -1; } @@ -366,16 +365,26 @@ namespace LC.Newtonsoft.Json.Utilities return multidimensionalArray; } + // 4.6 has Array.Empty to return a cached empty array. Lacking that in other + // frameworks, Enumerable.Empty happens to be implemented as a cached empty + // array in all versions (in .NET Core the same instance as Array.Empty). + // This includes the internal Linq bridge for 2.0. + // Since this method is simple and only 11 bytes long in a release build it's + // pretty much guaranteed to be inlined, giving us fast access of that cached + // array. With 4.5 and up we use AggressiveInlining just to be sure, so it's + // effectively the same as calling Array.Empty even when not available. +#if HAVE_METHOD_IMPL_ATTRIBUTE + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif public static T[] ArrayEmpty() { - // Enumerable.Empty no longer returns an empty array in .NET Core 3.0 - return EmptyArrayContainer.Empty; - } - - private static class EmptyArrayContainer - { + T[] array = Enumerable.Empty() as T[]; + Debug.Assert(array != null); + // Defensively guard against a version of Linq where Enumerable.Empty doesn't + // return an array, but throw in debug versions so a better strategy can be + // used if that ever happens. #pragma warning disable CA1825 // Avoid zero-length array allocations. - public static readonly T[] Empty = new T[0]; + return array ?? new T[0]; #pragma warning restore CA1825 // Avoid zero-length array allocations. } } diff --git a/Libs/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Libs/Newtonsoft.Json/Utilities/CollectionWrapper.cs index d16b1b7..bc59f1e 100644 --- a/Libs/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Libs/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -44,9 +44,9 @@ namespace LC.Newtonsoft.Json.Utilities internal class CollectionWrapper : ICollection, IWrappedCollection { - private readonly IList? _list; - private readonly ICollection? _genericCollection; - private object? _syncRoot; + private readonly IList _list; + private readonly ICollection _genericCollection; + private object _syncRoot; public CollectionWrapper(IList list) { @@ -77,7 +77,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - _list!.Add(item); + _list.Add(item); } } @@ -89,7 +89,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - _list!.Clear(); + _list.Clear(); } } @@ -101,7 +101,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - return _list!.Contains(item); + return _list.Contains(item); } } @@ -113,7 +113,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - _list!.CopyTo(array, arrayIndex); + _list.CopyTo(array, arrayIndex); } } @@ -127,7 +127,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - return _list!.Count; + return _list.Count; } } } @@ -142,7 +142,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - return _list!.IsReadOnly; + return _list.IsReadOnly; } } } @@ -155,11 +155,11 @@ namespace LC.Newtonsoft.Json.Utilities } else { - bool contains = _list!.Contains(item); + bool contains = _list.Contains(item); if (contains) { - _list!.Remove(item); + _list.Remove(item); } return contains; @@ -173,7 +173,7 @@ namespace LC.Newtonsoft.Json.Utilities IEnumerator IEnumerable.GetEnumerator() { - return ((IEnumerable)_genericCollection! ?? _list!).GetEnumerator(); + return ((IEnumerable)_genericCollection ?? _list).GetEnumerator(); } int IList.Add(object value) @@ -203,7 +203,7 @@ namespace LC.Newtonsoft.Json.Utilities if (IsCompatibleObject(value)) { - return _list!.IndexOf((T)value); + return _list.IndexOf((T)value); } return -1; @@ -216,7 +216,7 @@ namespace LC.Newtonsoft.Json.Utilities throw new InvalidOperationException("Wrapped ICollection does not support RemoveAt."); } - _list!.RemoveAt(index); + _list.RemoveAt(index); } void IList.Insert(int index, object value) @@ -227,7 +227,7 @@ namespace LC.Newtonsoft.Json.Utilities } VerifyValueType(value); - _list!.Insert(index, (T)value); + _list.Insert(index, (T)value); } bool IList.IsFixedSize @@ -241,7 +241,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - return _list!.IsFixedSize; + return _list.IsFixedSize; } } } @@ -263,7 +263,7 @@ namespace LC.Newtonsoft.Json.Utilities throw new InvalidOperationException("Wrapped ICollection does not support indexer."); } - return _list![index]; + return _list[index]; } set { @@ -273,7 +273,7 @@ namespace LC.Newtonsoft.Json.Utilities } VerifyValueType(value); - _list![index] = (T)value; + _list[index] = (T)value; } } @@ -315,6 +315,6 @@ namespace LC.Newtonsoft.Json.Utilities return true; } - public object UnderlyingCollection => (object)_genericCollection! ?? _list!; + public object UnderlyingCollection => (object)_genericCollection ?? _list; } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Libs/Newtonsoft.Json/Utilities/ConvertUtils.cs index 3356735..d3eba4e 100644 --- a/Libs/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -27,7 +27,6 @@ using System; using System.Collections.Generic; using System.Globalization; using System.ComponentModel; -using System.Runtime.CompilerServices; #if HAVE_BIG_INTEGER using System.Numerics; #endif @@ -37,7 +36,6 @@ using System.Text.RegularExpressions; #endif using LC.Newtonsoft.Json.Serialization; using System.Reflection; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #endif @@ -96,14 +94,8 @@ namespace LC.Newtonsoft.Json.Utilities internal class TypeInformation { - public Type Type { get; } - public PrimitiveTypeCode TypeCode { get; } - - public TypeInformation(Type type, PrimitiveTypeCode typeCode) - { - Type = type; - TypeCode = typeCode; - } + public Type Type { get; set; } + public PrimitiveTypeCode TypeCode { get; set; } } internal enum ParseResult @@ -171,25 +163,25 @@ namespace LC.Newtonsoft.Json.Utilities private static readonly TypeInformation[] PrimitiveTypeCodes = { // need all of these. lookup against the index with TypeCode value - new TypeInformation(typeof(object), PrimitiveTypeCode.Empty), - new TypeInformation(typeof(object), PrimitiveTypeCode.Object), - new TypeInformation(typeof(object), PrimitiveTypeCode.DBNull), - new TypeInformation(typeof(bool), PrimitiveTypeCode.Boolean), - new TypeInformation(typeof(char), PrimitiveTypeCode.Char), - new TypeInformation(typeof(sbyte), PrimitiveTypeCode.SByte), - new TypeInformation(typeof(byte), PrimitiveTypeCode.Byte), - new TypeInformation(typeof(short), PrimitiveTypeCode.Int16), - new TypeInformation(typeof(ushort), PrimitiveTypeCode.UInt16), - new TypeInformation(typeof(int), PrimitiveTypeCode.Int32), - new TypeInformation(typeof(uint), PrimitiveTypeCode.UInt32), - new TypeInformation(typeof(long), PrimitiveTypeCode.Int64), - new TypeInformation(typeof(ulong), PrimitiveTypeCode.UInt64), - new TypeInformation(typeof(float), PrimitiveTypeCode.Single), - new TypeInformation(typeof(double), PrimitiveTypeCode.Double), - new TypeInformation(typeof(decimal), PrimitiveTypeCode.Decimal), - new TypeInformation(typeof(DateTime), PrimitiveTypeCode.DateTime), - new TypeInformation(typeof(object), PrimitiveTypeCode.Empty), // no 17 in TypeCode for some reason - new TypeInformation(typeof(string), PrimitiveTypeCode.String) + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Object }, + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.DBNull }, + new TypeInformation { Type = typeof(bool), TypeCode = PrimitiveTypeCode.Boolean }, + new TypeInformation { Type = typeof(char), TypeCode = PrimitiveTypeCode.Char }, + new TypeInformation { Type = typeof(sbyte), TypeCode = PrimitiveTypeCode.SByte }, + new TypeInformation { Type = typeof(byte), TypeCode = PrimitiveTypeCode.Byte }, + new TypeInformation { Type = typeof(short), TypeCode = PrimitiveTypeCode.Int16 }, + new TypeInformation { Type = typeof(ushort), TypeCode = PrimitiveTypeCode.UInt16 }, + new TypeInformation { Type = typeof(int), TypeCode = PrimitiveTypeCode.Int32 }, + new TypeInformation { Type = typeof(uint), TypeCode = PrimitiveTypeCode.UInt32 }, + new TypeInformation { Type = typeof(long), TypeCode = PrimitiveTypeCode.Int64 }, + new TypeInformation { Type = typeof(ulong), TypeCode = PrimitiveTypeCode.UInt64 }, + new TypeInformation { Type = typeof(float), TypeCode = PrimitiveTypeCode.Single }, + new TypeInformation { Type = typeof(double), TypeCode = PrimitiveTypeCode.Double }, + new TypeInformation { Type = typeof(decimal), TypeCode = PrimitiveTypeCode.Decimal }, + new TypeInformation { Type = typeof(DateTime), TypeCode = PrimitiveTypeCode.DateTime }, + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, // no 17 in TypeCode for some reason + new TypeInformation { Type = typeof(string), TypeCode = PrimitiveTypeCode.String } }; #endif @@ -256,10 +248,10 @@ namespace LC.Newtonsoft.Json.Utilities #endif } - private static readonly ThreadSafeStore, Func?> CastConverters = - new ThreadSafeStore, Func?>(CreateCastConverter); + private static readonly ThreadSafeStore, Func> CastConverters = + new ThreadSafeStore, Func>(CreateCastConverter); - private static Func? CreateCastConverter(StructMultiKey t) + private static Func CreateCastConverter(StructMultiKey t) { Type initialType = t.Value1; Type targetType = t.Value2; @@ -271,7 +263,7 @@ namespace LC.Newtonsoft.Json.Utilities return null; } - MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(castMethodInfo); + MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(castMethodInfo); return o => call(null, o); } @@ -371,10 +363,10 @@ namespace LC.Newtonsoft.Json.Utilities public static object Convert(object initialValue, CultureInfo culture, Type targetType) { - switch (TryConvertInternal(initialValue, culture, targetType, out object? value)) + switch (TryConvertInternal(initialValue, culture, targetType, out object value)) { case ConvertResult.Success: - return value!; + return value; case ConvertResult.CannotConvertNull: throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); case ConvertResult.NotInstantiableType: @@ -386,7 +378,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value) + private static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object value) { try { @@ -405,7 +397,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - private static ConvertResult TryConvertInternal(object? initialValue, CultureInfo culture, Type targetType, out object? value) + private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value) { if (initialValue == null) { @@ -490,7 +482,7 @@ namespace LC.Newtonsoft.Json.Utilities } if (targetType == typeof(Version)) { - if (VersionTryParse(s, out Version? result)) + if (VersionTryParse(s, out Version result)) { value = result; return ConvertResult.Success; @@ -575,7 +567,7 @@ namespace LC.Newtonsoft.Json.Utilities /// The converted type. If conversion was unsuccessful, the initial value /// is returned if assignable to the target type. /// - public static object? ConvertOrCast(object? initialValue, CultureInfo culture, Type targetType) + public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType) { if (targetType == typeof(object)) { @@ -587,27 +579,27 @@ namespace LC.Newtonsoft.Json.Utilities return null; } - if (TryConvert(initialValue, culture, targetType, out object? convertedValue)) + if (TryConvert(initialValue, culture, targetType, out object convertedValue)) { return convertedValue; } - return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue)!, targetType); + return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); } #endregion - private static object? EnsureTypeAssignable(object? value, Type initialType, Type targetType) + private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { + Type valueType = value?.GetType(); + if (value != null) { - Type valueType = value.GetType(); - if (targetType.IsAssignableFrom(valueType)) { return value; } - Func? castConverter = CastConverters.Get(new StructMultiKey(valueType, targetType)); + Func castConverter = CastConverters.Get(new StructMultiKey(valueType, targetType)); if (castConverter != null) { return castConverter(value); @@ -624,7 +616,7 @@ namespace LC.Newtonsoft.Json.Utilities throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType?.ToString() ?? "{null}", targetType)); } - public static bool VersionTryParse(string input, [NotNullWhen(true)]out Version? result) + public static bool VersionTryParse(string input, out Version result) { #if HAVE_VERSION_TRY_PARSE return Version.TryParse(input, out result); diff --git a/Libs/Newtonsoft.Json/Utilities/DateTimeUtils.cs b/Libs/Newtonsoft.Json/Utilities/DateTimeUtils.cs index 5301d0f..ecd9219 100644 --- a/Libs/Newtonsoft.Json/Utilities/DateTimeUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/DateTimeUtils.cs @@ -179,9 +179,9 @@ namespace LC.Newtonsoft.Json.Utilities internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset) { - long universalTicks = ToUniversalTicks(dateTime, offset); + long universialTicks = ToUniversalTicks(dateTime, offset); - return UniversalTicksToJavaScriptTicks(universalTicks); + return UniversialTicksToJavaScriptTicks(universialTicks); } internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime) @@ -193,12 +193,12 @@ namespace LC.Newtonsoft.Json.Utilities { long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks; - return UniversalTicksToJavaScriptTicks(ticks); + return UniversialTicksToJavaScriptTicks(ticks); } - private static long UniversalTicksToJavaScriptTicks(long universalTicks) + private static long UniversialTicksToJavaScriptTicks(long universialTicks) { - long javaScriptTicks = (universalTicks - InitialJavaScriptDateTicks) / 10000; + long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000; return javaScriptTicks; } @@ -341,7 +341,7 @@ namespace LC.Newtonsoft.Json.Utilities return d; } - internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling dateTimeZoneHandling, string? dateFormatString, CultureInfo culture, out DateTime dt) + internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) { if (s.Length > 0) { @@ -364,7 +364,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - if (!StringUtils.IsNullOrEmpty(dateFormatString)) + if (!string.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeExact(s.ToString(), dateTimeZoneHandling, dateFormatString, culture, out dt)) { @@ -377,7 +377,7 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string? dateFormatString, CultureInfo culture, out DateTime dt) + internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) { if (s.Length > 0) { @@ -400,7 +400,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - if (!StringUtils.IsNullOrEmpty(dateFormatString)) + if (!string.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeExact(s, dateTimeZoneHandling, dateFormatString, culture, out dt)) { @@ -414,7 +414,7 @@ namespace LC.Newtonsoft.Json.Utilities } #if HAVE_DATE_TIME_OFFSET - internal static bool TryParseDateTimeOffset(StringReference s, string? dateFormatString, CultureInfo culture, out DateTimeOffset dt) + internal static bool TryParseDateTimeOffset(StringReference s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) { if (s.Length > 0) { @@ -437,7 +437,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - if (!StringUtils.IsNullOrEmpty(dateFormatString)) + if (!string.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeOffsetExact(s.ToString(), dateFormatString, culture, out dt)) { @@ -450,7 +450,7 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - internal static bool TryParseDateTimeOffset(string s, string? dateFormatString, CultureInfo culture, out DateTimeOffset dt) + internal static bool TryParseDateTimeOffset(string s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) { if (s.Length > 0) { @@ -475,7 +475,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - if (!StringUtils.IsNullOrEmpty(dateFormatString)) + if (!string.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeOffsetExact(s, dateFormatString, culture, out dt)) { @@ -618,9 +618,9 @@ namespace LC.Newtonsoft.Json.Utilities #endregion #region Write - internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string? formatString, CultureInfo culture) + internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string formatString, CultureInfo culture) { - if (StringUtils.IsNullOrEmpty(formatString)) + if (string.IsNullOrEmpty(formatString)) { char[] chars = new char[64]; int pos = WriteDateTimeString(chars, 0, value, null, value.Kind, format); @@ -751,9 +751,9 @@ namespace LC.Newtonsoft.Json.Utilities } #if HAVE_DATE_TIME_OFFSET - internal static void WriteDateTimeOffsetString(TextWriter writer, DateTimeOffset value, DateFormatHandling format, string? formatString, CultureInfo culture) + internal static void WriteDateTimeOffsetString(TextWriter writer, DateTimeOffset value, DateFormatHandling format, string formatString, CultureInfo culture) { - if (StringUtils.IsNullOrEmpty(formatString)) + if (string.IsNullOrEmpty(formatString)) { char[] chars = new char[64]; int pos = WriteDateTimeString(chars, 0, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format); @@ -822,4 +822,4 @@ namespace LC.Newtonsoft.Json.Utilities day = n - days[m - 1] + 1; } } -} +} \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/Libs/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index 6120a0b..e10cea0 100644 --- a/Libs/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/Libs/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -27,13 +27,11 @@ using System; using System.Collections.Generic; using System.Collections; using System.Threading; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace LC.Newtonsoft.Json.Utilities @@ -46,12 +44,12 @@ namespace LC.Newtonsoft.Json.Utilities internal class DictionaryWrapper : IDictionary, IWrappedDictionary { - private readonly IDictionary? _dictionary; - private readonly IDictionary? _genericDictionary; + private readonly IDictionary _dictionary; + private readonly IDictionary _genericDictionary; #if HAVE_READ_ONLY_COLLECTIONS - private readonly IReadOnlyDictionary? _readOnlyDictionary; + private readonly IReadOnlyDictionary _readOnlyDictionary; #endif - private object? _syncRoot; + private object _syncRoot; public DictionaryWrapper(IDictionary dictionary) { @@ -76,15 +74,6 @@ namespace LC.Newtonsoft.Json.Utilities } #endif - internal IDictionary GenericDictionary - { - get - { - MiscellaneousUtils.Assert(_genericDictionary != null); - return _genericDictionary; - } - } - public void Add(TKey key, TValue value) { if (_dictionary != null) @@ -115,7 +104,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.ContainsKey(key); + return _genericDictionary.ContainsKey(key); } } @@ -135,7 +124,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.Keys; + return _genericDictionary.Keys; } } } @@ -162,21 +151,17 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.Remove(key); + return _genericDictionary.Remove(key); } } -#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). - public bool TryGetValue(TKey key, out TValue? value) -#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). + public bool TryGetValue(TKey key, out TValue value) { if (_dictionary != null) { if (!_dictionary.Contains(key)) { -#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. value = default; -#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. return false; } else @@ -193,7 +178,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.TryGetValue(key, out value); + return _genericDictionary.TryGetValue(key, out value); } } @@ -213,7 +198,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.Values; + return _genericDictionary.Values; } } } @@ -234,7 +219,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary[key]; + return _genericDictionary[key]; } } set @@ -251,7 +236,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - GenericDictionary[key] = value; + _genericDictionary[key] = value; } } } @@ -288,7 +273,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - GenericDictionary.Clear(); + _genericDictionary.Clear(); } } @@ -306,7 +291,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.Contains(item); + return _genericDictionary.Contains(item); } } @@ -337,7 +322,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - GenericDictionary.CopyTo(array, arrayIndex); + _genericDictionary.CopyTo(array, arrayIndex); } } @@ -357,7 +342,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.Count; + return _genericDictionary.Count; } } } @@ -378,7 +363,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.IsReadOnly; + return _genericDictionary.IsReadOnly; } } } @@ -414,7 +399,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.Remove(item); + return _genericDictionary.Remove(item); } } @@ -432,7 +417,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary.GetEnumerator(); + return _genericDictionary.GetEnumerator(); } } @@ -455,11 +440,11 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - GenericDictionary.Add((TKey)key, (TValue)value); + _genericDictionary.Add((TKey)key, (TValue)value); } } - object? IDictionary.this[object key] + object IDictionary.this[object key] { get { @@ -475,7 +460,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary[(TKey)key]; + return _genericDictionary[(TKey)key]; } } set @@ -492,13 +477,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - // Consider changing this code to call GenericDictionary.Remove when value is null. - // -#pragma warning disable CS8601 // Possible null reference assignment. -#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. - GenericDictionary[(TKey)key] = (TValue)value; -#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. -#pragma warning restore CS8601 // Possible null reference assignment. + _genericDictionary[(TKey)key] = (TValue)value; } } } @@ -546,7 +525,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return new DictionaryEnumerator(GenericDictionary.GetEnumerator()); + return new DictionaryEnumerator(_genericDictionary.GetEnumerator()); } } @@ -564,7 +543,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return _dictionary!.Contains(key); + return _dictionary.Contains(key); } } @@ -584,7 +563,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return _dictionary!.IsFixedSize; + return _dictionary.IsFixedSize; } } } @@ -605,7 +584,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return _dictionary!.Keys; + return _dictionary.Keys; } } } @@ -624,7 +603,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - GenericDictionary.Remove((TKey)key); + _genericDictionary.Remove((TKey)key); } } @@ -644,7 +623,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return _dictionary!.Values; + return _dictionary.Values; } } } @@ -663,7 +642,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - GenericDictionary.CopyTo((KeyValuePair[])array, index); + _genericDictionary.CopyTo((KeyValuePair[])array, index); } } @@ -711,7 +690,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif else { - return GenericDictionary; + return _genericDictionary; } } } diff --git a/Libs/Newtonsoft.Json/Utilities/DynamicProxy.cs b/Libs/Newtonsoft.Json/Utilities/DynamicProxy.cs index 7a2ab75..90e9bb0 100644 --- a/Libs/Newtonsoft.Json/Utilities/DynamicProxy.cs +++ b/Libs/Newtonsoft.Json/Utilities/DynamicProxy.cs @@ -36,19 +36,19 @@ namespace LC.Newtonsoft.Json.Utilities return CollectionUtils.ArrayEmpty(); } - public virtual bool TryBinaryOperation(T instance, BinaryOperationBinder binder, object arg, out object? result) + public virtual bool TryBinaryOperation(T instance, BinaryOperationBinder binder, object arg, out object result) { result = null; return false; } - public virtual bool TryConvert(T instance, ConvertBinder binder, out object? result) + public virtual bool TryConvert(T instance, ConvertBinder binder, out object result) { result = null; return false; } - public virtual bool TryCreateInstance(T instance, CreateInstanceBinder binder, object[] args, out object? result) + public virtual bool TryCreateInstance(T instance, CreateInstanceBinder binder, object[] args, out object result) { result = null; return false; @@ -64,25 +64,25 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - public virtual bool TryGetIndex(T instance, GetIndexBinder binder, object[] indexes, out object? result) + public virtual bool TryGetIndex(T instance, GetIndexBinder binder, object[] indexes, out object result) { result = null; return false; } - public virtual bool TryGetMember(T instance, GetMemberBinder binder, out object? result) + public virtual bool TryGetMember(T instance, GetMemberBinder binder, out object result) { result = null; return false; } - public virtual bool TryInvoke(T instance, InvokeBinder binder, object[] args, out object? result) + public virtual bool TryInvoke(T instance, InvokeBinder binder, object[] args, out object result) { result = null; return false; } - public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object? result) + public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object result) { result = null; return false; @@ -98,7 +98,7 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - public virtual bool TryUnaryOperation(T instance, UnaryOperationBinder binder, out object? result) + public virtual bool TryUnaryOperation(T instance, UnaryOperationBinder binder, out object result) { result = null; return false; diff --git a/Libs/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Libs/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index 7b3952e..cfb8bbe 100644 --- a/Libs/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Libs/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -164,7 +164,7 @@ namespace LC.Newtonsoft.Json.Utilities : base.BindDeleteIndex(binder, indexes); } - private delegate DynamicMetaObject Fallback(DynamicMetaObject? errorSuggestion); + private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); private static Expression[] NoArgs => CollectionUtils.ArrayEmpty(); @@ -206,7 +206,7 @@ namespace LC.Newtonsoft.Json.Utilities /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic that returns a result /// - private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, Fallback fallback, Fallback? fallbackInvoke = null) + private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, Fallback fallback, Fallback fallbackInvoke = null) { // // First, call fallback to do default binding @@ -217,7 +217,7 @@ namespace LC.Newtonsoft.Json.Utilities return BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke); } - private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, DynamicMetaObject fallbackResult, Fallback? fallbackInvoke) + private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) { // // Build a new expression like: diff --git a/Libs/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Libs/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index 0006d08..2636c63 100644 --- a/Libs/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Libs/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -40,7 +40,7 @@ namespace LC.Newtonsoft.Json.Utilities { internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory(); - private static DynamicMethod CreateDynamicMethod(string name, Type? returnType, Type[] parameterTypes, Type owner) + private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { DynamicMethod dynamicMethod = !owner.IsInterface() ? new DynamicMethod(name, returnType, parameterTypes, owner, true) @@ -59,14 +59,14 @@ namespace LC.Newtonsoft.Json.Utilities return (ObjectConstructor)dynamicMethod.CreateDelegate(typeof(ObjectConstructor)); } - public override MethodCall CreateMethodCall(MethodBase method) + public override MethodCall CreateMethodCall(MethodBase method) { DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator, 1); - return (MethodCall)dynamicMethod.CreateDelegate(typeof(MethodCall)); + return (MethodCall)dynamicMethod.CreateDelegate(typeof(MethodCall)); } private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator, int argsIndex) @@ -93,9 +93,6 @@ namespace LC.Newtonsoft.Json.Utilities LocalBuilder localConvertible = generator.DeclareLocal(typeof(IConvertible)); LocalBuilder localObject = generator.DeclareLocal(typeof(object)); - OpCode variableAddressOpCode = args.Length < 256 ? OpCodes.Ldloca_S : OpCodes.Ldloca; - OpCode variableLoadOpCode = args.Length < 256 ? OpCodes.Ldloc_S : OpCodes.Ldloc; - for (int i = 0; i < args.Length; i++) { ParameterInfo parameter = args[i]; @@ -121,7 +118,7 @@ namespace LC.Newtonsoft.Json.Utilities generator.Emit(OpCodes.Brtrue_S, skipSettingDefault); // parameter has no value, initialize to default - generator.Emit(variableAddressOpCode, localVariable); + generator.Emit(OpCodes.Ldloca_S, localVariable); generator.Emit(OpCodes.Initobj, parameterType); generator.Emit(OpCodes.Br_S, finishedProcessingParameter); @@ -141,7 +138,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - generator.Emit(variableAddressOpCode, localVariable); + generator.Emit(OpCodes.Ldloca_S, localVariable); } else if (parameterType.IsValueType()) { @@ -159,9 +156,9 @@ namespace LC.Newtonsoft.Json.Utilities // parameter has no value, initialize to default LocalBuilder localVariable = generator.DeclareLocal(parameterType); - generator.Emit(variableAddressOpCode, localVariable); + generator.Emit(OpCodes.Ldloca_S, localVariable); generator.Emit(OpCodes.Initobj, parameterType); - generator.Emit(variableLoadOpCode, localVariable); + generator.Emit(OpCodes.Ldloc_S, localVariable); generator.Emit(OpCodes.Br_S, finishedProcessingParameter); // argument has value, try to convert it to parameter type @@ -282,14 +279,14 @@ namespace LC.Newtonsoft.Json.Utilities generator.Return(); } - public override Func CreateGet(PropertyInfo propertyInfo) + public override Func CreateGet(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetPropertyIL(propertyInfo, generator); - return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); } private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) @@ -310,12 +307,12 @@ namespace LC.Newtonsoft.Json.Utilities generator.Return(); } - public override Func CreateGet(FieldInfo fieldInfo) + public override Func CreateGet(FieldInfo fieldInfo) { if (fieldInfo.IsLiteral) { object constantValue = fieldInfo.GetValue(null); - Func getter = o => constantValue; + Func getter = o => constantValue; return getter; } @@ -324,7 +321,7 @@ namespace LC.Newtonsoft.Json.Utilities GenerateCreateGetFieldIL(fieldInfo, generator); - return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); } private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator) @@ -343,14 +340,14 @@ namespace LC.Newtonsoft.Json.Utilities generator.Return(); } - public override Action CreateSet(FieldInfo fieldInfo) + public override Action CreateSet(FieldInfo fieldInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetFieldIL(fieldInfo, generator); - return (Action)dynamicMethod.CreateDelegate(typeof(Action)); + return (Action)dynamicMethod.CreateDelegate(typeof(Action)); } internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator) @@ -375,14 +372,14 @@ namespace LC.Newtonsoft.Json.Utilities generator.Return(); } - public override Action CreateSet(PropertyInfo propertyInfo) + public override Action CreateSet(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetPropertyIL(propertyInfo, generator); - return (Action)dynamicMethod.CreateDelegate(typeof(Action)); + return (Action)dynamicMethod.CreateDelegate(typeof(Action)); } internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) diff --git a/Libs/Newtonsoft.Json/Utilities/DynamicUtils.cs b/Libs/Newtonsoft.Json/Utilities/DynamicUtils.cs index 8ad9f46..35357c8 100644 --- a/Libs/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -38,7 +38,6 @@ using System.Runtime.CompilerServices; using System.Text; using System.Globalization; using LC.Newtonsoft.Json.Serialization; -using System.Diagnostics; namespace LC.Newtonsoft.Json.Utilities { @@ -54,10 +53,10 @@ namespace LC.Newtonsoft.Json.Utilities private const string CSharpArgumentInfoFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, " + CSharpAssemblyName; private const string CSharpBinderFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, " + CSharpAssemblyName; - private static object? _getCSharpArgumentInfoArray; - private static object? _setCSharpArgumentInfoArray; - private static MethodCall? _getMemberCall; - private static MethodCall? _setMemberCall; + private static object _getCSharpArgumentInfoArray; + private static object _setCSharpArgumentInfoArray; + private static MethodCall _getMemberCall; + private static MethodCall _setMemberCall; private static bool _init; private static void Init() @@ -90,7 +89,7 @@ namespace LC.Newtonsoft.Json.Utilities for (int i = 0; i < values.Length; i++) { MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) }); - object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null }); + object arg = createArgumentInfoMethod.Invoke(null, new object[] { 0, null }); a.SetValue(arg, i); } @@ -106,10 +105,10 @@ namespace LC.Newtonsoft.Json.Utilities Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType); MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); - _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); + _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); - _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); + _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); } #endif @@ -117,9 +116,7 @@ namespace LC.Newtonsoft.Json.Utilities { #if !HAVE_REFLECTION_BINDER Init(); - MiscellaneousUtils.Assert(_getMemberCall != null); - MiscellaneousUtils.Assert(_getCSharpArgumentInfoArray != null); - return (CallSiteBinder)_getMemberCall(null, 0, name, context, _getCSharpArgumentInfoArray)!; + return (CallSiteBinder)_getMemberCall(null, 0, name, context, _getCSharpArgumentInfoArray); #else return Binder.GetMember( CSharpBinderFlags.None, name, context, new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); @@ -130,9 +127,7 @@ namespace LC.Newtonsoft.Json.Utilities { #if !HAVE_REFLECTION_BINDER Init(); - MiscellaneousUtils.Assert(_setMemberCall != null); - MiscellaneousUtils.Assert(_setCSharpArgumentInfoArray != null); - return (CallSiteBinder)_setMemberCall(null, 0, name, context, _setCSharpArgumentInfoArray)!; + return (CallSiteBinder)_setMemberCall(null, 0, name, context, _setCSharpArgumentInfoArray); #else return Binder.SetMember( CSharpBinderFlags.None, name, context, new[] diff --git a/Libs/Newtonsoft.Json/Utilities/EnumUtils.cs b/Libs/Newtonsoft.Json/Utilities/EnumUtils.cs index ba30a67..9df7f00 100644 --- a/Libs/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -36,8 +36,6 @@ using System.Linq; using System.Reflection; using System.Text; using LC.Newtonsoft.Json.Serialization; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; namespace LC.Newtonsoft.Json.Utilities { @@ -46,30 +44,27 @@ namespace LC.Newtonsoft.Json.Utilities private const char EnumSeparatorChar = ','; private const string EnumSeparatorString = ", "; - private static readonly ThreadSafeStore, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore, EnumInfo>(InitializeValuesAndNames); + private static readonly ThreadSafeStore, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore, EnumInfo>(InitializeValuesAndNames); - private static EnumInfo InitializeValuesAndNames(StructMultiKey key) + private static EnumInfo InitializeValuesAndNames(StructMultiKey key) { Type enumType = key.Value1; string[] names = Enum.GetNames(enumType); string[] resolvedNames = new string[names.Length]; ulong[] values = new ulong[names.Length]; - bool hasSpecifiedName; for (int i = 0; i < names.Length; i++) { string name = names[i]; - FieldInfo f = enumType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; + FieldInfo f = enumType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); values[i] = ToUInt64(f.GetValue(null)); string resolvedName; #if HAVE_DATA_CONTRACTS - string specifiedName = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) + resolvedName = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) .Cast() .Select(a => a.Value) - .SingleOrDefault(); - hasSpecifiedName = specifiedName != null; - resolvedName = specifiedName ?? name; + .SingleOrDefault() ?? f.Name; if (Array.IndexOf(resolvedNames, resolvedName, 0, i) != -1) { @@ -77,11 +72,10 @@ namespace LC.Newtonsoft.Json.Utilities } #else resolvedName = name; - hasSpecifiedName = false; #endif resolvedNames[i] = key.Value2 != null - ? key.Value2.GetPropertyName(resolvedName, hasSpecifiedName) + ? key.Value2.GetPropertyName(resolvedName, false) : resolvedName; } @@ -125,14 +119,14 @@ namespace LC.Newtonsoft.Json.Utilities // Used by Newtonsoft.Json.Schema private static CamelCaseNamingStrategy _camelCaseNamingStrategy = new CamelCaseNamingStrategy(); - public static bool TryToString(Type enumType, object value, bool camelCase, [NotNullWhen(true)]out string? name) + public static bool TryToString(Type enumType, object value, bool camelCase, out string name) { return TryToString(enumType, value, camelCase ? _camelCaseNamingStrategy : null, out name); } - public static bool TryToString(Type enumType, object value, NamingStrategy? namingStrategy, [NotNullWhen(true)]out string? name) + public static bool TryToString(Type enumType, object value, NamingStrategy namingStrategy, out string name) { - EnumInfo enumInfo = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); + EnumInfo enumInfo = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); ulong v = ToUInt64(value); if (!enumInfo.IsFlags) @@ -155,7 +149,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - private static string? InternalFlagsFormat(EnumInfo entry, ulong result) + private static string InternalFlagsFormat(EnumInfo entry, ulong result) { string[] resolvedNames = entry.ResolvedNames; ulong[] values = entry.Values; @@ -191,7 +185,7 @@ namespace LC.Newtonsoft.Json.Utilities index--; } - string? returnString; + string returnString; if (result != 0) { // We were unable to represent this number as a bitwise or of valid flags @@ -219,7 +213,7 @@ namespace LC.Newtonsoft.Json.Utilities public static EnumInfo GetEnumValuesAndNames(Type enumType) { - return ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, null)); + return ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, null)); } private static ulong ToUInt64(object value) @@ -255,7 +249,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - public static object ParseEnum(Type enumType, NamingStrategy? namingStrategy, string value, bool disallowNumber) + public static object ParseEnum(Type enumType, NamingStrategy namingStrategy, string value, bool disallowNumber) { ValidationUtils.ArgumentNotNull(enumType, nameof(enumType)); ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -265,7 +259,7 @@ namespace LC.Newtonsoft.Json.Utilities throw new ArgumentException("Type provided must be an Enum.", nameof(enumType)); } - EnumInfo entry = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); + EnumInfo entry = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); string[] enumNames = entry.Names; string[] resolvedNames = entry.ResolvedNames; ulong[] enumValues = entry.Values; @@ -298,7 +292,7 @@ namespace LC.Newtonsoft.Json.Utilities Type underlyingType = Enum.GetUnderlyingType(enumType); value = value.Trim(); - object? temp = null; + object temp = null; try { diff --git a/Libs/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/Libs/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index d267c02..409a415 100644 --- a/Libs/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/Libs/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -57,7 +57,7 @@ namespace LC.Newtonsoft.Json.Utilities return compiled; } - public override MethodCall CreateMethodCall(MethodBase method) + public override MethodCall CreateMethodCall(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -70,7 +70,7 @@ namespace LC.Newtonsoft.Json.Utilities LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall), callExpression, targetParameterExpression, argsParameterExpression); - MethodCall compiled = (MethodCall)lambdaExpression.Compile(); + MethodCall compiled = (MethodCall)lambdaExpression.Compile(); return compiled; } @@ -79,16 +79,9 @@ namespace LC.Newtonsoft.Json.Utilities public Expression Value; public ParameterExpression Variable; public bool IsOut; - - public ByRefParameter(Expression value, ParameterExpression variable, bool isOut) - { - Value = value; - Variable = variable; - IsOut = isOut; - } } - private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression? targetParameterExpression, ParameterExpression argsParameterExpression) + private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression) { ParameterInfo[] parametersInfo = method.GetParameters(); @@ -124,7 +117,7 @@ namespace LC.Newtonsoft.Json.Utilities if (isByRef) { ParameterExpression variable = Expression.Variable(parameterType); - refParameterMap.Add(new ByRefParameter(argExpression, variable, parameter.IsOut)); + refParameterMap.Add(new ByRefParameter {Value = argExpression, Variable = variable, IsOut = parameter.IsOut}); argExpression = variable; } @@ -144,7 +137,7 @@ namespace LC.Newtonsoft.Json.Utilities } else { - Expression readParameter = EnsureCastExpression(targetParameterExpression!, method.DeclaringType); + Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType); callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } @@ -218,7 +211,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - public override Func CreateGet(PropertyInfo propertyInfo) + public override Func CreateGet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); @@ -228,11 +221,7 @@ namespace LC.Newtonsoft.Json.Utilities ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance"); Expression resultExpression; - MethodInfo? getMethod = propertyInfo.GetGetMethod(true); - if (getMethod == null) - { - throw new ArgumentException("Property does not have a getter."); - } + MethodInfo getMethod = propertyInfo.GetGetMethod(true); if (getMethod.IsStatic) { @@ -249,11 +238,11 @@ namespace LC.Newtonsoft.Json.Utilities LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func), resultExpression, parameterExpression); - Func compiled = (Func)lambdaExpression.Compile(); + Func compiled = (Func)lambdaExpression.Compile(); return compiled; } - public override Func CreateGet(FieldInfo fieldInfo) + public override Func CreateGet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -273,11 +262,11 @@ namespace LC.Newtonsoft.Json.Utilities fieldExpression = EnsureCastExpression(fieldExpression, typeof(object)); - Func compiled = Expression.Lambda>(fieldExpression, sourceParameter).Compile(); + Func compiled = Expression.Lambda>(fieldExpression, sourceParameter).Compile(); return compiled; } - public override Action CreateSet(FieldInfo fieldInfo) + public override Action CreateSet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -309,11 +298,11 @@ namespace LC.Newtonsoft.Json.Utilities LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action), assignExpression, sourceParameterExpression, valueParameterExpression); - Action compiled = (Action)lambdaExpression.Compile(); + Action compiled = (Action)lambdaExpression.Compile(); return compiled; } - public override Action CreateSet(PropertyInfo propertyInfo) + public override Action CreateSet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); @@ -332,11 +321,7 @@ namespace LC.Newtonsoft.Json.Utilities ParameterExpression valueParameter = Expression.Parameter(valueType, "value"); Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType); - MethodInfo? setMethod = propertyInfo.GetSetMethod(true); - if (setMethod == null) - { - throw new ArgumentException("Property does not have a setter."); - } + MethodInfo setMethod = propertyInfo.GetSetMethod(true); Expression setExpression; if (setMethod.IsStatic) @@ -350,9 +335,9 @@ namespace LC.Newtonsoft.Json.Utilities setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); } - LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action), setExpression, instanceParameter, valueParameter); + LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action), setExpression, instanceParameter, valueParameter); - Action compiled = (Action)lambdaExpression.Compile(); + Action compiled = (Action)lambdaExpression.Compile(); return compiled; } diff --git a/Libs/Newtonsoft.Json/Utilities/FSharpUtils.cs b/Libs/Newtonsoft.Json/Utilities/FSharpUtils.cs index ad66c34..0a6e1a5 100644 --- a/Libs/Newtonsoft.Json/Utilities/FSharpUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/FSharpUtils.cs @@ -31,16 +31,15 @@ using System.Linq; using System.Reflection; using System.Text; using LC.Newtonsoft.Json.Serialization; -using System.Diagnostics; namespace LC.Newtonsoft.Json.Utilities { internal class FSharpFunction { - private readonly object? _instance; - private readonly MethodCall _invoker; + private readonly object _instance; + private readonly MethodCall _invoker; - public FSharpFunction(object? instance, MethodCall invoker) + public FSharpFunction(object instance, MethodCall invoker) { _instance = instance; _invoker = invoker; @@ -54,64 +53,24 @@ namespace LC.Newtonsoft.Json.Utilities } } - internal class FSharpUtils + internal static class FSharpUtils { - private FSharpUtils(Assembly fsharpCoreAssembly) - { - FSharpCoreAssembly = fsharpCoreAssembly; - - Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); - - MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); - IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo)!; - - MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); - GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo)!; - - Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); - - PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); - PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); - PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); - - Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); - - GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")!)!; - GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")!)!; - GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")!)!; - GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); - - Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); - _ofSeq = listModule.GetMethod("OfSeq"); - - _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); - } - private static readonly object Lock = new object(); - private static FSharpUtils? _instance; - public static FSharpUtils Instance - { - get - { - MiscellaneousUtils.Assert(_instance != null); - return _instance; - } - } + private static bool _initialized; + private static MethodInfo _ofSeq; + private static Type _mapType; - private MethodInfo _ofSeq; - private Type _mapType; - - public Assembly FSharpCoreAssembly { get; private set; } - public MethodCall IsUnion { get; private set; } - public MethodCall GetUnionCases { get; private set; } - public MethodCall PreComputeUnionTagReader { get; private set; } - public MethodCall PreComputeUnionReader { get; private set; } - public MethodCall PreComputeUnionConstructor { get; private set; } - public Func GetUnionCaseInfoDeclaringType { get; private set; } - public Func GetUnionCaseInfoName { get; private set; } - public Func GetUnionCaseInfoTag { get; private set; } - public MethodCall GetUnionCaseInfoFields { get; private set; } + public static Assembly FSharpCoreAssembly { get; private set; } + public static MethodCall IsUnion { get; private set; } + public static MethodCall GetUnionCases { get; private set; } + public static MethodCall PreComputeUnionTagReader { get; private set; } + public static MethodCall PreComputeUnionReader { get; private set; } + public static MethodCall PreComputeUnionConstructor { get; private set; } + public static Func GetUnionCaseInfoDeclaringType { get; private set; } + public static Func GetUnionCaseInfoName { get; private set; } + public static Func GetUnionCaseInfoTag { get; private set; } + public static MethodCall GetUnionCaseInfoFields { get; private set; } public const string FSharpSetTypeName = "FSharpSet`1"; public const string FSharpListTypeName = "FSharpList`1"; @@ -119,13 +78,44 @@ namespace LC.Newtonsoft.Json.Utilities public static void EnsureInitialized(Assembly fsharpCoreAssembly) { - if (_instance == null) + if (!_initialized) { lock (Lock) { - if (_instance == null) + if (!_initialized) { - _instance = new FSharpUtils(fsharpCoreAssembly); + FSharpCoreAssembly = fsharpCoreAssembly; + + Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); + + MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); + IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo); + + MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); + GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo); + + Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); + + PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); + PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); + PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); + + Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); + + GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")); + GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")); + GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")); + GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); + + Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); + _ofSeq = listModule.GetMethod("OfSeq"); + + _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + +#if HAVE_MEMORY_BARRIER + Thread.MemoryBarrier(); +#endif + _initialized = true; } } } @@ -144,20 +134,20 @@ namespace LC.Newtonsoft.Json.Utilities methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic); } - return methodInfo!; + return methodInfo; } - private static MethodCall CreateFSharpFuncCall(Type type, string methodName) + private static MethodCall CreateFSharpFuncCall(Type type, string methodName) { MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance); - MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); - MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc)!; + MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); + MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc); - MethodCall createFunction = (target, args) => + MethodCall createFunction = (target, args) => { - object? result = call(target, args); + object result = call(target, args); FSharpFunction f = new FSharpFunction(result, invoke); return f; @@ -166,23 +156,23 @@ namespace LC.Newtonsoft.Json.Utilities return createFunction; } - public ObjectConstructor CreateSeq(Type t) + public static ObjectConstructor CreateSeq(Type t) { MethodInfo seqType = _ofSeq.MakeGenericMethod(t); return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType); } - public ObjectConstructor CreateMap(Type keyType, Type valueType) + public static ObjectConstructor CreateMap(Type keyType, Type valueType) { MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator"); MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType); - return (ObjectConstructor)creatorGeneric.Invoke(this, null); + return (ObjectConstructor)creatorGeneric.Invoke(null, null); } - public ObjectConstructor BuildMapCreator() + public static ObjectConstructor BuildMapCreator() { Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) }); @@ -191,7 +181,7 @@ namespace LC.Newtonsoft.Json.Utilities ObjectConstructor creator = args => { // convert dictionary KeyValuePairs to Tuples - IEnumerable> values = (IEnumerable>)args[0]!; + IEnumerable> values = (IEnumerable>)args[0]; IEnumerable> tupleValues = values.Select(kv => new Tuple(kv.Key, kv.Value)); return ctorDelegate(tupleValues); diff --git a/Libs/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs b/Libs/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs index ecbab85..02e4467 100644 --- a/Libs/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs @@ -25,14 +25,12 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Reflection; -using System.Runtime.CompilerServices; using System.Text; using LC.Newtonsoft.Json.Serialization; @@ -90,7 +88,7 @@ namespace LC.Newtonsoft.Json.Utilities new ImmutableCollectionTypeInfo(ImmutableQueueGenericTypeName, ImmutableQueueGenericTypeName, ImmutableQueueTypeName), new ImmutableCollectionTypeInfo(ImmutableStackGenericInterfaceTypeName, ImmutableStackGenericTypeName, ImmutableStackTypeName), new ImmutableCollectionTypeInfo(ImmutableStackGenericTypeName, ImmutableStackGenericTypeName, ImmutableStackTypeName), - new ImmutableCollectionTypeInfo(ImmutableSetGenericInterfaceTypeName, ImmutableHashSetGenericTypeName, ImmutableHashSetTypeName), + new ImmutableCollectionTypeInfo(ImmutableSetGenericInterfaceTypeName, ImmutableSortedSetGenericTypeName, ImmutableSortedSetTypeName), new ImmutableCollectionTypeInfo(ImmutableSortedSetGenericTypeName, ImmutableSortedSetGenericTypeName, ImmutableSortedSetTypeName), new ImmutableCollectionTypeInfo(ImmutableHashSetGenericTypeName, ImmutableHashSetGenericTypeName, ImmutableHashSetTypeName), new ImmutableCollectionTypeInfo(ImmutableArrayGenericTypeName, ImmutableArrayGenericTypeName, ImmutableArrayTypeName) @@ -106,12 +104,12 @@ namespace LC.Newtonsoft.Json.Utilities private static readonly IList DictionaryContractImmutableCollectionDefinitions = new List { - new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericInterfaceTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName), + new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericInterfaceTypeName, ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryTypeName), new ImmutableCollectionTypeInfo(ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryTypeName), new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName) }; - internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor? parameterizedCreator) + internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, out Type createdType, out ObjectConstructor parameterizedCreator) { if (underlyingType.IsGenericType()) { @@ -143,7 +141,7 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor? parameterizedCreator) + internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, out Type createdType, out ObjectConstructor parameterizedCreator) { if (underlyingType.IsGenericType()) { diff --git a/Libs/Newtonsoft.Json/Utilities/JavaScriptUtils.cs b/Libs/Newtonsoft.Json/Utilities/JavaScriptUtils.cs index 0efa3aa..00c1950 100644 --- a/Libs/Newtonsoft.Json/Utilities/JavaScriptUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/JavaScriptUtils.cs @@ -31,8 +31,6 @@ using System.Threading.Tasks; #endif using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -43,7 +41,7 @@ namespace LC.Newtonsoft.Json.Utilities { internal static class BufferUtils { - public static char[] RentBuffer(IArrayPool? bufferPool, int minSize) + public static char[] RentBuffer(IArrayPool bufferPool, int minSize) { if (bufferPool == null) { @@ -54,12 +52,12 @@ namespace LC.Newtonsoft.Json.Utilities return buffer; } - public static void ReturnBuffer(IArrayPool? bufferPool, char[]? buffer) + public static void ReturnBuffer(IArrayPool bufferPool, char[] buffer) { bufferPool?.Return(buffer); } - public static char[] EnsureBufferSize(IArrayPool? bufferPool, int size, char[]? buffer) + public static char[] EnsureBufferSize(IArrayPool bufferPool, int size, char[] buffer) { if (bufferPool == null) { @@ -125,16 +123,15 @@ namespace LC.Newtonsoft.Json.Utilities return SingleQuoteCharEscapeFlags; } - public static bool ShouldEscapeJavaScriptString(string? s, bool[] charEscapeFlags) + public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) { return false; } - for (int i = 0; i < s.Length; i++) + foreach (char c in s) { - char c = s[i]; if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; @@ -144,8 +141,8 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - public static void WriteEscapedJavaScriptString(TextWriter writer, string? s, char delimiter, bool appendDelimiters, - bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool? bufferPool, ref char[]? writeBuffer) + public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, + bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool bufferPool, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) @@ -153,7 +150,7 @@ namespace LC.Newtonsoft.Json.Utilities writer.Write(delimiter); } - if (!StringUtils.IsNullOrEmpty(s)) + if (!string.IsNullOrEmpty(s)) { int lastWritePosition = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); if (lastWritePosition == -1) @@ -184,7 +181,7 @@ namespace LC.Newtonsoft.Json.Utilities continue; } - string? escapedValue; + string escapedValue; switch (c) { @@ -233,7 +230,7 @@ namespace LC.Newtonsoft.Json.Utilities writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } - StringUtils.ToCharAsUnicode(c, writeBuffer!); + StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; @@ -266,7 +263,7 @@ namespace LC.Newtonsoft.Json.Utilities // copy it over when creating new buffer if (isEscapedUnicodeText) { - MiscellaneousUtils.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); + Debug.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } @@ -293,7 +290,7 @@ namespace LC.Newtonsoft.Json.Utilities } } - MiscellaneousUtils.Assert(lastWritePosition != 0); + Debug.Assert(lastWritePosition != 0); length = s.Length - lastWritePosition; if (length > 0) { @@ -317,13 +314,13 @@ namespace LC.Newtonsoft.Json.Utilities } } - public static string ToEscapedJavaScriptString(string? value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) + public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { - char[]? buffer = null; + char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } @@ -374,7 +371,7 @@ namespace LC.Newtonsoft.Json.Utilities return WriteEscapedJavaScriptStringWithDelimitersAsync(writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { return cancellationToken.CancelIfRequestedAsync() ?? AsyncUtils.CompletedTask; } @@ -391,7 +388,7 @@ namespace LC.Newtonsoft.Json.Utilities return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } - if (!StringUtils.IsNullOrEmpty(s)) + if (!string.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); if (task.IsCompletedSucessfully()) @@ -409,7 +406,7 @@ namespace LC.Newtonsoft.Json.Utilities { await task.ConfigureAwait(false); - if (!StringUtils.IsNullOrEmpty(s)) + if (!string.IsNullOrEmpty(s)) { await WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken).ConfigureAwait(false); } @@ -453,7 +450,7 @@ namespace LC.Newtonsoft.Json.Utilities int length; bool isEscapedUnicodeText = false; - string? escapedValue = null; + string escapedValue = null; for (int i = lastWritePosition; i < s.Length; i++) { @@ -542,7 +539,7 @@ namespace LC.Newtonsoft.Json.Utilities lastWritePosition = i + 1; if (!isEscapedUnicodeText) { - await writer.WriteAsync(escapedValue!, cancellationToken).ConfigureAwait(false); + await writer.WriteAsync(escapedValue, cancellationToken).ConfigureAwait(false); } else { @@ -568,7 +565,7 @@ namespace LC.Newtonsoft.Json.Utilities } #endif - public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, [NotNullWhen(false)]out string? errorMessage) + public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, out string errorMessage) { dateTime = default; errorMessage = null; @@ -629,7 +626,7 @@ namespace LC.Newtonsoft.Json.Utilities return true; } - private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, [NotNullWhen(false)] out string? errorMessage) + private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, out string errorMessage) { integer = null; errorMessage = null; @@ -649,7 +646,7 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - integer = (long)reader.Value!; + integer = (long)reader.Value; return true; } } diff --git a/Libs/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/Libs/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index 533cbd6..0e753f4 100644 --- a/Libs/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/Libs/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -53,7 +53,7 @@ namespace LC.Newtonsoft.Json.Utilities return a => method.Invoke(null, a); } - public override MethodCall CreateMethodCall(MethodBase method) + public override MethodCall CreateMethodCall(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -79,28 +79,28 @@ namespace LC.Newtonsoft.Json.Utilities return () => (T)constructorInfo.Invoke(null); } - public override Func CreateGet(PropertyInfo propertyInfo) + public override Func CreateGet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); return o => propertyInfo.GetValue(o, null); } - public override Func CreateGet(FieldInfo fieldInfo) + public override Func CreateGet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); return o => fieldInfo.GetValue(o); } - public override Action CreateSet(FieldInfo fieldInfo) + public override Action CreateSet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); return (o, v) => fieldInfo.SetValue(o, v); } - public override Action CreateSet(PropertyInfo propertyInfo) + public override Action CreateSet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); diff --git a/Libs/Newtonsoft.Json/Utilities/LinqBridge.cs b/Libs/Newtonsoft.Json/Utilities/LinqBridge.cs index ff0749a..e3c30e5 100644 --- a/Libs/Newtonsoft.Json/Utilities/LinqBridge.cs +++ b/Libs/Newtonsoft.Json/Utilities/LinqBridge.cs @@ -35,8 +35,6 @@ using System.Diagnostics; using System.Globalization; using LC.Newtonsoft.Json.Serialization; -#nullable disable - namespace LC.Newtonsoft.Json.Utilities.LinqBridge { /// @@ -377,7 +375,7 @@ namespace LC.Newtonsoft.Json.Utilities.LinqBridge Func empty) { CheckNotNull(source, "source"); - MiscellaneousUtils.Assert(empty != null); + Debug.Assert(empty != null); var list = source as IList; // optimized case for lists if (list != null) @@ -1364,7 +1362,7 @@ namespace LC.Newtonsoft.Json.Utilities.LinqBridge Func lesser) { CheckNotNull(source, "source"); - MiscellaneousUtils.Assert(lesser != null); + Debug.Assert(lesser != null); return source.Aggregate((a, item) => lesser(a, item) ? a : item); } @@ -1378,7 +1376,7 @@ namespace LC.Newtonsoft.Json.Utilities.LinqBridge TSource? seed, Func lesser) where TSource : struct { CheckNotNull(source, "source"); - MiscellaneousUtils.Assert(lesser != null); + Debug.Assert(lesser != null); return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item); // == MinMaxImpl(Repeat(null, 1).Concat(source), lesser); @@ -1442,7 +1440,7 @@ namespace LC.Newtonsoft.Json.Utilities.LinqBridge private static IEnumerable Renumerable(this IEnumerator e) { - MiscellaneousUtils.Assert(e != null); + Debug.Assert(e != null); do { diff --git a/Libs/Newtonsoft.Json/Utilities/MethodBinder.cs b/Libs/Newtonsoft.Json/Utilities/MethodBinder.cs index a92244b..a453ce1 100644 --- a/Libs/Newtonsoft.Json/Utilities/MethodBinder.cs +++ b/Libs/Newtonsoft.Json/Utilities/MethodBinder.cs @@ -126,7 +126,7 @@ namespace LC.Newtonsoft.Json.Utilities } // check if the last parameter is ParamArray - Type? paramArrayType = null; + Type paramArrayType = null; if (enableParamArray) { @@ -211,7 +211,7 @@ namespace LC.Newtonsoft.Json.Utilities return 1; } - Type? paramArrayType1 = null, paramArrayType2 = null; + Type paramArrayType1 = null, paramArrayType2 = null; if (_enableParamArray) { diff --git a/Libs/Newtonsoft.Json/Utilities/MethodCall.cs b/Libs/Newtonsoft.Json/Utilities/MethodCall.cs index 69714d5..c8bf761 100644 --- a/Libs/Newtonsoft.Json/Utilities/MethodCall.cs +++ b/Libs/Newtonsoft.Json/Utilities/MethodCall.cs @@ -25,5 +25,5 @@ namespace LC.Newtonsoft.Json.Utilities { - internal delegate TResult MethodCall(T target, params object?[] args); + internal delegate TResult MethodCall(T target, params object[] args); } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/Libs/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index ce2b8e0..adfc8a6 100644 --- a/Libs/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -31,8 +31,6 @@ using System.Reflection; using System.Text; using System.Globalization; using System.Text.RegularExpressions; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; namespace LC.Newtonsoft.Json.Utilities { @@ -40,13 +38,7 @@ namespace LC.Newtonsoft.Json.Utilities internal static class MiscellaneousUtils { - [Conditional("DEBUG")] - public static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null) - { - Debug.Assert(condition, message); - } - - public static bool ValueEquals(object? objA, object? objB) + public static bool ValueEquals(object objA, object objB) { if (objA == objB) { @@ -85,14 +77,14 @@ namespace LC.Newtonsoft.Json.Utilities return new ArgumentOutOfRangeException(paramName, newMessage); } - public static string ToString(object? value) + public static string ToString(object value) { if (value == null) { return "{null}"; } - return (value is string s) ? @"""" + s + @"""" : value!.ToString(); + return (value is string s) ? @"""" + s + @"""" : value.ToString(); } public static int ByteArrayCompare(byte[] a1, byte[] a2) @@ -115,9 +107,9 @@ namespace LC.Newtonsoft.Json.Utilities return 0; } - public static string? GetPrefix(string qualifiedName) + public static string GetPrefix(string qualifiedName) { - GetQualifiedNameParts(qualifiedName, out string? prefix, out _); + GetQualifiedNameParts(qualifiedName, out string prefix, out _); return prefix; } @@ -129,7 +121,7 @@ namespace LC.Newtonsoft.Json.Utilities return localName; } - public static void GetQualifiedNameParts(string qualifiedName, out string? prefix, out string localName) + public static void GetQualifiedNameParts(string qualifiedName, out string prefix, out string localName) { int colonPosition = qualifiedName.IndexOf(':'); @@ -148,10 +140,9 @@ namespace LC.Newtonsoft.Json.Utilities internal static RegexOptions GetRegexOptions(string optionsText) { RegexOptions options = RegexOptions.None; - - for (int i = 0; i < optionsText.Length; i++) + foreach (char c in optionsText) { - switch (optionsText[i]) + switch (c) { case 'i': options |= RegexOptions.IgnoreCase; diff --git a/Libs/Newtonsoft.Json/Utilities/NullableAttributes.cs b/Libs/Newtonsoft.Json/Utilities/NullableAttributes.cs deleted file mode 100644 index fa1f55e..0000000 --- a/Libs/Newtonsoft.Json/Utilities/NullableAttributes.cs +++ /dev/null @@ -1,74 +0,0 @@ -#region License -// Copyright (c) 2007 James Newton-King -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -#endregion - -namespace System.Diagnostics.CodeAnalysis -{ - /// Specifies that an output will not be null even if the corresponding type allows it. - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true)] - internal sealed class NotNullAttribute : Attribute { } - - /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. - [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] - internal sealed class NotNullWhenAttribute : Attribute - { - /// Initializes the attribute with the specified return value condition. - /// - /// The return value condition. If the method returns this value, the associated parameter will not be null. - /// - public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; - - /// Gets the return value condition. - public bool ReturnValue { get; } - } - - /// Specifies that an output may be null even if the corresponding type disallows it. - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] - internal sealed class MaybeNullAttribute : Attribute - { } - - /// Specifies that null is allowed as an input even if the corresponding type disallows it. - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] - internal sealed class AllowNullAttribute : Attribute - { } - - /// - /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value. - /// - [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] - internal class DoesNotReturnIfAttribute : Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to - /// the associated parameter matches this value. - /// - public DoesNotReturnIfAttribute(bool parameterValue) => this.ParameterValue = parameterValue; - - /// Gets the condition parameter value. - public bool ParameterValue { get; } - } -} \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs b/Libs/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs index 25ee493..480af5f 100644 --- a/Libs/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs +++ b/Libs/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs @@ -36,7 +36,7 @@ namespace LC.Newtonsoft.Json.Utilities { internal abstract class ReflectionDelegateFactory { - public Func CreateGet(MemberInfo memberInfo) + public Func CreateGet(MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -57,7 +57,7 @@ namespace LC.Newtonsoft.Json.Utilities throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } - public Action CreateSet(MemberInfo memberInfo) + public Action CreateSet(MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -72,12 +72,12 @@ namespace LC.Newtonsoft.Json.Utilities throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } - public abstract MethodCall CreateMethodCall(MethodBase method); + public abstract MethodCall CreateMethodCall(MethodBase method); public abstract ObjectConstructor CreateParameterizedConstructor(MethodBase method); public abstract Func CreateDefaultConstructor(Type type); - public abstract Func CreateGet(PropertyInfo propertyInfo); - public abstract Func CreateGet(FieldInfo fieldInfo); - public abstract Action CreateSet(FieldInfo fieldInfo); - public abstract Action CreateSet(PropertyInfo propertyInfo); + public abstract Func CreateGet(PropertyInfo propertyInfo); + public abstract Func CreateGet(FieldInfo fieldInfo); + public abstract Action CreateSet(FieldInfo fieldInfo); + public abstract Action CreateSet(PropertyInfo propertyInfo); } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Utilities/ReflectionObject.cs b/Libs/Newtonsoft.Json/Utilities/ReflectionObject.cs index 79ad388..0215e00 100644 --- a/Libs/Newtonsoft.Json/Utilities/ReflectionObject.cs +++ b/Libs/Newtonsoft.Json/Utilities/ReflectionObject.cs @@ -39,37 +39,37 @@ namespace LC.Newtonsoft.Json.Utilities { internal class ReflectionMember { - public Type? MemberType { get; set; } - public Func? Getter { get; set; } - public Action? Setter { get; set; } + public Type MemberType { get; set; } + public Func Getter { get; set; } + public Action Setter { get; set; } } internal class ReflectionObject { - public ObjectConstructor? Creator { get; } + public ObjectConstructor Creator { get; } public IDictionary Members { get; } - private ReflectionObject(ObjectConstructor? creator) + private ReflectionObject(ObjectConstructor creator) { Members = new Dictionary(); Creator = creator; } - public object? GetValue(object target, string member) + public object GetValue(object target, string member) { - Func getter = Members[member].Getter!; + Func getter = Members[member].Getter; return getter(target); } - public void SetValue(object target, string member, object? value) + public void SetValue(object target, string member, object value) { - Action setter = Members[member].Setter!; + Action setter = Members[member].Setter; setter(target, value); } public Type GetType(string member) { - return Members[member].MemberType!; + return Members[member].MemberType; } public static ReflectionObject Create(Type t, params string[] memberNames) @@ -77,11 +77,11 @@ namespace LC.Newtonsoft.Json.Utilities return Create(t, null, memberNames); } - public static ReflectionObject Create(Type t, MethodBase? creator, params string[] memberNames) + public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames) { ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; - ObjectConstructor? creatorConstructor = null; + ObjectConstructor creatorConstructor = null; if (creator != null) { creatorConstructor = delegateFactory.CreateParameterizedConstructor(creator); @@ -131,12 +131,12 @@ namespace LC.Newtonsoft.Json.Utilities ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 0 && method.ReturnType != typeof(void)) { - MethodCall call = delegateFactory.CreateMethodCall(method); + MethodCall call = delegateFactory.CreateMethodCall(method); reflectionMember.Getter = target => call(target); } else if (parameters.Length == 1 && method.ReturnType == typeof(void)) { - MethodCall call = delegateFactory.CreateMethodCall(method); + MethodCall call = delegateFactory.CreateMethodCall(method); reflectionMember.Setter = (target, arg) => call(target, arg); } } diff --git a/Libs/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Libs/Newtonsoft.Json/Utilities/ReflectionUtils.cs index c4e4ced..bdfc742 100644 --- a/Libs/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -32,8 +32,6 @@ using System.Reflection; using System.Collections; using System.Globalization; using System.Text; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -98,7 +96,7 @@ namespace LC.Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); - MethodInfo? m = propertyInfo.GetGetMethod(true); + MethodInfo m = propertyInfo.GetGetMethod(true); if (m != null && m.IsVirtual) { return true; @@ -113,11 +111,11 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - public static MethodInfo? GetBaseDefinition(this PropertyInfo propertyInfo) + public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); - MethodInfo? m = propertyInfo.GetGetMethod(true); + MethodInfo m = propertyInfo.GetGetMethod(true); if (m != null) { return m.GetBaseDefinition(); @@ -128,13 +126,11 @@ namespace LC.Newtonsoft.Json.Utilities public static bool IsPublic(PropertyInfo property) { - var getMethod = property.GetGetMethod(); - if (getMethod != null && getMethod.IsPublic) + if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) { return true; } - var setMethod = property.GetSetMethod(); - if (setMethod != null && setMethod.IsPublic) + if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) { return true; } @@ -142,12 +138,12 @@ namespace LC.Newtonsoft.Json.Utilities return false; } - public static Type? GetObjectType(object? v) + public static Type GetObjectType(object v) { return v?.GetType(); } - public static string GetTypeName(Type t, TypeNameAssemblyFormatHandling assemblyFormat, ISerializationBinder? binder) + public static string GetTypeName(Type t, TypeNameAssemblyFormatHandling assemblyFormat, ISerializationBinder binder) { string fullyQualifiedTypeName = GetFullyQualifiedTypeName(t, binder); @@ -162,11 +158,11 @@ namespace LC.Newtonsoft.Json.Utilities } } - private static string GetFullyQualifiedTypeName(Type t, ISerializationBinder? binder) + private static string GetFullyQualifiedTypeName(Type t, ISerializationBinder binder) { if (binder != null) { - binder.BindToName(t, out string? assemblyName, out string? typeName); + binder.BindToName(t, out string assemblyName, out string typeName); #if (NET20 || NET35) // for older SerializationBinder implementations that didn't have BindToName if (assemblyName == null & typeName == null) @@ -298,7 +294,7 @@ namespace LC.Newtonsoft.Json.Utilities return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _); } - public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, [NotNullWhen(true)]out Type? implementingType) + public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition)); @@ -345,7 +341,7 @@ namespace LC.Newtonsoft.Json.Utilities return InheritsGenericDefinition(type, genericClassDefinition, out _); } - public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type? implementingType) + public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(genericClassDefinition, nameof(genericClassDefinition)); @@ -358,7 +354,7 @@ namespace LC.Newtonsoft.Json.Utilities return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } - private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type? implementingType) + private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { do { @@ -381,7 +377,7 @@ namespace LC.Newtonsoft.Json.Utilities /// /// The type. /// The type of the typed collection's items. - public static Type? GetCollectionItemType(Type type) + public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -389,14 +385,14 @@ namespace LC.Newtonsoft.Json.Utilities { return type.GetElementType(); } - if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type? genericListType)) + if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type genericListType)) { - if (genericListType!.IsGenericTypeDefinition()) + if (genericListType.IsGenericTypeDefinition()) { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } - return genericListType!.GetGenericArguments()[0]; + return genericListType.GetGenericArguments()[0]; } if (typeof(IEnumerable).IsAssignableFrom(type)) { @@ -406,18 +402,18 @@ namespace LC.Newtonsoft.Json.Utilities throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } - public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type? keyType, out Type? valueType) + public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); - if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type? genericDictionaryType)) + if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type genericDictionaryType)) { - if (genericDictionaryType!.IsGenericTypeDefinition()) + if (genericDictionaryType.IsGenericTypeDefinition()) { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } - Type[] dictionaryGenericArguments = genericDictionaryType!.GetGenericArguments(); + Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; @@ -526,7 +522,7 @@ namespace LC.Newtonsoft.Json.Utilities /// The member. /// The target. /// The value. - public static void SetMemberValue(MemberInfo member, object target, object? value) + public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, nameof(member)); ValidationUtils.ArgumentNotNull(target, nameof(target)); @@ -725,12 +721,12 @@ namespace LC.Newtonsoft.Json.Utilities return true; } - public static T? GetAttribute(object attributeProvider) where T : Attribute + public static T GetAttribute(object attributeProvider) where T : Attribute { return GetAttribute(attributeProvider, true); } - public static T? GetAttribute(object attributeProvider, bool inherit) where T : Attribute + public static T GetAttribute(object attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes(attributeProvider, inherit); @@ -750,7 +746,7 @@ namespace LC.Newtonsoft.Json.Utilities return a.Cast().ToArray(); } - public static Attribute[] GetAttributes(object attributeProvider, Type? attributeType, bool inherit) + public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit) { ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider)); @@ -801,7 +797,7 @@ namespace LC.Newtonsoft.Json.Utilities return GetAttributes(attributeProvider, typeof(T), inherit).Cast().ToArray(); } - public static Attribute[] GetAttributes(object provider, Type? attributeType, bool inherit) + public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit) { switch (provider) { @@ -823,12 +819,12 @@ namespace LC.Newtonsoft.Json.Utilities } #endif - public static StructMultiKey SplitFullyQualifiedTypeName(string fullyQualifiedTypeName) + public static StructMultiKey SplitFullyQualifiedTypeName(string fullyQualifiedTypeName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); string typeName; - string? assemblyName; + string assemblyName; if (assemblyDelimiterIndex != null) { @@ -841,7 +837,7 @@ namespace LC.Newtonsoft.Json.Utilities assemblyName = null; } - return new StructMultiKey(assemblyName, typeName); + return new StructMultiKey(assemblyName, typeName); } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) @@ -1042,7 +1038,7 @@ namespace LC.Newtonsoft.Json.Utilities return isMethodOverriden; } - public static object? GetDefaultValue(Type type) + public static object GetDefaultValue(Type type) { if (!type.IsValueType()) { @@ -1093,4 +1089,4 @@ namespace LC.Newtonsoft.Json.Utilities return Activator.CreateInstance(type); } } -} \ No newline at end of file +} diff --git a/Libs/Newtonsoft.Json/Utilities/StringBuffer.cs b/Libs/Newtonsoft.Json/Utilities/StringBuffer.cs index 129ba03..225fd1e 100644 --- a/Libs/Newtonsoft.Json/Utilities/StringBuffer.cs +++ b/Libs/Newtonsoft.Json/Utilities/StringBuffer.cs @@ -32,7 +32,7 @@ namespace LC.Newtonsoft.Json.Utilities /// internal struct StringBuffer { - private char[]? _buffer; + private char[] _buffer; private int _position; public int Position @@ -43,7 +43,7 @@ namespace LC.Newtonsoft.Json.Utilities public bool IsEmpty => _buffer == null; - public StringBuffer(IArrayPool? bufferPool, int initalSize) : this(BufferUtils.RentBuffer(bufferPool, initalSize)) + public StringBuffer(IArrayPool bufferPool, int initalSize) : this(BufferUtils.RentBuffer(bufferPool, initalSize)) { } @@ -53,21 +53,21 @@ namespace LC.Newtonsoft.Json.Utilities _position = 0; } - public void Append(IArrayPool? bufferPool, char value) + public void Append(IArrayPool bufferPool, char value) { // test if the buffer array is large enough to take the value - if (_position == _buffer!.Length) + if (_position == _buffer.Length) { EnsureSize(bufferPool, 1); } // set value and increment poisition - _buffer![_position++] = value; + _buffer[_position++] = value; } - public void Append(IArrayPool? bufferPool, char[] buffer, int startIndex, int count) + public void Append(IArrayPool bufferPool, char[] buffer, int startIndex, int count) { - if (_position + count >= _buffer!.Length) + if (_position + count >= _buffer.Length) { EnsureSize(bufferPool, count); } @@ -77,7 +77,7 @@ namespace LC.Newtonsoft.Json.Utilities _position += count; } - public void Clear(IArrayPool? bufferPool) + public void Clear(IArrayPool bufferPool) { if (_buffer != null) { @@ -87,7 +87,7 @@ namespace LC.Newtonsoft.Json.Utilities _position = 0; } - private void EnsureSize(IArrayPool? bufferPool, int appendLength) + private void EnsureSize(IArrayPool bufferPool, int appendLength) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, (_position + appendLength) * 2); @@ -111,6 +111,6 @@ namespace LC.Newtonsoft.Json.Utilities return new string(_buffer, start, length); } - public char[]? InternalBuffer => _buffer; + public char[] InternalBuffer => _buffer; } } \ No newline at end of file diff --git a/Libs/Newtonsoft.Json/Utilities/StringUtils.cs b/Libs/Newtonsoft.Json/Utilities/StringUtils.cs index 38f6fb4..3c87f2c 100644 --- a/Libs/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/StringUtils.cs @@ -28,7 +28,6 @@ using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -46,32 +45,27 @@ namespace LC.Newtonsoft.Json.Utilities public const char LineFeed = '\n'; public const char Tab = '\t'; - public static bool IsNullOrEmpty([NotNullWhen(false)] string? value) + public static string FormatWith(this string format, IFormatProvider provider, object arg0) { - return string.IsNullOrEmpty(value); + return format.FormatWith(provider, new[] { arg0 }); } - public static string FormatWith(this string format, IFormatProvider provider, object? arg0) + public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1) { - return format.FormatWith(provider, new object?[] { arg0 }); + return format.FormatWith(provider, new[] { arg0, arg1 }); } - public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1) + public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2) { - return format.FormatWith(provider, new object?[] { arg0, arg1 }); + return format.FormatWith(provider, new[] { arg0, arg1, arg2 }); } - public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2) + public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) { - return format.FormatWith(provider, new object?[] { arg0, arg1, arg2 }); + return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 }); } - public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2, object? arg3) - { - return format.FormatWith(provider, new object?[] { arg0, arg1, arg2, arg3 }); - } - - private static string FormatWith(this string format, IFormatProvider provider, params object?[] args) + private static string FormatWith(this string format, IFormatProvider provider, params object[] args) { // leave this a private to force code to use an explicit overload // avoids stack memory being reserved for the object array @@ -154,7 +148,7 @@ namespace LC.Newtonsoft.Json.Utilities public static string ToCamelCase(string s) { - if (StringUtils.IsNullOrEmpty(s) || !char.IsUpper(s[0])) + if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0])) { return s; } @@ -195,7 +189,7 @@ namespace LC.Newtonsoft.Json.Utilities private static char ToLower(char c) { -#if HAVE_CHAR_TO_LOWER_WITH_CULTURE +#if HAVE_CHAR_TO_STRING_WITH_CULTURE c = char.ToLower(c, CultureInfo.InvariantCulture); #else c = char.ToLowerInvariant(c); @@ -203,11 +197,7 @@ namespace LC.Newtonsoft.Json.Utilities return c; } - public static string ToSnakeCase(string s) => ToSeparatedCase(s, '_'); - - public static string ToKebabCase(string s) => ToSeparatedCase(s, '-'); - - private enum SeparatedCaseState + internal enum SnakeCaseState { Start, Lower, @@ -215,43 +205,43 @@ namespace LC.Newtonsoft.Json.Utilities NewWord } - private static string ToSeparatedCase(string s, char separator) + public static string ToSnakeCase(string s) { - if (StringUtils.IsNullOrEmpty(s)) + if (string.IsNullOrEmpty(s)) { return s; } StringBuilder sb = new StringBuilder(); - SeparatedCaseState state = SeparatedCaseState.Start; + SnakeCaseState state = SnakeCaseState.Start; for (int i = 0; i < s.Length; i++) { if (s[i] == ' ') { - if (state != SeparatedCaseState.Start) + if (state != SnakeCaseState.Start) { - state = SeparatedCaseState.NewWord; + state = SnakeCaseState.NewWord; } } else if (char.IsUpper(s[i])) { switch (state) { - case SeparatedCaseState.Upper: + case SnakeCaseState.Upper: bool hasNext = (i + 1 < s.Length); if (i > 0 && hasNext) { char nextChar = s[i + 1]; - if (!char.IsUpper(nextChar) && nextChar != separator) + if (!char.IsUpper(nextChar) && nextChar != '_') { - sb.Append(separator); + sb.Append('_'); } } break; - case SeparatedCaseState.Lower: - case SeparatedCaseState.NewWord: - sb.Append(separator); + case SnakeCaseState.Lower: + case SnakeCaseState.NewWord: + sb.Append('_'); break; } @@ -263,22 +253,22 @@ namespace LC.Newtonsoft.Json.Utilities #endif sb.Append(c); - state = SeparatedCaseState.Upper; + state = SnakeCaseState.Upper; } - else if (s[i] == separator) + else if (s[i] == '_') { - sb.Append(separator); - state = SeparatedCaseState.Start; + sb.Append('_'); + state = SnakeCaseState.Start; } else { - if (state == SeparatedCaseState.NewWord) + if (state == SnakeCaseState.NewWord) { - sb.Append(separator); + sb.Append('_'); } sb.Append(s[i]); - state = SeparatedCaseState.Lower; + state = SnakeCaseState.Lower; } } diff --git a/Libs/Newtonsoft.Json/Utilities/TypeExtensions.cs b/Libs/Newtonsoft.Json/Utilities/TypeExtensions.cs index a3c5dc9..a56be14 100644 --- a/Libs/Newtonsoft.Json/Utilities/TypeExtensions.cs +++ b/Libs/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -26,8 +26,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using LC.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -42,12 +40,12 @@ namespace LC.Newtonsoft.Json.Utilities #if !DOTNET private static readonly BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; - public static MethodInfo? GetGetMethod(this PropertyInfo propertyInfo) + public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetGetMethod(false); } - public static MethodInfo? GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) + public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo getMethod = propertyInfo.GetMethod; if (getMethod != null && (getMethod.IsPublic || nonPublic)) @@ -58,12 +56,12 @@ namespace LC.Newtonsoft.Json.Utilities return null; } - public static MethodInfo? GetSetMethod(this PropertyInfo propertyInfo) + public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetSetMethod(false); } - public static MethodInfo? GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) + public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo setMethod = propertyInfo.SetMethod; if (setMethod != null && (setMethod.IsPublic || nonPublic)) @@ -87,7 +85,7 @@ namespace LC.Newtonsoft.Json.Utilities } #endif - public static bool IsInstanceOfType(this Type type, object? o) + public static bool IsInstanceOfType(this Type type, object o) { if (o == null) { @@ -217,7 +215,7 @@ namespace LC.Newtonsoft.Json.Utilities } #if (PORTABLE40 || DOTNET || PORTABLE) - public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object? placeholder1, Type propertyType, IList indexParameters, object? placeholder2) + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object placeholder1, Type propertyType, IList indexParameters, object placeholder2) { IEnumerable propertyInfos = type.GetProperties(bindingFlags); @@ -291,12 +289,12 @@ namespace LC.Newtonsoft.Json.Utilities return type.GetMethod(null, parameterTypes); } - public static MethodInfo GetMethod(this Type type, string? name, IList parameterTypes) + public static MethodInfo GetMethod(this Type type, string name, IList parameterTypes) { return type.GetMethod(name, DefaultFlags, null, parameterTypes, null); } - public static MethodInfo GetMethod(this Type type, string? name, BindingFlags bindingFlags, object? placeHolder1, IList parameterTypes, object? placeHolder2) + public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object placeHolder1, IList parameterTypes, object placeHolder2) { return MethodBinder.SelectMethod(type.GetTypeInfo().DeclaredMethods.Where(m => (name == null || m.Name == name) && TestAccessibility(m, bindingFlags)), parameterTypes); } @@ -316,7 +314,7 @@ namespace LC.Newtonsoft.Json.Utilities return type.GetConstructor(DefaultFlags, null, parameterTypes, null); } - public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object? placeholder1, IList parameterTypes, object? placeholder2) + public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList parameterTypes, object placeholder2) { return MethodBinder.SelectMethod(type.GetConstructors(bindingFlags), parameterTypes); } @@ -340,12 +338,12 @@ namespace LC.Newtonsoft.Json.Utilities TestAccessibility(m, bindingFlags)).ToArray(); } - public static FieldInfo? GetField(this Type type, string member) + public static FieldInfo GetField(this Type type, string member) { return type.GetField(member, DefaultFlags); } - public static FieldInfo? GetField(this Type type, string member, BindingFlags bindingFlags) + public static FieldInfo GetField(this Type type, string member, BindingFlags bindingFlags) { FieldInfo field = type.GetTypeInfo().GetDeclaredField(member); if (field == null || !TestAccessibility(field, bindingFlags)) @@ -380,7 +378,7 @@ namespace LC.Newtonsoft.Json.Utilities private static IList GetMembersRecursive(this TypeInfo type) { - TypeInfo? t = type; + TypeInfo t = type; List members = new List(); while (t != null) { @@ -399,7 +397,7 @@ namespace LC.Newtonsoft.Json.Utilities private static IList GetPropertiesRecursive(this TypeInfo type) { - TypeInfo? t = type; + TypeInfo t = type; List properties = new List(); while (t != null) { @@ -418,7 +416,7 @@ namespace LC.Newtonsoft.Json.Utilities private static IList GetFieldsRecursive(this TypeInfo type) { - TypeInfo? t = type; + TypeInfo t = type; List fields = new List(); while (t != null) { @@ -440,12 +438,12 @@ namespace LC.Newtonsoft.Json.Utilities return type.GetTypeInfo().DeclaredMethods; } - public static PropertyInfo? GetProperty(this Type type, string name) + public static PropertyInfo GetProperty(this Type type, string name) { return type.GetProperty(name, DefaultFlags); } - public static PropertyInfo? GetProperty(this Type type, string name, BindingFlags bindingFlags) + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags) { PropertyInfo property = type.GetTypeInfo().GetDeclaredProperty(name); if (property == null || !TestAccessibility(property, bindingFlags)) @@ -578,7 +576,7 @@ namespace LC.Newtonsoft.Json.Utilities #endif } - public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, [NotNullWhen(true)]out Type? match) + public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, out Type match) { Type current = type; diff --git a/Libs/Newtonsoft.Json/Utilities/ValidationUtils.cs b/Libs/Newtonsoft.Json/Utilities/ValidationUtils.cs index a2d1873..6d84f48 100644 --- a/Libs/Newtonsoft.Json/Utilities/ValidationUtils.cs +++ b/Libs/Newtonsoft.Json/Utilities/ValidationUtils.cs @@ -24,14 +24,12 @@ #endregion using System; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; namespace LC.Newtonsoft.Json.Utilities { internal static class ValidationUtils { - public static void ArgumentNotNull([NotNull]object? value, string parameterName) + public static void ArgumentNotNull(object value, string parameterName) { if (value == null) { diff --git a/Libs/Newtonsoft.Json/packageIcon.png b/Libs/Newtonsoft.Json/packageIcon.png deleted file mode 100644 index 10c06a5c4da3336c12fe3b61a37cfef8cd15cceb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8956 zcmbtai$Bxf|9|g-MhHa+(U?nag%G*qHZq!3lAuwQjWsr6mXV+*X4n#irDJ6~sb zr<J{GTMNjvrg2lsG8Hm%>wK5S7+nArS^|4tp?kl1@CLxAkHC zAL%GnJxbL!%11-&U;d=o*f$e~>@Me<$O7 z>yhL5i#OpsMb4u8Ba$QuO+Szef9Sb^mrqvFnf&r_{q*1`!v^3GYxYRA%c)0))nTszlXdsu#y^KQ!RC>b%xql#ravVHvcD9NfN7V{5)k@MH#b{&DSi zqD6cF;A1;ZFmuT^qQ8m~mcN~@E$sA*03LqMficHQOY`sV;7_DwwVHiGCFJKE9|lmvVLJoXyf#~O9}Auh9$ zTfY^A&fge@T=32Hq*mmpbF6nd(x__H%2Q^Dt0H{3$LGE)d0@oRUoie9_Er8f)n7&5 zEr84LRL}g^XW-SRqYSz(0OegnCal9u8|aY8WKpw_leHBN_4frwSsQBT+Frl`oh^Oz znJF7o+(9ryXl@si!021rB^9QWN9p3kteSUeJG@zri>wX|)75?H<<5^*hOkN_EzC*s z^o1Xux0LdsMgf7kw5Y^7#=7jy8_09QKp>|2A4-z9lXJ<4^QZUz_JwEA{Phq-=|p7u z_k9V?C{HR}Wo@2#^EOMF*sDOZc(n+}(O)p-(0_0gEQr33q`63=2&MIy^}A1oXW*N$ zZkxmtQ63yGrKGXdfEZfCJ>b7TMxz(66b=FW{y;BM0C~8YtEVqP#(+Qs3(^#lz_9-F z5IL!y_F0ur{9 zl%cfFzl}q%khXXoGl*{!c1B56$4439 zy;M(5IF5*H)=?OSkBJ^p$xrUDULKB<0scovAqP^D}9Fa?<%mi{n^X! z<793?=#r2CmX-hDlmjgrL{R_1?PNjwcvVD5Alx6ZSx0jVGX><6rpFIl_WIm{;?`x* z2<1|Vl5wHHpF)K)Tw@q-6Eq9U$U1)juQK`29f+$Fg70uIxIxtMN2o?sN-Hwzz#(B4 z(diw-S1eY^t$HSC*R_ojUlF*r}-#E(Z6I6~IEbD&K$-+&L|h0m>|2Mn!lJF-WRrop)fNo<26k zQi@_5atcvB>=5abb{{eb{TSJ0?Q?c*HM;(&Qk3YNTKO~TO^HozFAb{CK#ZyY5+7toDBs*=Ad>9iqhOaaJFsi}*{L%0z zF;S_IW>l}|;Pktt32TTNU#~JCQ<>|GDLQq|%#xgwC!25kBH~KiUXW-W4Ivt-?1QteeZ@?X z9&G<7c~;I8+9xL9Ddj!nlJjy8ON{B$lXB92tkh?xVf%v~RNYkR6cQbL_A>M%*>8)f zR{EokB#GL3^|`^i3h#!}P%UhI+zzALTxsWk`J2x1(#!O=>8F0fr4z5;SMI+J5{XH6 zF}cc1rHAqJu$YxXz5}8u%4(*5uVENsbMV;?L=bCoH!k8Tu28*%f7lHivRVInz;07; z_U9hzS&}bhEuGQVFNZ}nV}kp2n9fC+Z)|5)2Je8nAeMNF7UFgKYvNz#Z%^>{Z9udBZaDNS)SeQa8;n`y%9A(zE z=g1LJ?bsLVxAHZ8Fu;OlZA-G~MYU+KNn<fan5MZC#XT7#8}jP51IDxVj1bn5DP5eI zL8zQ4+jTN^=BXO#x=x4wQ@=i~apJdTmo|__uTMT=(tEIFv7zwUtGFVq1o*H6rY8ga zOhD~AZC*{{Mp`)S8Nn&~eQ)vL)raYh5+-7)Xy^p&M~Z;7{n*5s`TG)cgVppnd2f1) zno2{$Wl$CDt1EUb)D$`xJPHA#?U;edsnb#&iglUH6K7IYr>Py*Jf@ z`J%H;iCLA>dcxgl+pxgt0dn)_uYrW&6tiTUL#K~e|rKYD3#BuU)d>-!Q3D zKs3k*(w;rvQYpHBi@O&oQihoJKAAcjp3#5al=LlGV6=Vy%3W-vY_)8Z>fB&y8du*4 z-yN9Q@2Cf}(crhee7-$mOMU|UZRsI_L3ib629`~uGl?<+yAz*OPLp=Xg$A)A#;Y82 zYdrK1;P99~%5!SRoD^%;aWw{_@wuf40c5qqVaDRw7J_6mdSUwbxXshl`Efhe;ksJo zFs%=dPA$AJ^|isO{InalVW!@j7-S}t3DBK7gzoV!cIksLUoyy^kg`@B}C*WhnmT1S2;Y8M@_EUr7HxX95 zV|{142tg9%lFd{$p=+A-fxPd%$Bu(RaA!x1v8pnpW4#k`0J`gp(FoR#gep^U$E-l~ z`3o7;1pVzrvu{dC(F&_{S+_qjek$mI86T^O${dQd-~XhJ$~gGh2kAVPD0Gu_A? zMRK=NxtE{jG~wDmi77n(%$DQ=G#_*yz;(5d7$=^WN$((+SIcnD+bJ~K^vizM{1kdA5V6_x zTVuOA-S=Aell(U_cbFM z^Pd(1j}|Ntl-B+Y0{3Stb~fcf%{wen*a{0xOY%_=^^&vG%!avE3|+5Me6$ z@w<4U3Yew&j<_slQ%5`6_`!o+;0LQxFYe%9?Ld)CZkm#2kIvm_`m%k!Cl6f6O_J$^ zbiS35r3|*BDW5$oI6vjU26ry@7#*-=u!O$2o(M98oA13dF!QTi5 zyEerqB_yBtsw62wB++=A4)*9StX;cW9#pnhV(5{w9H{sSLthy&~6AG zM8A08hR>3A#=KdtOsaD)(QS$?53TA2$XO35WId2XuDC(Q_eGD0g^88F;yNY_6!OsY zZ}RYAL<4fNXCnrhwnTEZtKFhhskD^*-H(Mj>jF(#TUpg0La>=RVqvfmwS1S%Jjf(c zl3_|yDU!Q}Uif4pZpddL3xmDL6cS=pq|S&GcsOHvP1HpD%Ud6h8)7Xi$WlU<-q0jT zW1b&g8Dd?>Vwp4R^cLP}etjktDH7k=y3lN&yA0Eq4795eyPe#)*t9UkK^2{%y>0vW%JP2IjAw^%hz|c|iEa&o=;M z_FUYszMrQxbgMK~}YLGrnvS}N)(ZN8OtN3@AXNohQljTUAXGdGnpFghM z%C|lZH!>EwWyPbiwJ0>n9Eq!Siu2}_u zvofa8(Vvk1VQOt4Jm?R_xIb8%?tMo3I|`}$noz*b6Wn&jQ1vj7-aPQpb?kCASGpa= zy!T7YAO&YnHMtXsm`%lLoH2vk;($>lvr_&T7JbSgdQz4tD+CG7m1ss#i28XDLFjbv z88jzt3hnw4SvW3q`hH&xcd!dZn*8I2XD7kGOEj;`cfmFt`RPQu%X#jHbsazucKoqc z%6AEFYC*DuQz|D(4M*o99d2Nt6$Q(Bta5-j@Oc%b=|sR>B;mkn=hvn@_VN9ZOQD`X z@E^!0wDlkCVu#Y(TaO;jgEm3Fn}ocG5TSn%5$QOZMAKVn#f@MX=LGBCltWWds2kL= zGVk0P3h{1}35+A;q3;%RZx1%c{f5?x4PPIujU&d$9`3)sYD0Vy?0ZW3qGZp-^X710 z_t+phT1QeEuhP!9jnOzfa8Z-AMHmsT1)@?<#?=@8&S zkSw$?qN$4ka~}4ca*%LU>k@O=lv}c%^GKG7u=7f74Hr|=zpB>K04`PHBRHVp8V0S9 zeQELLT03x3Md6Umd}Ls>Py+F&avTf>#y9fv9^ne!Gsk>e*ZY z{Fg{&I?h2(FA#17Pef5#(T+LJv0VTJQDOoSuLxI;_M15jvYXuANLTK&X3>E(qOuc4 z1FKTME^Y@$ttX}IjOHE)_XNb)wW|O;e*^m4JjM6K;=aK@Z`B8GfVGtlC;qtEjvqrfBJt32Y+_*C8C2lh)qqVqv;M z(6nV*$SZIsF7$12PXGa3|Dq!4;)_7IF!K5fGHbXBhL=~#PS_>I^8y#y(Yh&Q{7Sc! z+V?(ny2lE!ISp&#)Ht6(g`*%#d1d9k=tHB3Jn$lZe|=td#hcm!F)6XvfZJ)e*i{AP z517Lww<5W{sf5+|eRWnGghODA#+A(R6))))r^_O$TXtE>w7Z6{PRbJ_{~-;7NzMIA zE1FJ>pk5+pP_K8VxO~mMFI=DPNp=gb1lOhl&lcwHsuY-K>ACKxkiD*fg;FTnk`eUd95(-3k(| z(%Vet{UY!etFXZ%-EMgBuh0HIZ&aUT{BRzz|##NT5pU&(%W z?1?qVD3?yFM{P9PVJY*uVtQp|dReb&mhT70tM1fWtYVDVz;A;G$>)N;n_kz)0NmsNq;Dvx|?hlRpAWuW`kdvCaK-?O{J37LJ% zfa?c21yH&42-%tMim$3fO2G<}-FKIS#w)W@z#&RMFoyiqHeMxfVgd7(G=UZ_&X zmT-f>sRV9t>`Pj+upw!%mE6CGun^2v5RehU_h3W!ACKu{HRHs&awA{tX!UM1AMV{T<^Nh&E)aj!3FchUO-SAflmn0e1w4=cr?$(tmLY2FY| z1#h3T3l$|kfc8(nfo`HmE{9zq=O%>SevY~BrB_A>o|-}XLk;~O{f zZG>U)$NIYRon#65j(vnN`}jaPaP6~WZDy6StY{nR7R>!A*q!pQLHq`u1YK2o+uE@m z!BIOPv58knu7pF9koTUPZPJZ-j43~)mG6()#dDcUiz=)&T1P@ME!&k}vQx%jej-vO z@n7uw635mSFLF0cCq1Bw%FY?m$F#*xV+Onha8}UIh5|n^fPCx+Ie=7KEO#wlW}w7p zk5$$5!An7qmB;GX>^O$Ee{<7Elftx_$Ky+gmC%Bwhg_P(E% z*V}3FC!Q?QTR!_a)d!i!g5E3lVM&Vl|MuUV5`~%$?wL8(x&M*i&YuOIWz5{UOs)B7 zE55HH_703RPwCWP#b=jK-k8_F^K;Ri-9aH?zzZV&x+?->=kC?%n4vZ_igzP!oeq1#Q6=lNd-7h#FaSvtGw66AAf0;hX zuTMbCJ54%GYM6*mLIRYZ+#s}Rgg#4x>8r(;o{wNG@XnRtrtn)q-zRe!o$d4j#2ZR1 z=@xT_DazDkW)ha?4MieS+}tNPdC+yXIqN5ICh5}%r0rn_)9pzhRe@XnLV#-woSipZ zmK~^?hI3%_c!9hApL;M*pz`{c&M71fJd?DqxRYGRk+$z@V4i3oe}W?23qTZ}1TbVd zD6m7+R;L=}IgW#hk0g)L0N#X&!8@R?>M5c{~c0076)Z%Dg%+0tU#t z8O-%MP}?bLYf*#p1hsu_H#4X!&7FjwK-wMzwqFf{XUSq9A#^l=CJe2PxCKVAWLKa^ z0CdhOh9)o_y*k+Ss9d4;s>16}wQOZpk#zy``!4`lDFtU6^877x19J%+$R{bJVCEB0 z2~M(rdD8QcWs=?ga|cSpAOdi~^wk0}@P(*tNiE7V(^qidei+m*Vg?Jj0(1iLVW0>+ zdOU?VK zFu2JY;7+zAsqSBQ(h_(Gzq<#^$OafmtAlA9-XY5l05|oOq2Mqx82jQXp3-f1k``Fj zurvqE=0N{Ymbm{PaF}H|GW*+YO1^_~zSbn#HsGuhrFGj0#O8%(TDC8Kh}s6e0_C=R zcT)D3rPg~wd54xQc&2NIf|`OL42}efEPx^-GgvgdupGR(FVv!@%z%YCk|dK&xuluD z;x-`GS``!0he@reIQxpfT?_BjEn)TGjw{3;2-+V54-p0cP|WCXV&cG+WgpOD3JQX% zV$PVtw}8U8;JqI|1jVGUj#C;{A`C+V`m4i&1DG8?Sl^JZL+`8*{G|=p~pzy-_3lL2%4;6##D< zr%4AKFn89CLS^5Dj-KX?9R?b$f%{Qr&K#`Frd^)>075=V zL8Z=^JI6t=$pE`ME%<}~>v~#>5Oc!Zq5bVjnNB;@Qdf=vm2x)teB%Cct~L9N7tpL? zwZ!bPx(Q*u_ZQZ5psDkKO>m`AihbA zrwz(4c*_}0elERd53eBP&=>)Y_34s&s-RQMk2-YQL=>pdJmH8beE*=rgK9!oP7&M> z>6crC%{owN*f9IVo^6+;8y2wE(I{I++#-?xT8uAsdt4jKZj(+H{0dns-{5HtX3|>9 zFG>qKjYr;Muu5GYpDJuGUIh3A1o-|m0s;s?P(zGWxQMy2khGMx@N-m}&u`A{I?%%J z_Jw;63f-KrRO7CT@(|Wi;2)fM4ZZ>I00x@Acc-l1_f*Y~_jl194Pa$2fW4a`dAJ`8 zhx~$^)WEVy!0flf3yrcvNz_FwmG+*?xjob@CN{VVeuE30Gb z3$KAy*-nI2O?`ZH4NaE`Mf^xHOg@Yfno8vuj8l#&JQ3PSaQ&=F4-F+zGZHkFtd$)RX&9jpAdG)&tUk&(K;)G(Jg1EiETe5*LZ z$0aXGv<@$!v97)#`wJUgE-LQK-^|i*i~*Kt4JC3zG_iUW(0>_-JMP|NaK#@1KyE+!P>ws6N&k6WO5$ Q{;CDSI^rBE?fuXHA7hI;RR910 diff --git a/Realtime/Realtime/Realtime.csproj b/Realtime/Realtime/Realtime.csproj index 400a961..02da402 100644 --- a/Realtime/Realtime/Realtime.csproj +++ b/Realtime/Realtime/Realtime.csproj @@ -22,6 +22,8 @@ - + + ProjectReference + diff --git a/csharp-sdk.sln b/csharp-sdk.sln index 3ff4f70..00d45e8 100644 --- a/csharp-sdk.sln +++ b/csharp-sdk.sln @@ -33,12 +33,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine", "Engine\Engine.csp EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libs", "Libs", "{3B53EFFB-6962-4EED-88FD-F9D6E9650A2D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LC.Google.Protobuf", "Libs\Google.Protobuf\LC.Google.Protobuf.csproj", "{FA0E2CEC-4623-4119-92D9-12F2A4699F41}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LC.Newtonsoft.Json", "Libs\Newtonsoft.Json\LC.Newtonsoft.Json.csproj", "{AE39723C-03C3-423F-9086-9AA36B3587D1}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Storage.Test", "Storage\Storage.Test\Storage.Test.csproj", "{07B8BAE6-CA9A-48B0-9881-F63F1F5DCE70}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LC.Newtonsoft.Json", "Libs\Newtonsoft.Json\LC.Newtonsoft.Json.csproj", "{64BEB6ED-38BF-419C-9CC0-E08F0B4F36C8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LC.Google.Protobuf", "Libs\Google.Protobuf\LC.Google.Protobuf.csproj", "{B3BB497E-D654-4680-8312-ABCC12FFBBB2}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -81,18 +81,18 @@ Global {0A6AEBC9-9A36-4EA7-8F58-8B951126092D}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A6AEBC9-9A36-4EA7-8F58-8B951126092D}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A6AEBC9-9A36-4EA7-8F58-8B951126092D}.Release|Any CPU.Build.0 = Release|Any CPU - {FA0E2CEC-4623-4119-92D9-12F2A4699F41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FA0E2CEC-4623-4119-92D9-12F2A4699F41}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FA0E2CEC-4623-4119-92D9-12F2A4699F41}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA0E2CEC-4623-4119-92D9-12F2A4699F41}.Release|Any CPU.Build.0 = Release|Any CPU - {AE39723C-03C3-423F-9086-9AA36B3587D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AE39723C-03C3-423F-9086-9AA36B3587D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AE39723C-03C3-423F-9086-9AA36B3587D1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AE39723C-03C3-423F-9086-9AA36B3587D1}.Release|Any CPU.Build.0 = Release|Any CPU {07B8BAE6-CA9A-48B0-9881-F63F1F5DCE70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {07B8BAE6-CA9A-48B0-9881-F63F1F5DCE70}.Debug|Any CPU.Build.0 = Debug|Any CPU {07B8BAE6-CA9A-48B0-9881-F63F1F5DCE70}.Release|Any CPU.ActiveCfg = Release|Any CPU {07B8BAE6-CA9A-48B0-9881-F63F1F5DCE70}.Release|Any CPU.Build.0 = Release|Any CPU + {64BEB6ED-38BF-419C-9CC0-E08F0B4F36C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64BEB6ED-38BF-419C-9CC0-E08F0B4F36C8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64BEB6ED-38BF-419C-9CC0-E08F0B4F36C8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64BEB6ED-38BF-419C-9CC0-E08F0B4F36C8}.Release|Any CPU.Build.0 = Release|Any CPU + {B3BB497E-D654-4680-8312-ABCC12FFBBB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B3BB497E-D654-4680-8312-ABCC12FFBBB2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B3BB497E-D654-4680-8312-ABCC12FFBBB2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B3BB497E-D654-4680-8312-ABCC12FFBBB2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {4194FE34-327C-42C2-971F-6B07904E20A5} = {076871D0-BE1F-4AF0-B83E-697C71C0C3B3} @@ -104,9 +104,9 @@ Global {0F61B6D7-4948-4D98-B6CC-41CF33B55669} = {A1A24E0F-6901-4A9A-9BB8-4F586BC7EE17} {9D5E6A37-8925-48ED-B7EA-12C89291B59D} = {2D980281-F060-4363-AB7A-D4B6C30ADDBB} {0A6AEBC9-9A36-4EA7-8F58-8B951126092D} = {8087ABCD-629C-4EE5-9ECE-8BDAE631236F} - {FA0E2CEC-4623-4119-92D9-12F2A4699F41} = {3B53EFFB-6962-4EED-88FD-F9D6E9650A2D} - {AE39723C-03C3-423F-9086-9AA36B3587D1} = {3B53EFFB-6962-4EED-88FD-F9D6E9650A2D} {07B8BAE6-CA9A-48B0-9881-F63F1F5DCE70} = {076871D0-BE1F-4AF0-B83E-697C71C0C3B3} + {64BEB6ED-38BF-419C-9CC0-E08F0B4F36C8} = {3B53EFFB-6962-4EED-88FD-F9D6E9650A2D} + {B3BB497E-D654-4680-8312-ABCC12FFBBB2} = {3B53EFFB-6962-4EED-88FD-F9D6E9650A2D} EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution version = 0.7.1